aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
use std::collections::HashMap;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{
    atomic::{AtomicBool, AtomicU64, Ordering},
    mpsc, Arc, Mutex, OnceLock, Weak,
};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::{slog_debug, slog_error, slog_info, slog_warn};

/// Owns an already-acquired OS file lock, unlike the path/heartbeat lease below.
/// Closing a file alone can leave its lock held by a forked child's descriptor
/// until exec or exit. Explicitly unlock when the protected operation ends.
/// Keep one guard per acquisition; share the guard, not cloned file handles.
#[derive(Debug)]
pub struct AdvisoryLockGuard(File);

impl AdvisoryLockGuard {
    pub fn from_locked_file(file: File) -> Self {
        Self(file)
    }
}

impl Drop for AdvisoryLockGuard {
    fn drop(&mut self) {
        let _ = self.0.unlock();
    }
}

pub const HEARTBEAT_INTERVAL_MS: u64 = 5_000;
/// Successful refreshes need not rewrite every wake. Foreign hosts allow 75s
/// of silence, leaving 50s of scheduling/I/O headroom after a normal refresh.
/// Same-host readers use process identity, never heartbeat age, for takeover.
pub const HEARTBEAT_REFRESH_INTERVAL_MS: u64 = 25_000;
pub const STALE_HEARTBEAT_MS: u64 = 15_000;
pub const LIVE_OWNER_WARN_MS: u64 = 600_000;
pub const POLL_INTERVAL_MS: u64 = 100;

/// Max consecutive transient OS errors tolerated while creating the lock file
/// before giving up. On Windows, two processes/threads racing to create (or one
/// creating while another deletes) the same path can momentarily return
/// ERROR_ACCESS_DENIED (5) or ERROR_SHARING_VIOLATION (32) instead of a clean
/// "already exists". Those windows close in milliseconds, so a small bounded
/// retry rides them out while a genuinely persistent permission/IO failure still
/// surfaces promptly.
const MAX_TRANSIENT_CREATE_RETRIES: u32 = 50;
const RECLAIM_TOKEN_MALFORMED_STALE_AGE: Duration = Duration::from_secs(60);
const RECLAIM_BLOCK_LOG_INTERVAL: Duration = Duration::from_secs(60);
const DEAD_RECLAIM_INITIAL_BACKOFF_MS: u64 = 250;
const DEAD_RECLAIM_MAX_BACKOFF_MS: u64 = 5_000;

/// A heartbeat normally keeps one descriptor per lease open between beats
/// instead of opening and closing the file on every beat. Closing a lease
/// descriptor is expensive on the live daemon: it pulls the write-back of the
/// lease page into the closing thread, and with hundreds of long-lived leases on
/// macOS that was 10% of a core. The handle is released only when this process
/// replaces the lease, or when a beat finds the lease no longer its own. These
/// entries let those replacements find the open handles; acquisition, ownership
/// checks and reclaim paths on other threads keep their own short-lived opens.
static NEXT_LEASE_SLOT: AtomicU64 = AtomicU64::new(0);
static LEASE_FILES: OnceLock<Mutex<HashMap<usize, LeaseSlot>>> = OnceLock::new();
static LEASE_SLOT_BY_PATH: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();

/// One heartbeat handle, filed under the slot that owns it and, in
/// `LEASE_SLOT_BY_PATH`, under the lease path it was opened for. The path entry
/// is what lets a replacement release the handle for *its* lease without
/// touching any other lease's handle.
#[derive(Clone)]
struct LeaseSlot {
    handle: Weak<Mutex<Option<LeaseFile>>>,
}

// Lock files in these storage domains have the fixed layout
// `<storage>/<domain>/<key>/<lock>`. Add a domain here when a new persistent
// artifact lock is introduced. BackupStore's deeper `.locks` shape is handled
// separately so maintenance never walks backup entry histories.
// compress::trust owns this one lock directly under the storage root.
// BackupStore scopes locks below each harness and session. Prefixes cover the
// client-specific MCP and fingerprint-specific federated harness directories.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReclaimTokenState {
    Alive,
    DeadForeignHost,
    Malformed,
    Dead,
}

impl ReclaimTokenState {
    fn as_str(self) -> &'static str {
        match self {
            Self::Alive => "alive",
            Self::DeadForeignHost => "dead-foreign-host",
            Self::Malformed => "malformed",
            Self::Dead => "dead",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ReclaimTokenHeld {
    pid: Option<u32>,
    state: ReclaimTokenState,
}

#[derive(Debug)]
enum ReclaimResult {
    Removed,
    Blocked(ReclaimTokenHeld),
    Unchanged,
}

#[derive(Clone, Debug)]
struct ReclaimBlockLogRecord {
    last_emitted: Instant,
    suppressed: u64,
}

/// Which live-owner conditions one acquisition already reported, so a single
/// attempt that polls many times (a daemon waiting on its own long-lived lease)
/// logs each condition once instead of on every poll.
#[derive(Clone, Debug, Default)]
struct LiveOwnerLogRecord {
    stale_logged: bool,
    long_held_logged: bool,
}

/// Per-acquisition record of which live-owner conditions it already reported.
struct LiveOwnerLog {
    record: LiveOwnerLogRecord,
}

impl LiveOwnerLog {
    fn new() -> Self {
        Self {
            record: LiveOwnerLogRecord::default(),
        }
    }

    fn first_stale(&mut self) -> bool {
        !std::mem::replace(&mut self.record.stale_logged, true)
    }

    fn first_long_held(&mut self) -> bool {
        !std::mem::replace(&mut self.record.long_held_logged, true)
    }
}

static RECLAIM_BLOCK_LOGS: OnceLock<Mutex<HashMap<PathBuf, ReclaimBlockLogRecord>>> =
    OnceLock::new();

/// True for OS errors that mean "another actor is touching this exact lock path
/// right now", as opposed to a real, persistent failure. On Windows a contended
/// create/delete on the same file surfaces as ERROR_ACCESS_DENIED (5) or
/// ERROR_SHARING_VIOLATION (32); `PermissionDenied` covers the former across
/// platforms. These are retried as contention, never treated as fatal.
fn is_transient_create_contention(error: &io::Error) -> bool {
    if error.kind() == io::ErrorKind::PermissionDenied {
        return true;
    }
    #[cfg(windows)]
    {
        // ERROR_SHARING_VIOLATION = 32. ERROR_ACCESS_DENIED = 5 maps to
        // PermissionDenied above, but match it explicitly too in case the OS
        // surfaces it as an Other-kind raw error.
        if let Some(code) = error.raw_os_error() {
            if code == 32 || code == 5 {
                return true;
            }
        }
    }
    false
}

#[derive(Clone, Copy, Debug)]
struct LockConfig {
    heartbeat_interval_ms: u64,
    heartbeat_refresh_interval_ms: u64,
    stale_heartbeat_ms: u64,
    live_owner_warn_ms: u64,
    poll_interval_ms: u64,
}

impl LockConfig {
    fn cross_host_stale_heartbeat_ms(self) -> u64 {
        self.stale_heartbeat_ms.saturating_mul(5)
    }

    fn live_owner_warning_age_ms(self) -> u64 {
        // A healthy lease can now be older than the old warning window. Allow
        // one wake of jitter without changing the foreign-host takeover bound.
        self.stale_heartbeat_ms.max(
            self.heartbeat_refresh_interval_ms
                .saturating_add(self.heartbeat_interval_ms),
        )
    }
}

impl Default for LockConfig {
    fn default() -> Self {
        Self {
            heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
            heartbeat_refresh_interval_ms: HEARTBEAT_REFRESH_INTERVAL_MS,
            stale_heartbeat_ms: STALE_HEARTBEAT_MS,
            live_owner_warn_ms: LIVE_OWNER_WARN_MS,
            poll_interval_ms: POLL_INTERVAL_MS,
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
#[derive(Clone, Debug, PartialEq, Eq)]
struct ProcessIdentity {
    #[cfg(any(test, feature = "test-support"))]
    pub start_time: u64,
    #[cfg(not(any(test, feature = "test-support")))]
    start_time: u64,
    boot_id: Option<String>,
    #[cfg(any(test, feature = "test-support"))]
    pub exited: bool,
    #[cfg(not(any(test, feature = "test-support")))]
    exited: bool,
}
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
struct LockMetadata {
    pid: u32,
    hostname: String,
    /// Identifies this PID incarnation so a process in a restarted PID namespace
    /// cannot be mistaken for an owner that was hard-killed in an earlier launch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    process_start_time: Option<u64>,
    /// Linux start times are relative to boot. Keeping the boot ID alongside the
    /// raw jiffies prevents a reboot from making a newly recycled PID look like
    /// an earlier owner whose start time happened to match.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    boot_id: Option<String>,
    created_at_ms: u64,
    heartbeat_at_ms: u64,
    /// Fencing nonce for writer leases. The owner re-reads the lock immediately
    /// before publishing/writing and aborts if a stale guard has been usurped.
    #[serde(default)]
    writer_epoch: String,
}

/// Acquire a filesystem lock at `path`. Blocks until the lock is held.
///
/// The returned guard owns a background heartbeat thread; dropping it releases
/// the lock and removes the lock file.
pub fn acquire(path: &Path) -> Result<LockGuard, AcquireError> {
    acquire_with_config(path, None, LockConfig::default())
}

/// Try to acquire a filesystem lock at `path` within `timeout`.
pub fn try_acquire(path: &Path, timeout: Duration) -> Result<LockGuard, AcquireError> {
    acquire_with_config(path, Some(timeout), LockConfig::default())
}

/// Preserve a caller's deadline across filesystem preparation instead of
/// starting a fresh timeout after that work has finished. Always allow the
/// first attempt: slow preparation does not imply another writer owns the lock.
pub fn try_acquire_until(path: &Path, deadline: Instant) -> Result<LockGuard, AcquireError> {
    crate::production_storage::refuse_write(path)?;
    #[cfg(any(test, feature = "test-support"))]
    retry_clock::before_acquire();
    acquire_with_deadline(path, Some(deadline), false, true, LockConfig::default())
}

/// Try one lock acquisition attempt, then check once whether an existing stale
/// lock can be taken over.
///
/// Read-only cache openers use this to switch to writer mode without waiting
/// behind another process that is still building the cache. Malformed leases
/// receive one poll interval of grace so a creator can finish writing before
/// the existing guarded reclaim path is tried.
pub fn try_acquire_once(path: &Path) -> Result<LockGuard, AcquireError> {
    try_acquire(path, Duration::ZERO)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LockAvailability {
    Available,
    LiveOwner,
    Stale,
    Malformed,
}

enum ObservedLock {
    Available,
    LiveOwner(LockMetadata),
    Stale(LockMetadata),
    Malformed(serde_json::Error),
}

impl ObservedLock {
    fn availability(&self) -> LockAvailability {
        match self {
            Self::Available => LockAvailability::Available,
            Self::LiveOwner(_) => LockAvailability::LiveOwner,
            Self::Stale(_) => LockAvailability::Stale,
            Self::Malformed(_) => LockAvailability::Malformed,
        }
    }
}

/// Observe the same lease states used by acquisition, without taking a lock.
/// Malformed contents are not proof of a dead owner: acquisition must still
/// perform its grace-period reread and guarded reclaim. I/O failures remain
/// errors rather than evidence about ownership.
pub fn lock_availability(path: &Path) -> io::Result<LockAvailability> {
    observe_lock(path, &current_hostname(), LockConfig::default())
        .map(|observed| observed.availability())
}

fn observe_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<ObservedLock> {
    match read_lock_metadata(path) {
        Ok(metadata) => {
            if metadata_blocks_acquisition(&metadata, hostname, config, now_ms()) {
                Ok(ObservedLock::LiveOwner(metadata))
            } else {
                Ok(ObservedLock::Stale(metadata))
            }
        }
        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
            Ok(ObservedLock::Available)
        }
        Err(ReadLockError::Io(error)) => Err(error),
        Err(ReadLockError::Malformed(error)) => Ok(ObservedLock::Malformed(error)),
    }
}

fn metadata_blocks_acquisition(
    metadata: &LockMetadata,
    hostname: &str,
    config: LockConfig,
    now: u64,
) -> bool {
    if metadata.hostname != hostname {
        now.saturating_sub(metadata.heartbeat_at_ms) <= config.cross_host_stale_heartbeat_ms()
    } else {
        lock_owner_is_alive(metadata)
    }
}

pub struct LockGuard {
    path: PathBuf,
    metadata: LockMetadata,
    shutdown: Arc<AtomicBool>,
    heartbeat_failed: Arc<AtomicBool>,
    heartbeat_done: mpsc::Receiver<()>,
    heartbeat: Option<JoinHandle<()>>,
    pump: HeartbeatPump,
    /// The heartbeat thread's handle on the lease, shared with it so the guard
    /// can close it before any replacement of the lease and so this process's
    /// lease index can tell other threads to wait for it.
    heartbeat_file: Arc<Mutex<Option<LeaseFile>>>,
}

impl LockGuard {
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn writer_epoch(&self) -> &str {
        &self.metadata.writer_epoch
    }

    /// Whether this guard's heartbeat is still running. `verify_writer_epoch`
    /// treats a guard whose heartbeat stopped as unverified, because nothing
    /// else would keep the lease's heartbeat fresh for other processes.
    pub(crate) fn heartbeat_is_visible(&self) -> bool {
        self.pump.is_visible()
    }

    /// Refresh this lease once through the guard's own handle, so a same-length
    /// beat costs one write and no descriptor open or close. Tests use this to
    /// drive beats from a single thread; runtime beats go through the pump.
    #[cfg(any(test, feature = "test-support"))]
    #[cfg_attr(not(test), allow(dead_code))]
    fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
        heartbeat_once(&self.path, &self.metadata, &self.heartbeat_file)
    }

    /// Re-read the lock file and confirm that this guard still owns the writer
    /// token. Writers call this right before saving published data or starting
    /// SQLite writes so they stop if another process has taken over the lock.
    pub fn verify_writer_epoch(&self) -> io::Result<bool> {
        if self.heartbeat_failed.load(Ordering::Acquire) || !self.heartbeat_is_visible() {
            return Ok(false);
        }
        match read_lock_metadata(&self.path) {
            Ok(metadata) => Ok(lock_identity_matches(&metadata, &self.metadata)),
            Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(false),
            Err(ReadLockError::Io(error)) => Err(error),
            Err(ReadLockError::Malformed(_)) => Ok(false),
        }
    }
    #[rustfmt::skip]
    test_support_visibility! {
    /// Stop and join the heartbeat, closing its kept descriptor without
    /// unlinking the lease. Retention uses this immediately before moving or
    /// removing a cache tree: Windows cannot rename a directory containing an
    /// open lease file. The lease remains on disk and excludes other writers
    /// during the move; the guard must be dropped after the operation, even on
    /// error. Do not stop it early: remote hosts still rely on heartbeat age.
    pub(crate) fn stop_heartbeat_for_removal(&mut self) {
        // Signal shutdown then unconditionally join the heartbeat thread
        // BEFORE removing the lockfile. The earlier `recv_timeout(100ms)`
        // implementation could let `remove_lock_if_owned` race with a
        // still-alive heartbeat:
        //
        //   1. Drop signals shutdown, ack times out under CI load.
        //   2. Drop calls `remove_lock_if_owned` → file removed.
        //   3. Another caller acquires the lock → writes its metadata.
        //   4. Our heartbeat (still alive, mid-rewrite
        //      from before shutdown was checked) overwrites the new
        //      owner's file with our stale metadata. heartbeat_once's
        //      ownership check happens BEFORE the write, so it can race
        //      with a concurrent acquire that flips ownership in between.
        //   5. The new owner's heartbeat sees foreign metadata, exits
        //      `NotOwner`. The new owner's drop sees foreign metadata,
        //      `remove_lock_if_owned` returns `Ok(false)`, file persists.
        //
        // Always-joining bounds drop latency to one `park_timeout`
        // iteration (~25ms) plus the current `heartbeat_once` IO —
        // typically <500ms under CI load. The unused `heartbeat_done`
        // channel is kept for backward compatibility with any external
        // code that may still construct LockGuard manually, but Drop no
        // longer relies on it.
        self.shutdown.store(true, Ordering::Release);
        if let Some(handle) = self.heartbeat.take() {
            handle.thread().unpark();
            let _ = handle.join();
        }
        // Drain any pending ack so the receiver doesn't carry stale state
        // if this LockGuard is somehow re-used (it isn't today, but be
        // defensive).
        while self.heartbeat_done.try_recv().is_ok() {}

        // Release the heartbeat handle before the lease file: closing any other
        // descriptor to it now would drop the advisory locks this process holds
        // on it, so the unlink and any concurrent replacement wait for this.
        let mut handle = self
            .heartbeat_file
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *handle = None;
        drop(handle);
        // Stop publishing the slot so a later replacement for this path never
        // waits on this guard's closed handle.
        unregister_lease_slot(self.pump.slot, &self.path);
        self.pump.visible.store(false, Ordering::Release);
    }

    }
}

impl Drop for LockGuard {
    fn drop(&mut self) {
        self.stop_heartbeat_for_removal();
        match remove_lock_if_owned(&self.path, &self.metadata) {
            Ok(true) => slog_debug!("released filesystem lock at {}", self.path.display()),
            Ok(false) => {}
            Err(error) => slog_warn!(
                "failed to release filesystem lock at {}: {}",
                self.path.display(),
                error
            ),
        }
    }
}

/// Run `replace`, a replacement of a lease file, after releasing the heartbeat
/// handles this process publishes for leases.
///
/// Closing one descriptor to a file drops *all* the POSIX advisory locks this
/// process holds on it, including on a descriptor another thread still keeps.
/// A heartbeat holds its lease open between beats, so the process must not leave
/// that descriptor to be closed by a replacement: this takes each published
/// handle, drops the descriptor, and holds the handle's lock across `replace`.
/// Because the guards are taken before the lock is released, a beat cannot open
/// a lease into a slot this call is holding; a beat waits for the replacement
/// and then opens the live file.
fn with_lease_handles_closed<T>(
    path: &Path,
    replace: impl FnOnce() -> io::Result<T>,
) -> io::Result<T> {
    // Only this path's handle. Releasing every published handle would empty
    // another lease's slot, and its next beat would reopen the file, giving
    // back the per-beat descriptor churn the kept handle exists to avoid.
    let slot = lease_slots_by_path()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .get(path)
        .copied();
    let handle = slot.and_then(|slot| {
        lease_files()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .get(&slot)
            .and_then(|entry| entry.handle.upgrade())
    });
    // Take the handle without waiting. A held lock means the heartbeat is
    // mid-beat on this lease (or the caller is the beat itself), and a beat that
    // already holds the descriptor keeps its own safety: it re-checks the path's
    // identity and the owner before every write. Waiting here would deadlock
    // against the very thread that has to finish the beat.
    let mut released = Vec::new();
    for handle in handle.iter() {
        let Ok(mut slot) = handle.try_lock() else {
            continue;
        };
        *slot = None;
        released.push(slot);
    }
    let result = replace();
    drop(released);
    result
}

#[derive(Debug)]
pub enum AcquireError {
    Io(io::Error),
    Timeout,
}

impl fmt::Display for AcquireError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AcquireError::Io(error) => write!(f, "filesystem lock I/O error: {error}"),
            AcquireError::Timeout => write!(f, "timed out acquiring filesystem lock"),
        }
    }
}

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

impl From<io::Error> for AcquireError {
    fn from(error: io::Error) -> Self {
        AcquireError::Io(error)
    }
}

fn acquire_with_config(
    path: &Path,
    timeout: Option<Duration>,
    config: LockConfig,
) -> Result<LockGuard, AcquireError> {
    crate::production_storage::refuse_write(path)?;
    #[cfg(any(test, feature = "test-support"))]
    retry_clock::before_acquire();
    let deadline = timeout.map(|timeout| acquisition_now() + timeout);
    acquire_with_deadline(
        path,
        deadline,
        timeout == Some(Duration::ZERO),
        false,
        config,
    )
}

fn acquire_with_deadline(
    path: &Path,
    deadline: Option<Instant>,
    allow_malformed_grace: bool,
    strict_deadline: bool,
    config: LockConfig,
) -> Result<LockGuard, AcquireError> {
    let hostname = current_hostname();
    // Report a live blocking owner once, not once per poll this acquisition
    // makes: a daemon with many roots re-attempts its own long-lived leases
    // constantly, and every attempt would otherwise repeat the same warning.
    let mut live_owner_log = LiveOwnerLog::new();
    let mut transient_create_failures: u32 = 0;
    let mut attempted_once = false;
    let mut dead_reclaim_blocked_attempts = 0_u32;
    // A zero-timeout acquire still gets one immediate retry after it removes a
    // stale lock; otherwise it would reap the dead owner and report Timeout.
    let mut immediate_retry_budget = 0_u8;
    let mut malformed_grace_used = false;

    loop {
        if attempted_once {
            if immediate_retry_budget > 0 && !strict_deadline {
                immediate_retry_budget -= 1;
            } else if let Some(deadline) = deadline {
                if acquisition_now() >= deadline {
                    return Err(AcquireError::Timeout);
                }
            }
        }
        attempted_once = true;
        #[cfg(any(test, feature = "test-support"))]
        retry_clock::note_attempt();

        match create_new_lock(path, &hostname, config) {
            Ok(guard) => return Ok(guard),
            // The lock file already exists — fall through to inspect its owner.
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
            // Transient contention (chiefly Windows: a concurrent create/delete
            // on this exact path surfaces as access-denied/sharing-violation
            // rather than already-exists). Back off one poll interval and retry,
            // bounded so a persistent failure still propagates instead of
            // spinning forever.
            Err(error) if is_transient_create_contention(&error) => {
                transient_create_failures += 1;
                if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
                    return Err(error.into());
                }
                sleep_until_retry(deadline, config.poll_interval_ms)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        }
        transient_create_failures = 0;

        let observed = match observe_lock(path, &hostname, config) {
            Ok(observed) => observed,
            // The same Windows contention the create arm above tolerates can
            // land here instead: a lock file pending deletion is visible to
            // the create attempt but denies the open that reads it. Only the
            // create path recognised that spelling of "busy", so a race that
            // was meant to be retried propagated as a hard failure and
            // panicked a caller mid-write (Windows CI, 2026-09-22).
            Err(error) if is_transient_create_contention(&error) => {
                transient_create_failures += 1;
                if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
                    return Err(error.into());
                }
                sleep_until_retry(deadline, config.poll_interval_ms)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let availability = observed.availability();
        let metadata = match observed {
            ObservedLock::LiveOwner(metadata) | ObservedLock::Stale(metadata) => metadata,
            ObservedLock::Available => {
                immediate_retry_budget = 1;
                continue;
            }
            ObservedLock::Malformed(error) => {
                // A just-created O_EXCL file is visible before its owner has
                // finished writing JSON. Give that transient creation window
                // one poll interval before treating malformed contents as stale.
                // Zero-timeout callers also need this one grace read to reach
                // reclaim, but must not loop if another actor keeps corrupting
                // the lease or prevents its removal.
                if allow_malformed_grace && !malformed_grace_used {
                    malformed_grace_used = true;
                    sleep_until_retry(None, config.poll_interval_ms)?;
                } else {
                    sleep_until_retry(deadline, config.poll_interval_ms)?;
                }
                match read_lock_metadata(path) {
                    Ok(_) => continue,
                    Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
                        continue;
                    }
                    Err(ReadLockError::Io(error)) => return Err(error.into()),
                    Err(ReadLockError::Malformed(_)) => {}
                }
                slog_warn!(
                    "removing malformed filesystem lock at {}: {}",
                    path.display(),
                    error
                );
                let judged = fs::read(path)?;
                if serde_json::from_slice::<LockMetadata>(&judged).is_ok() {
                    continue;
                }
                #[cfg(any(test, feature = "test-support"))]
                run_acquisition_hook(&BEFORE_MALFORMED_RECLAIM);
                if reclaim_malformed_lock(path, &judged)? {
                    immediate_retry_budget = 1;
                }
                continue;
            }
        };

        let now = now_ms();
        let since_heartbeat = now.saturating_sub(metadata.heartbeat_at_ms);

        if metadata.hostname != hostname {
            dead_reclaim_blocked_attempts = 0;
            let cross_host_stale_ms = config.cross_host_stale_heartbeat_ms();
            if availability == LockAvailability::Stale {
                match reclaim_lock_file(path, &metadata)? {
                    ReclaimResult::Removed => {
                        slog_warn!(
                            "reclaimed cross-host filesystem lock at {} from host {} after stale heartbeat ({}ms > {}ms)",
                            path.display(),
                            metadata.hostname,
                            since_heartbeat,
                            cross_host_stale_ms
                        );
                        immediate_retry_budget = 1;
                    }
                    ReclaimResult::Blocked(holder) => {
                        log_reclaim_blocked(path, &holder);
                        sleep_until_retry(deadline, config.poll_interval_ms)?;
                    }
                    ReclaimResult::Unchanged => {
                        sleep_until_retry(deadline, config.poll_interval_ms)?;
                    }
                }
                continue;
            }
            sleep_until_retry(deadline, config.poll_interval_ms)?;
            continue;
        }

        if availability == LockAvailability::Stale {
            match reclaim_lock_file(path, &metadata)? {
                ReclaimResult::Removed => {
                    slog_info!(
                        "removing filesystem lock at {} from dead or recycled PID {}",
                        path.display(),
                        metadata.pid
                    );
                    immediate_retry_budget = 1;
                    dead_reclaim_blocked_attempts = 0;
                }
                ReclaimResult::Blocked(holder) => {
                    log_reclaim_blocked(path, &holder);
                    let backoff_ms = dead_reclaim_backoff_ms(
                        dead_reclaim_blocked_attempts,
                        config.poll_interval_ms,
                    );
                    dead_reclaim_blocked_attempts = dead_reclaim_blocked_attempts.saturating_add(1);
                    sleep_until_retry(deadline, backoff_ms)?;
                }
                ReclaimResult::Unchanged => {
                    dead_reclaim_blocked_attempts = 0;
                    sleep_until_retry(deadline, config.poll_interval_ms)?;
                }
            }
            continue;
        }
        dead_reclaim_blocked_attempts = 0;

        if since_heartbeat > config.live_owner_warning_age_ms() && live_owner_log.first_stale() {
            // Same-host PID plus start-time identity is authoritative. A
            // SIGSTOP'd process, suspended VM, or sleeping laptop can miss
            // heartbeats and later resume inside the critical section. Breaking
            // that lock would allow split-brain writers, so a paused matching
            // owner blocks acquirers until it resumes and releases the lock or
            // dies. PID namespaces restart numbering after hard-killed owners,
            // which turns this safety rule into a deadlock unless the start time
            // distinguishes the unrelated process that reused the PID.
            slog_warn!(
                "filesystem lock at {} held by live PID {} has stale heartbeat ({}ms); NOT breaking",
                path.display(),
                metadata.pid,
                since_heartbeat
            );
        }

        let held_for = now.saturating_sub(metadata.created_at_ms);
        if held_for > config.live_owner_warn_ms && live_owner_log.first_long_held() {
            if metadata.pid == std::process::id() {
                // A lease this process holds and keeps heartbeating is a
                // long-lived writer (an inspect or callgraph writer lease lives
                // as long as its cache), so nothing is wrong and nothing is at
                // risk. Report it at debug level so the acquisition trace still
                // shows why it is waiting.
                slog_debug!(
                    "filesystem lock at {} is held by a live lease of this process for >10min; \
                     waiting without breaking it",
                    path.display()
                );
            } else {
                slog_warn!(
                    "filesystem lock at {} held >10min by live heartbeating PID {}; NOT breaking",
                    path.display(),
                    metadata.pid
                );
            }
        }

        sleep_until_retry(deadline, config.poll_interval_ms)?;
    }
}

fn create_new_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<LockGuard> {
    // Anchor the first deadline before publication, not when the new thread
    // eventually gets CPU time. A late-starting thread must refresh immediately.
    let first_refresh =
        Instant::now() + Duration::from_millis(config.heartbeat_refresh_interval_ms);
    let now = now_ms();
    let pid = std::process::id();
    let process_identity = process_identity(pid);
    let metadata = LockMetadata {
        pid,
        hostname: hostname.to_string(),
        process_start_time: process_identity
            .as_ref()
            .map(|identity| identity.start_time),
        boot_id: process_identity.and_then(|identity| identity.boot_id),
        created_at_ms: now,
        heartbeat_at_ms: now,
        writer_epoch: format!("{pid}-{}", now_nanos()),
    };

    create_lock_file_atomically(path, &metadata)?;

    let (heartbeat_pump, heartbeat_file) =
        HeartbeatPump::attach(path, &metadata).inspect_err(|_| {
            let _ = remove_lock_if_owned(path, &metadata);
        })?;

    let shutdown = Arc::new(AtomicBool::new(false));
    let heartbeat_failed = Arc::new(AtomicBool::new(false));
    let (done_tx, done_rx) = mpsc::channel();
    let heartbeat_path = path.to_path_buf();
    let heartbeat_shutdown = Arc::clone(&shutdown);
    let heartbeat_failed_for_thread = Arc::clone(&heartbeat_failed);
    let heartbeat_pump_for_thread = heartbeat_pump.clone();
    let heartbeat = spawn_heartbeat(move || {
        let heartbeat_shutdown_for_run = Arc::clone(&heartbeat_shutdown);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_heartbeat(
                heartbeat_path,
                &heartbeat_pump_for_thread,
                heartbeat_shutdown_for_run,
                config,
                first_refresh,
            );
        }));
        if result.is_err() || !heartbeat_shutdown.load(Ordering::Acquire) {
            heartbeat_failed_for_thread.store(true, Ordering::Release);
        }
        let _ = done_tx.send(());
    })
    .inspect_err(|_| {
        // Thread creation failed after publication; do not strand this PID's
        // lease, or unlink a replacement that no longer has our epoch.
        let _ = remove_lock_if_owned(path, &metadata);
    })?;

    slog_debug!("acquired filesystem lock at {}", path.display());
    #[cfg(any(test, feature = "test-support"))]
    io_ledger::record(|ledger| ledger.acquisitions += 1);

    Ok(LockGuard {
        path: path.to_path_buf(),
        metadata,
        shutdown,
        heartbeat_failed,
        heartbeat_done: done_rx,
        heartbeat: Some(heartbeat),
        pump: heartbeat_pump,
        heartbeat_file,
    })
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    pub static BEFORE_MALFORMED_RECLAIM: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
    pub static BEFORE_HEARTBEAT_SPAWN_FAILURE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}

#[cfg(any(test, feature = "test-support"))]
fn run_acquisition_hook(
    hook: &'static std::thread::LocalKey<std::cell::RefCell<Option<Box<dyn FnOnce()>>>>,
) -> bool {
    let action = hook.with(|slot| slot.borrow_mut().take());
    if let Some(action) = action {
        action();
        true
    } else {
        false
    }
}

fn spawn_heartbeat(run: impl FnOnce() + Send + 'static) -> io::Result<thread::JoinHandle<()>> {
    #[cfg(any(test, feature = "test-support"))]
    if run_acquisition_hook(&BEFORE_HEARTBEAT_SPAWN_FAILURE) {
        return Err(io::Error::other("injected heartbeat spawn failure"));
    }
    thread::Builder::new()
        .name("aft-fs-lock-heartbeat".to_string())
        .spawn(run)
}

fn run_heartbeat(
    path: PathBuf,
    pump: &HeartbeatPump,
    shutdown: Arc<AtomicBool>,
    config: LockConfig,
    mut next_refresh: Instant,
) {
    // Number of consecutive retry intervals before the warning window elapses.
    // Local takeover still requires proof of a dead or recycled process.
    // Beyond this point a sustained failure is genuinely dangerous, so we
    // escalate the log from warn to error — but we still keep retrying.
    let stale_intervals = config
        .stale_heartbeat_ms
        .checked_div(config.heartbeat_interval_ms.max(1))
        .unwrap_or(3)
        .max(1);
    let mut consecutive_transient_failures: u64 = 0;
    let refresh_interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);

    loop {
        if shutdown.load(Ordering::Acquire) {
            return;
        }

        match refresh_heartbeat_if_due(pump, &mut next_refresh, refresh_interval, Instant::now()) {
            Ok(false) => {}
            Ok(true) => {
                if consecutive_transient_failures > 0 {
                    slog_info!(
                        "filesystem lock at {} heartbeat recovered after {} transient failure(s)",
                        path.display(),
                        consecutive_transient_failures
                    );
                    consecutive_transient_failures = 0;
                }
            }
            Err(error) if heartbeat_error_is_terminal(&error) => {
                // Terminal states: the lock is provably gone or owned by
                // someone else. Continuing to write would clobber a new owner's
                // metadata (the exact race documented in LockGuard::drop), so
                // stop heartbeating.
                #[cfg(any(test, feature = "test-support"))]
                pump.mark_stopped();
                slog_error!(
                    "{}; stopping heartbeat",
                    terminal_heartbeat_message(&path, &error)
                );
                return;
            }
            Err(error) => {
                // Transient states: a temporary I/O hiccup (disk/NFS blip,
                // quota) or a read that raced a concurrent writer mid-write
                // (momentarily unparseable file). A single such error must NOT
                // permanently kill the heartbeat — that would silently stop
                // refreshing heartbeat_at_ms while the guard holder keeps
                // running its critical section, letting another process reclaim
                // the lock after the stale window and produce concurrent
                // writers. Log and retry on the next interval; a later success
                // resumes heartbeating automatically.
                consecutive_transient_failures += 1;
                log_transient_heartbeat_failure(
                    &path,
                    &transient_heartbeat_reason(&error),
                    consecutive_transient_failures,
                    stale_intervals,
                );
            }
        }
        thread::park_timeout(Duration::from_millis(config.heartbeat_interval_ms));
    }
}

fn refresh_heartbeat_if_due(
    pump: &HeartbeatPump,
    next_refresh: &mut Instant,
    interval: Duration,
    now: Instant,
) -> Result<bool, HeartbeatError> {
    if now < *next_refresh {
        return Ok(false);
    }
    // A delayed wake refreshes immediately. Only success advances the deadline,
    // so transient failures retry at the short wake cadence, not another 25s.
    pump.heartbeat_once()?;
    *next_refresh = now + interval;
    Ok(true)
}

/// A heartbeat failure is terminal when the lock is provably no longer ours to
/// refresh: it was removed (`LockGone`) or a different owner now holds it
/// (`NotOwner`). I/O and malformed-read failures are treated as transient —
/// they are typically temporary disk/NFS hiccups or a read that raced a
/// concurrent writer — so the heartbeat retries rather than dying.
fn heartbeat_error_is_terminal(error: &HeartbeatError) -> bool {
    matches!(
        error,
        HeartbeatError::LockGone | HeartbeatError::NotOwner | HeartbeatError::NotPumped
    )
}

fn terminal_heartbeat_message(path: &Path, error: &HeartbeatError) -> String {
    match error {
        HeartbeatError::LockGone => {
            format!("filesystem lock at {} disappeared", path.display())
        }
        HeartbeatError::NotOwner => format!(
            "filesystem lock at {} is no longer owned by this guard",
            path.display()
        ),
        HeartbeatError::NotPumped => format!(
            "filesystem lock at {} heartbeat handle was released by this process",
            path.display()
        ),
        // Not reachable for non-terminal errors, but keep a sensible string.
        HeartbeatError::Io(error) => {
            format!("filesystem lock at {} I/O error: {error}", path.display())
        }
        HeartbeatError::Malformed(error) => {
            format!(
                "filesystem lock at {} became malformed: {error}",
                path.display()
            )
        }
    }
}

fn transient_heartbeat_reason(error: &HeartbeatError) -> String {
    match error {
        HeartbeatError::Io(error) => format!("I/O error: {error}"),
        HeartbeatError::Malformed(error) => format!("became malformed: {error}"),
        HeartbeatError::LockGone => "lock disappeared".to_string(),
        HeartbeatError::NotOwner => "lock no longer owned".to_string(),
        HeartbeatError::NotPumped => "heartbeat handle released".to_string(),
    }
}

/// Log a transient heartbeat failure, escalating to error exactly once when the
/// failures have lasted long enough that the lock is now reclaimable by another
/// owner. Beyond that point we stay quiet to avoid log spam while still
/// retrying — the holder has already been warned the lock is at risk.
fn log_transient_heartbeat_failure(
    path: &Path,
    reason: &str,
    consecutive_failures: u64,
    stale_intervals: u64,
) {
    if consecutive_failures < stale_intervals {
        slog_warn!(
            "transient failure to heartbeat filesystem lock at {}: {}; retrying (attempt {})",
            path.display(),
            reason,
            consecutive_failures
        );
    } else if consecutive_failures == stale_intervals {
        slog_error!(
            "filesystem lock at {} has failed {} consecutive heartbeats: {}; \
             the lock may now be reclaimed by another owner — continuing to retry",
            path.display(),
            consecutive_failures,
            reason
        );
    }
}

/// The heartbeat thread's handle on one lease.
///
/// The thread keeps the lease open between beats so a beat costs one write
/// instead of an open, a read and a close. A `File` released on its own thread
/// closes there, and on macOS the close is where the lease's write-back runs,
/// so per-beat close/open churn put the write-back cost on the heartbeat
/// thread. Three rules bound how long the handle lives:
///
/// * Another thread of this process that has to replace the lease needs every
///   handle to it released first (`LEASE_FILES`), because closing any
///   descriptor to a file drops the advisory locks this process holds on it.
///   That is why the replacement paths close before they rename.
/// * A beat never trusts the handle blindly. Before reading it compares the
///   file the handle refers to with the file the path now names (device and
///   inode, or on Windows volume serial number and file index). Unix reads both
///   with a stat; Windows reads the descriptor's identity from its own handle
///   and opens the path for attributes only, so that arm does take one
///   short-lived handle per beat. A different file retires the old handle. If
///   the path still carries this guard's owner identity, the beat reopens it
///   immediately; a different owner stops the heartbeat instead of refreshing
///   the orphan the handle still holds.
///   When the handle was released by a replacement, the next beat opens the path
///   again. Releases happen on the heartbeat thread, or on the thread running a
///   replacement through `with_lease_handles_closed`.
/// * Failing that check, the bytes read through the handle must still carry this
///   guard's identity, and a path that is gone is reported as `LockGone`. A
///   guard whose heartbeat stopped reports the lease as unverified; see
///   `heartbeat_is_visible`.
#[derive(Debug)]
struct HeartbeatPump {
    path: PathBuf,
    slot: usize,
    /// Full owner identity, recorded at attach. The path can later hold a
    /// different owner: a reclaim by any process mints a new epoch, so a path
    /// whose identity no longer matches was released and re-indexed for its new
    /// owner. A reclaim happens when the owner is judged dead, or when another
    /// host's heartbeat went stale beyond its extended window.
    owner: Mutex<LockMetadata>,
    visible: AtomicBool,
    /// Set when the heartbeat ends for a reason other than the guard closing.
    /// Tests read it to tell "a later beat failed" from "the beat was still
    /// retrying", which a file timestamp cannot show.
    #[cfg(any(test, feature = "test-support"))]
    stopped: Arc<AtomicBool>,
}

fn lease_files() -> &'static Mutex<HashMap<usize, LeaseSlot>> {
    LEASE_FILES.get_or_init(|| Mutex::new(HashMap::new()))
}

fn lease_slots_by_path() -> &'static Mutex<HashMap<PathBuf, usize>> {
    LEASE_SLOT_BY_PATH.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Record a handle under its slot and its path. A path holds one heartbeat's
/// handle, so a later registration for the same path supersedes the earlier
/// entry; the old handle belongs to a guard that has released or lost the lease.
fn register_lease_slot(slot: usize, path: &Path, handle: &Arc<Mutex<Option<LeaseFile>>>) {
    lease_files()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .insert(
            slot,
            LeaseSlot {
                handle: Arc::downgrade(handle),
            },
        );
    lease_slots_by_path()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .insert(path.to_path_buf(), slot);
}

/// Forget a slot and, if it still owns the path entry, that entry too.
fn unregister_lease_slot(slot: usize, path: &Path) {
    lease_files()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .remove(&slot);
    let mut by_path = lease_slots_by_path()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if by_path.get(path).copied() == Some(slot) {
        by_path.remove(path);
    }
}

impl Clone for HeartbeatPump {
    fn clone(&self) -> Self {
        Self {
            path: self.path.clone(),
            slot: self.slot,
            owner: Mutex::new(
                self.owner
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .clone(),
            ),
            visible: AtomicBool::new(self.is_visible()),
            #[cfg(any(test, feature = "test-support"))]
            stopped: Arc::clone(&self.stopped),
        }
    }
}

impl HeartbeatPump {
    /// Register a heartbeat handle for a newly created lease and publish it in
    /// this process's lease index.
    fn attach(
        path: &Path,
        owner: &LockMetadata,
    ) -> io::Result<(Self, Arc<Mutex<Option<LeaseFile>>>)> {
        let file = Arc::new(Mutex::new(Some(
            open_lease_for_heartbeat(path).map_err(heartbeat_io_error)?,
        )));
        let slot = NEXT_LEASE_SLOT.fetch_add(1, Ordering::Relaxed) as usize;
        {
            let mut registry = lease_files()
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if registry.len() > 4096 {
                registry.retain(|_, known| known.handle.strong_count() > 0);
            }
        }
        register_lease_slot(slot, path, &file);
        Ok((
            Self {
                path: path.to_path_buf(),
                slot,
                owner: Mutex::new(owner.clone()),
                visible: AtomicBool::new(true),
                #[cfg(any(test, feature = "test-support"))]
                stopped: Arc::new(AtomicBool::new(false)),
            },
            file,
        ))
    }

    fn is_visible(&self) -> bool {
        self.visible.load(Ordering::Acquire)
    }

    #[cfg(any(test, feature = "test-support"))]
    fn mark_stopped(&self) {
        self.stopped.store(true, Ordering::Release);
    }

    /// Whether the heartbeat thread ended by itself instead of at guard drop.
    #[cfg(any(test, feature = "test-support"))]
    #[cfg_attr(not(test), allow(dead_code))]
    pub(super) fn heartbeat_stopped(&self) -> bool {
        self.stopped.load(Ordering::Acquire)
    }

    /// One beat: read the lease through the kept handle, refresh the timestamp,
    /// and write it back through the same handle, opening the lease only when
    /// no handle is kept.
    fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
        if !self.is_visible() {
            return Err(HeartbeatError::NotPumped);
        }
        let mut reopened = false;
        loop {
            let handle = {
                let registry = lease_files()
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                registry
                    .get(&self.slot)
                    .and_then(|entry| entry.handle.upgrade())
            };
            let Some(handle) = handle else {
                return Err(HeartbeatError::NotPumped);
            };
            match self.beat(&handle) {
                Ok(()) => return Ok(()),
                // The lease on disk is not the one this handle was opened for.
                // If it is no longer this process's lease, stop instead of
                // writing over another owner's heartbeat; otherwise the path
                // was replaced under the handle (a plain rewrite, or a stale
                // rename), so the next attempt reads the live file.
                Err(HeartbeatError::NotOwner) => {
                    self.retire_handle(&handle);
                    if self.release_if_reclaimed() {
                        return Err(HeartbeatError::NotOwner);
                    }
                    // A same-owner replacement is already safe to reopen. An
                    // extra heartbeat-interval sleep here leaves the live path
                    // stale even though the inode change was detected. Retry
                    // once now; repeated replacements remain transient and are
                    // retried by the normal heartbeat loop without spinning.
                    if reopened {
                        return Err(HeartbeatError::Io(io::Error::new(
                            io::ErrorKind::WouldBlock,
                            "lease replaced repeatedly during heartbeat",
                        )));
                    }
                    reopened = true;
                }
                // A partial rewrite does not prove ownership was lost. Retire
                // the descriptor so the next scheduled beat opens the live
                // path, including when recovery replaces the inode atomically.
                // Let the heartbeat loop schedule that retry: waiting here can
                // turn a transient read into a terminal NotOwner timeout.
                Err(error @ HeartbeatError::Malformed(_)) => {
                    self.retire_handle(&handle);
                    return Err(error);
                }
                Err(error) => return Err(error),
            }
        }
    }

    fn beat(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) -> Result<(), HeartbeatError> {
        let owner = self
            .owner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone();
        let needs_open = handle
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .is_none();
        if needs_open {
            // Publish the reopened descriptor under the slot before the beat:
            // the handle another thread's replacement waits for must always be
            // the one this process holds. Opening inside the beat would leave a
            // window where a replacement renames the lease the beat is not
            // looking at.
            let file = open_lease_for_heartbeat(&self.path)?;
            let mut slot = handle
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if slot.is_none() {
                *slot = Some(file);
            }
        }
        heartbeat_once(&self.path, &owner, handle)
    }

    /// Release the lease descriptor but keep the slot registered, so the next
    /// beat reopens the lease into it. Dropping the slot instead would leave the
    /// heartbeat with no handle to find, and it would stop.
    fn retire_handle(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) {
        let mut slot = handle
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *slot = None;
    }

    fn release_if_reclaimed(&self) -> bool {
        match read_lock_metadata(&self.path) {
            Err(ReadLockError::Malformed(_)) => false,
            Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => true,
            Err(ReadLockError::Io(_)) => false,
            Ok(on_disk) => {
                let owner = self
                    .owner
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                !lock_identity_matches(&on_disk, &owner)
            }
        }
    }
}

/// Refresh `heartbeat_at_ms` in a lease this guard owns.
///
/// Durability: a heartbeat only has to be visible to other processes, so this
/// path never fsyncs the file or its directory. If the machine crashes before
/// the page cache is written back, the lease on disk just carries an older
/// heartbeat and looks stale sooner, which the stale-lease rules already
/// handle. Creation and reclaim tokens also need only visibility: ownership
/// depends on a live process identity, which cannot survive a machine crash.
///
/// The rewrite happens in place on `handle`, whose contents were just checked
/// for ownership: no new inode per beat, and no window in which the path is
/// missing (which other code reads as `LockGone`). Serialization is
/// deterministic, so only the digits of `heartbeat_at_ms` differ and the file
/// keeps its length; overwriting the same length from offset zero never leaves
/// a truncated or zero-length file. If the length would change (the timestamp
/// gained a digit), fall back to an unsynced temp-file rename, which still
/// replaces the path atomically.
///
/// `handle` is empty for a beat that has no kept descriptor; that beat opens
/// the lease for itself and releases it when it returns. A heartbeat thread
/// passes the handle it keeps, so a same-length beat opens and closes nothing;
/// a length change still writes a temp file and renames it.
fn heartbeat_once(
    path: &Path,
    owner: &LockMetadata,
    handle: &Mutex<Option<LeaseFile>>,
) -> Result<(), HeartbeatError> {
    let mut slot = handle
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    // A kept descriptor only speaks for the lease while it is still the file
    // the path names. Another process's reclaim renames its own lease over the
    // path, which leaves our descriptor holding the old, unlinked file: reading
    // it would show our own identity, the beat would refresh the orphan and
    // report success, and the live lease would silently go stale. On Unix both
    // identities come from a stat, so this costs no descriptor there.
    if let Some(kept) = slot.as_mut() {
        let on_path = match LeaseFileIdentity::of_path(path) {
            Ok(identity) => identity,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                return Err(HeartbeatError::LockGone);
            }
            Err(error) => return Err(HeartbeatError::Io(error)),
        };
        // A stat that cannot read the descriptor's identity is the only reason
        // this comparison is unavailable, and it may be the same failure that
        // hides a replacement. Retire the handle instead of trusting it: the
        // read below then opens the live file and compares the bytes, which is
        // the behaviour before the descriptor was kept between beats.
        match LeaseFileIdentity::of_file(kept.file()) {
            Some(held) if held != on_path => return Err(HeartbeatError::NotOwner),
            Some(_) => {}
            None => *slot = None,
        }
    }
    let mut opened = None;
    let file = match slot.as_mut() {
        Some(kept) => kept.file(),
        None => opened.insert(open_lease_for_heartbeat(path)?).file(),
    };
    file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
    let mut current = Vec::new();
    file.read_to_end(&mut current).map_err(HeartbeatError::Io)?;
    let mut metadata: LockMetadata =
        serde_json::from_slice(&current).map_err(HeartbeatError::Malformed)?;

    if !lock_identity_matches(&metadata, owner) {
        return Err(HeartbeatError::NotOwner);
    }

    metadata.heartbeat_at_ms = now_ms();
    let next = lock_metadata_bytes(&metadata).map_err(HeartbeatError::Io)?;
    if next.len() == current.len() {
        file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
        return write_lock_bytes(file, &next).map_err(HeartbeatError::Io);
    }
    // Close before replacing the path: a handle stays usable for later beats
    // only while it refers to the lease at this path. The replacement itself
    // also releases any handle this process publishes for the path.
    *slot = None;
    drop(opened);
    replace_lock_bytes_unsynced(path, &next).map_err(HeartbeatError::Io)
}

/// What identifies one lease file on disk, independent of the name pointing at
/// it: device and inode on Unix, volume serial number and file index on
/// Windows. A rename gives the path a different file, so comparing the file a
/// heartbeat holds with the file the path now names tells whether the lease was
/// replaced under the kept descriptor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LeaseFileIdentity {
    volume: u64,
    file: u64,
}

impl LeaseFileIdentity {
    #[cfg(unix)]
    fn of_metadata(metadata: &fs::Metadata) -> Self {
        use std::os::unix::fs::MetadataExt;
        Self {
            volume: metadata.dev(),
            file: metadata.ino(),
        }
    }

    /// Volume serial number and 64-bit file index from a handle. On Windows
    /// that pair is what an inode is on Unix. Creation time would not do: NTFS
    /// file-name tunneling gives a name reused within about 15 s the creation
    /// time of the entry that last had it, so a replaced lease could look
    /// unchanged.
    #[cfg(windows)]
    fn from_raw_handle(handle: windows_sys::Win32::Foundation::HANDLE) -> Option<Self> {
        use windows_sys::Win32::Storage::FileSystem::{
            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
        };
        // SAFETY: an all-zero BY_HANDLE_FILE_INFORMATION is a valid value (plain
        // integers and FILETIME structs); the call only writes into it.
        let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
        // SAFETY: the caller owns `handle` and keeps it alive across this call,
        // and `info` is a valid out pointer.
        let ok = unsafe { GetFileInformationByHandle(handle, &mut info) } != 0;
        ok.then(|| Self {
            volume: u64::from(info.dwVolumeSerialNumber),
            file: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
        })
    }

    /// The identity of the file behind an open descriptor, read from the
    /// descriptor's own handle: nothing is opened.
    #[cfg(unix)]
    fn of_file(file: &File) -> Option<Self> {
        file.metadata()
            .ok()
            .map(|metadata| Self::of_metadata(&metadata))
    }

    #[cfg(windows)]
    fn of_file(file: &File) -> Option<Self> {
        use std::os::windows::io::AsRawHandle;
        Self::from_raw_handle(file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE)
    }

    /// The identity of the file the path names now. On Unix this is a stat and
    /// opens nothing. Windows has no handle-free file index, so that arm opens
    /// the path for attributes only, sharing every access a heartbeat holds, and
    /// closes it before returning.
    #[cfg(unix)]
    fn of_path(path: &Path) -> io::Result<Self> {
        fs::metadata(path).map(|metadata| Self::of_metadata(&metadata))
    }

    #[cfg(windows)]
    fn of_path(path: &Path) -> io::Result<Self> {
        use std::os::windows::ffi::OsStrExt;
        use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
        use windows_sys::Win32::Storage::FileSystem::{
            CreateFileW, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ,
            FILE_SHARE_WRITE, OPEN_EXISTING,
        };

        /// Closes the attribute handle on every path out of this function.
        struct Closed(windows_sys::Win32::Foundation::HANDLE);
        impl Drop for Closed {
            fn drop(&mut self) {
                // SAFETY: this wrapper is only ever built from the handle
                // `CreateFileW` returned after it was checked against
                // `INVALID_HANDLE_VALUE`, and it is dropped exactly once.
                unsafe { CloseHandle(self.0) };
            }
        }

        let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
        // SAFETY: `wide` is a NUL-terminated UTF-16 path that outlives the call;
        // the remaining arguments are plain flags and null pointers.
        let handle = unsafe {
            CreateFileW(
                wide.as_ptr(),
                FILE_READ_ATTRIBUTES,
                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                std::ptr::null(),
                OPEN_EXISTING,
                0,
                std::ptr::null_mut(),
            )
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        let handle = Closed(handle);
        Self::from_raw_handle(handle.0)
            .ok_or_else(|| io::Error::other("lease path has no file identity"))
    }

    #[cfg(not(any(unix, windows)))]
    fn of_file(_file: &File) -> Option<Self> {
        None
    }

    #[cfg(not(any(unix, windows)))]
    fn of_path(_path: &Path) -> io::Result<Self> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "no file identity on this platform",
        ))
    }
}

fn open_lease_for_heartbeat(path: &Path) -> Result<LeaseFile, HeartbeatError> {
    let file = match OpenOptions::new().read(true).write(true).open(path) {
        Ok(file) => file,
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            return Err(HeartbeatError::LockGone);
        }
        Err(error) => return Err(HeartbeatError::Io(error)),
    };
    io_ledger::record(|ledger| ledger.opens += 1);
    Ok(LeaseFile(file))
}

/// A descriptor the heartbeat opened, so its release is counted wherever it
/// happens: a beat that drops it, `LockGuard::drop`, or a lease replacement
/// that releases the published handle.
#[derive(Debug)]
struct LeaseFile(File);

impl LeaseFile {
    fn file(&mut self) -> &mut File {
        &mut self.0
    }
}

impl Drop for LeaseFile {
    fn drop(&mut self) {
        io_ledger::record(|ledger| ledger.closes += 1);
    }
}

fn heartbeat_io_error(error: HeartbeatError) -> io::Error {
    match error {
        HeartbeatError::Io(error) => error,
        other => io::Error::other(format!("{other:?}")),
    }
}

#[derive(Debug)]
enum HeartbeatError {
    Io(io::Error),
    LockGone,
    Malformed(serde_json::Error),
    NotOwner,
    NotPumped,
}

#[derive(Debug)]
enum ReadLockError {
    Io(io::Error),
    Malformed(serde_json::Error),
}

#[rustfmt::skip]
test_support_visibility! {

/// Read a lease file, re-reading until two consecutive reads agree.
///
/// Heartbeats overwrite lease files in place, and a read that overlaps such a
/// write is not guaranteed to be atomic on every filesystem: it could mix old
/// and new digits of the timestamp. The contents are otherwise identical, so a
/// mixed read still parses, but the timestamp could look older than either
/// write. Two identical reads in a row rule that out. The retry is bounded;
/// after it the last read is returned as-is.
pub(crate) fn read_lease_settled(path: &Path) -> io::Result<Vec<u8>> {
    let mut previous = fs::read(path)?;
    for _ in 0..3 {
        let next = fs::read(path)?;
        if next == previous {
            return Ok(next);
        }
        previous = next;
    }
    Ok(previous)
}
}

/// Parse a lease. An empty or partial file (for example one left by a crash
/// after an unsynced rename) is `Malformed`, which acquirers treat as a stale
/// lease to remove, never as a live owner.
fn read_lock_metadata(path: &Path) -> Result<LockMetadata, ReadLockError> {
    let bytes = read_lease_settled(path).map_err(ReadLockError::Io)?;
    serde_json::from_slice(&bytes).map_err(ReadLockError::Malformed)
}

fn open_new_lock_file(path: &Path) -> io::Result<File> {
    let file = crate::private_storage::options()
        .write(true)
        .create_new(true)
        .open(path)?;
    io_ledger::record(|ledger| ledger.new_files += 1);
    Ok(file)
}

fn lock_metadata_bytes(metadata: &LockMetadata) -> io::Result<Vec<u8>> {
    let mut bytes = serde_json::to_vec(metadata).map_err(io::Error::other)?;
    bytes.push(b'\n');
    Ok(bytes)
}

fn write_lock_bytes(file: &mut File, bytes: &[u8]) -> io::Result<()> {
    file.write_all(bytes)?;
    io_ledger::record(|ledger| ledger.bytes_written += bytes.len() as u64);
    Ok(())
}

fn write_lock_metadata_to_file(file: &mut File, metadata: &LockMetadata) -> io::Result<()> {
    write_lock_bytes(file, &lock_metadata_bytes(metadata)?)
}

fn create_lock_file_atomically(path: &Path, metadata: &LockMetadata) -> io::Result<()> {
    let tmp_path = temp_path_for_lock(path);
    let result = (|| {
        let mut file = open_new_lock_file(&tmp_path)?;
        write_lock_metadata_to_file(&mut file, metadata)?;
        drop(file);

        fs::hard_link(&tmp_path, path)?;
        Ok(())
    })();

    let _ = fs::remove_file(&tmp_path);
    result
}

/// Replace a lease's contents through a temp file and an atomic rename,
/// without fsync. Only the heartbeat uses this, and only when the in-place
/// rewrite cannot keep the file length; see `heartbeat_once` for why a
/// heartbeat needs no durability.
fn replace_lock_bytes_unsynced(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let tmp_path = temp_path_for_lock(path);
    let write_result = (|| {
        let mut file = open_new_lock_file(&tmp_path)?;
        write_lock_bytes(&mut file, bytes)?;
        drop(file);
        with_lease_handles_closed(path, || rename_over(&tmp_path, path))
    })();

    if write_result.is_err() {
        let _ = fs::remove_file(&tmp_path);
    }

    write_result
}

#[cfg(any(windows, any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn rename_over_with(
    from: &Path,
    to: &Path,
    replace: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
    replace(from, to)
}

#[cfg(windows)]
pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
    // MoveFileExW with MOVEFILE_REPLACE_EXISTING is the only replacement path
    // here that preserves the old destination on failure. A copy fallback
    // truncates the destination before copying and can expose partial bytes or
    // destroy the last valid artifact if the copy fails midway. Callers retain
    // their temp file cleanup and retry policy when an open handle prevents the
    // atomic replacement.
    // Closure instead of the bare `fs::rename` fn item: the generic fn item
    // instantiates with concrete reference lifetimes and fails the
    // higher-ranked `FnOnce(&Path, &Path)` bound on some targets.
    rename_over_with(from, to, |from, to| fs::rename(from, to))
}

#[cfg(not(windows))]
pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
    fs::rename(from, to)
}

// Per-thread counter that disambiguates temp lockfile paths for callers
// inside the same process. `now_nanos()` alone is not unique enough on
// Windows when two threads race to acquire the same lock (caught by the
// `acquire_serializes_concurrent_callers` test): two threads sampling the
// nanosecond clock within the same scheduler quantum produce identical
// timestamps, both write to the same `.lock.tmp.<pid>.<nanos>` file, one
// thread's `fs::remove_file(&tmp_path)` cleanup deletes the file before
// the other thread's `fs::hard_link(&tmp_path, ...)` runs, and the loser
// panics with `Io(Os { code: 2, NotFound })`.
//
// `AtomicU64` shared across threads makes every temp path unique within
// the process regardless of clock resolution or scheduling races.
static TEMP_LOCK_COUNTER: AtomicU64 = AtomicU64::new(0);

fn temp_path_for_lock(path: &Path) -> PathBuf {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("lock");
    let seq = TEMP_LOCK_COUNTER.fetch_add(1, Ordering::Relaxed);
    path.with_file_name(format!(
        ".{file_name}.tmp.{}.{}.{}",
        std::process::id(),
        now_nanos(),
        seq
    ))
}

fn lock_identity_matches(left: &LockMetadata, right: &LockMetadata) -> bool {
    left.pid == right.pid
        && left.hostname == right.hostname
        && left.process_start_time == right.process_start_time
        && left.boot_id == right.boot_id
        && left.created_at_ms == right.created_at_ms
        && left.writer_epoch == right.writer_epoch
}

fn remove_lock_if_owned(path: &Path, owner: &LockMetadata) -> io::Result<bool> {
    let metadata = match read_lock_metadata(path) {
        Ok(metadata) => metadata,
        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
            return Ok(false);
        }
        Err(ReadLockError::Io(error)) => return Err(error),
        Err(ReadLockError::Malformed(_)) => return Ok(false),
    };

    if lock_identity_matches(&metadata, owner) {
        remove_lock_file(path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn remove_lock_file(path: &Path) -> io::Result<()> {
    match with_lease_handles_closed(path, || fs::remove_file(path)) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

/// Reclaim (delete) a lock file we judged stale/dead, but ONLY if it still holds
/// the SAME owner identity we evaluated. Between reading the metadata and
/// deleting, the stale owner could release and a FRESH owner acquire — blindly
/// `remove_file` would then delete the fresh owner's lock, allowing split-brain
/// writers. Re-read immediately before the unlink and bail if the full owner
/// identity changed or the file vanished. POSIX has no atomic compare-and-unlink,
/// so a microscopic residual race remains, but this shrinks the window from the
/// whole judgment/poll duration to a couple of syscalls — the standard mitigation.
fn reclaim_lock_file(path: &Path, judged: &LockMetadata) -> io::Result<ReclaimResult> {
    let token = match acquire_reclaim_token(path)? {
        ReclaimTokenAcquire::Acquired(token) => token,
        ReclaimTokenAcquire::Held(holder) => return Ok(ReclaimResult::Blocked(holder)),
    };
    let _token = token;
    match read_lock_metadata(path) {
        Ok(current) => {
            if lock_identity_matches(&current, judged) {
                remove_lock_file(path)?;
                Ok(ReclaimResult::Removed)
            } else {
                // A different owner acquired it in the gap — do NOT delete.
                Ok(ReclaimResult::Unchanged)
            }
        }
        // Already gone (released/reclaimed by someone else) — nothing to do.
        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
            Ok(ReclaimResult::Unchanged)
        }
        // Malformed now (mid-write by a new owner) — don't delete; retry next poll.
        Err(ReadLockError::Malformed(_)) => Ok(ReclaimResult::Unchanged),
        Err(ReadLockError::Io(error)) => Err(error),
    }
}

fn reclaim_malformed_lock(path: &Path, judged: &[u8]) -> io::Result<bool> {
    let _token = match acquire_reclaim_token(path)? {
        ReclaimTokenAcquire::Acquired(token) => token,
        ReclaimTokenAcquire::Held(_) => return Ok(false),
    };
    match fs::read(path) {
        Ok(current)
            if current == judged && serde_json::from_slice::<LockMetadata>(&current).is_err() =>
        {
            remove_lock_file(path)?;
            Ok(true)
        }
        Ok(_) => Ok(false),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error),
    }
}

struct ReclaimTokenGuard {
    path: PathBuf,
}

impl Drop for ReclaimTokenGuard {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

fn acquire_reclaim_token(lock_path: &Path) -> io::Result<ReclaimTokenAcquire> {
    let token_path = reclaim_token_path(lock_path);
    let metadata = current_reclaim_token_metadata();

    match create_reclaim_token(&token_path, &metadata) {
        Ok(guard) => return Ok(ReclaimTokenAcquire::Acquired(guard)),
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
        Err(error) => return Err(error),
    }

    let stale = match inspect_reclaim_token(&token_path)? {
        ExistingReclaimToken::Held(holder) => return Ok(ReclaimTokenAcquire::Held(holder)),
        ExistingReclaimToken::StaleValid(owner) => remove_lock_if_owned(&token_path, &owner)?,
        ExistingReclaimToken::StaleMalformed => remove_malformed_reclaim_token(&token_path)?,
        ExistingReclaimToken::Missing => true,
    };
    if !stale {
        return inspect_reclaim_token_as_held(&token_path);
    }

    // A stale-token takeover gets exactly one O_EXCL retry. Another contender may
    // win after the unlink; never loop and accidentally turn reclamation into a
    // second lock-acquisition spin.
    match create_reclaim_token(&token_path, &metadata) {
        Ok(guard) => Ok(ReclaimTokenAcquire::Acquired(guard)),
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
            inspect_reclaim_token_as_held(&token_path)
        }
        Err(error) => Err(error),
    }
}

enum ReclaimTokenAcquire {
    Acquired(ReclaimTokenGuard),
    Held(ReclaimTokenHeld),
}

enum ExistingReclaimToken {
    Held(ReclaimTokenHeld),
    StaleValid(LockMetadata),
    StaleMalformed,
    Missing,
}

fn current_reclaim_token_metadata() -> LockMetadata {
    let pid = std::process::id();
    let process_identity = process_identity(pid);
    let now = now_ms();
    LockMetadata {
        pid,
        hostname: current_hostname(),
        process_start_time: process_identity
            .as_ref()
            .map(|identity| identity.start_time),
        boot_id: process_identity.and_then(|identity| identity.boot_id),
        created_at_ms: now,
        heartbeat_at_ms: now,
        writer_epoch: format!("reclaim-{pid}-{}", now_nanos()),
    }
}

fn create_reclaim_token(
    token_path: &Path,
    metadata: &LockMetadata,
) -> io::Result<ReclaimTokenGuard> {
    let mut file = open_new_lock_file(token_path)?;
    if let Err(error) = write_lock_metadata_to_file(&mut file, metadata) {
        let _ = fs::remove_file(token_path);
        return Err(error);
    }
    Ok(ReclaimTokenGuard {
        path: token_path.to_path_buf(),
    })
}

fn inspect_reclaim_token(token_path: &Path) -> io::Result<ExistingReclaimToken> {
    match read_lock_metadata(token_path) {
        Ok(metadata) if metadata.hostname != current_hostname() => {
            Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
                pid: Some(metadata.pid),
                state: ReclaimTokenState::DeadForeignHost,
            }))
        }
        Ok(metadata) if lock_owner_is_alive(&metadata) => {
            Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
                pid: Some(metadata.pid),
                state: ReclaimTokenState::Alive,
            }))
        }
        Ok(metadata) => Ok(ExistingReclaimToken::StaleValid(metadata)),
        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
            Ok(ExistingReclaimToken::Missing)
        }
        Err(ReadLockError::Io(error)) => Err(error),
        Err(ReadLockError::Malformed(_)) => {
            let old_enough = fs::metadata(token_path)
                .and_then(|metadata| metadata.modified())
                .ok()
                .and_then(|modified| SystemTime::now().duration_since(modified).ok())
                .is_some_and(|age| age > RECLAIM_TOKEN_MALFORMED_STALE_AGE);
            if old_enough {
                Ok(ExistingReclaimToken::StaleMalformed)
            } else {
                Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
                    pid: malformed_token_pid(token_path),
                    state: ReclaimTokenState::Malformed,
                }))
            }
        }
    }
}

fn inspect_reclaim_token_as_held(token_path: &Path) -> io::Result<ReclaimTokenAcquire> {
    let holder = match inspect_reclaim_token(token_path)? {
        ExistingReclaimToken::Held(holder) => holder,
        ExistingReclaimToken::StaleValid(metadata) => ReclaimTokenHeld {
            pid: Some(metadata.pid),
            state: ReclaimTokenState::Dead,
        },
        ExistingReclaimToken::StaleMalformed | ExistingReclaimToken::Missing => ReclaimTokenHeld {
            pid: malformed_token_pid(token_path),
            state: ReclaimTokenState::Malformed,
        },
    };
    Ok(ReclaimTokenAcquire::Held(holder))
}

fn malformed_token_pid(token_path: &Path) -> Option<u32> {
    let bytes = fs::read(token_path).ok()?;
    serde_json::from_slice::<serde_json::Value>(&bytes)
        .ok()?
        .get("pid")?
        .as_u64()
        .and_then(|pid| u32::try_from(pid).ok())
}

fn remove_malformed_reclaim_token(token_path: &Path) -> io::Result<bool> {
    match fs::remove_file(token_path) {
        Ok(()) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
        Err(error) => Err(error),
    }
}

fn reclaim_token_path(lock_path: &Path) -> PathBuf {
    let file_name = lock_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("lock");
    lock_path.with_file_name(format!(".{file_name}.reclaim"))
}

fn dead_reclaim_backoff_ms(blocked_attempt: u32, poll_interval_ms: u64) -> u64 {
    let base = poll_interval_ms.max(DEAD_RECLAIM_INITIAL_BACKOFF_MS);
    base.saturating_mul(
        1_u64
            .checked_shl(blocked_attempt.min(20))
            .unwrap_or(u64::MAX),
    )
    .min(DEAD_RECLAIM_MAX_BACKOFF_MS)
}

fn log_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld) {
    let now = Instant::now();
    let logs = RECLAIM_BLOCK_LOGS.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut logs) = logs.lock() else {
        return;
    };
    let message = match logs.get_mut(path) {
        Some(record)
            if now.saturating_duration_since(record.last_emitted) < RECLAIM_BLOCK_LOG_INTERVAL =>
        {
            record.suppressed = record.suppressed.saturating_add(1);
            return;
        }
        Some(record) => {
            let suppressed = record.suppressed;
            record.last_emitted = now;
            record.suppressed = 0;
            format_reclaim_blocked(path, holder, suppressed)
        }
        None => {
            logs.insert(
                path.to_path_buf(),
                ReclaimBlockLogRecord {
                    last_emitted: now,
                    suppressed: 0,
                },
            );
            format_reclaim_blocked(path, holder, 0)
        }
    };
    drop(logs);
    emit_reclaim_warning(message);
}

fn format_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld, suppressed: u64) -> String {
    let pid = holder
        .pid
        .map(|pid| pid.to_string())
        .unwrap_or_else(|| "unknown".to_string());
    let mut message = format!(
        "reclaim of {} blocked: reclaim token held by pid {} ({})",
        path.display(),
        pid,
        holder.state.as_str()
    );
    if suppressed > 0 {
        message.push_str(&format!(" (repeated {suppressed}x in 60s)"));
    }
    message
}

fn emit_reclaim_warning(message: String) {
    #[cfg(any(test, feature = "test-support"))]
    RECLAIM_TEST_LOGS.with(|logs| logs.borrow_mut().push(message.clone()));
    slog_warn!("{}", message);
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    pub static RECLAIM_TEST_LOGS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };

    // The observer is thread-local so concurrent lock tests cannot record one
    // another's retry decisions.
    static RETRY_SLEEP_OBSERVER: std::cell::RefCell<Option<Arc<std::sync::atomic::AtomicUsize>>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(any(test, feature = "test-support"))]
pub struct RetrySleepObserverGuard {
    previous: Option<Arc<std::sync::atomic::AtomicUsize>>,
}

#[cfg(any(test, feature = "test-support"))]
impl Drop for RetrySleepObserverGuard {
    fn drop(&mut self) {
        RETRY_SLEEP_OBSERVER.with(|observer| {
            *observer.borrow_mut() = self.previous.take();
        });
    }
}

#[cfg(any(test, feature = "test-support"))]
pub fn observe_retry_sleeps_for_test(
    observer: Arc<std::sync::atomic::AtomicUsize>,
) -> RetrySleepObserverGuard {
    let previous = RETRY_SLEEP_OBSERVER.with(|slot| slot.replace(Some(observer)));
    RetrySleepObserverGuard { previous }
}

#[cfg(any(test, feature = "test-support"))]
fn note_retry_sleep_for_test() {
    RETRY_SLEEP_OBSERVER.with(|observer| {
        if let Some(observer) = observer.borrow().as_ref() {
            observer.fetch_add(1, Ordering::SeqCst);
        }
    });
}

pub fn acquisition_now() -> Instant {
    #[cfg(any(test, feature = "test-support"))]
    if let Some(now) = retry_clock::now() {
        return now;
    }
    Instant::now()
}

pub fn sleep_until_retry(
    deadline: Option<Instant>,
    poll_interval_ms: u64,
) -> Result<(), AcquireError> {
    let poll = Duration::from_millis(poll_interval_ms);
    let sleep_for = match deadline {
        Some(deadline) => {
            let now = acquisition_now();
            if now >= deadline {
                return Err(AcquireError::Timeout);
            }
            poll.min(deadline.saturating_duration_since(now))
        }
        None => poll,
    };
    #[cfg(any(test, feature = "test-support"))]
    note_retry_sleep_for_test();
    #[cfg(any(test, feature = "test-support"))]
    if retry_clock::sleep(sleep_for) {
        return Ok(());
    }
    thread::sleep(sleep_for);
    Ok(())
}

/// Per-thread counters of successful acquisitions and lease I/O: file fsyncs,
/// directory fsyncs, newly created files (new inodes) and payload bytes.
/// Tests read them to prove which paths sync and how much a heartbeat
/// writes; outside tests every call compiles to nothing. The counters are
/// thread-local so tests running in parallel do not see each other's I/O.
pub(crate) mod io_ledger {
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
    pub(crate) struct IoLedger {
        pub(crate) acquisitions: u64,
        /// Descriptors opened for a heartbeat read or write (`fopen`/`open`).
        pub(crate) opens: u64,
        /// Descriptors released by a heartbeat (`fclose`/`close`), at the
        /// `fclose` that `close()` spends its time in on the performance sweep.
        pub(crate) closes: u64,
        pub(crate) file_syncs: u64,
        pub(crate) dir_syncs: u64,
        pub(crate) new_files: u64,
        pub(crate) bytes_written: u64,
    }

    #[cfg(any(test, feature = "test-support"))]
    thread_local! {
        static LEDGER: std::cell::Cell<IoLedger> = std::cell::Cell::new(IoLedger::default());
    }

    #[cfg(any(test, feature = "test-support"))]
    pub(crate) fn record(update: impl FnOnce(&mut IoLedger)) {
        LEDGER.with(|cell| {
            let mut ledger = cell.get();
            update(&mut ledger);
            cell.set(ledger);
        });
    }

    #[cfg(not(any(test, feature = "test-support")))]
    #[inline(always)]
    pub(crate) fn record(_update: impl FnOnce(&mut IoLedger)) {}

    /// Return this thread's counters and reset them to zero.
    #[cfg(any(test, feature = "test-support"))]
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn take() -> IoLedger {
        LEDGER.with(|cell| cell.replace(IoLedger::default()))
    }
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::ZERO)
        .as_millis() as u64
}

fn now_nanos() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::ZERO)
        .as_nanos()
}

#[cfg(unix)]
pub(crate) fn current_hostname() -> String {
    let mut buffer = [0u8; 256];
    let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
    if result == 0 {
        let len = buffer
            .iter()
            .position(|byte| *byte == 0)
            .unwrap_or(buffer.len());
        if len > 0 {
            return String::from_utf8_lossy(&buffer[..len]).into_owned();
        }
    }

    crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
}

#[cfg(windows)]
pub(crate) fn current_hostname() -> String {
    crate::environment::non_empty_var("COMPUTERNAME")
        .or_else(|| crate::environment::non_empty_var("HOSTNAME"))
        .unwrap_or_else(|| "unknown-host".to_string())
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn current_hostname() -> String {
    crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
}

/// Returns whether a same-host lock owner is still the same process instance.
///
/// Old leases have no start time, so they deliberately retain PID-only liveness
/// for backward compatibility. If an OS lookup cannot attest a recorded start
/// time, keep the PID alive: incorrectly reclaiming a paused owner is worse than
/// waiting for a process that may release the lock later.
fn lock_owner_is_alive(metadata: &LockMetadata) -> bool {
    if !process_alive(metadata.pid) {
        return false;
    }

    let identity = process_identity(metadata.pid);
    // An exited process cannot execute protected work, even while its parent
    // leaves it waitable. Missing or inconclusive identity still fails closed.
    if identity.as_ref().is_some_and(|identity| identity.exited) {
        return false;
    }
    let Some(recorded_start_time) = metadata.process_start_time else {
        return true;
    };
    let Some(current_identity) = identity else {
        return true;
    };

    if current_identity.start_time != recorded_start_time {
        return false;
    }

    match &metadata.boot_id {
        Some(recorded_boot_id) => current_identity
            .boot_id
            .as_deref()
            .map_or(true, |current_boot_id| current_boot_id == recorded_boot_id),
        None => true,
    }
}

#[cfg(target_os = "linux")]
fn linux_process_stat_identity(stat: &str) -> Option<(u64, bool)> {
    // Fields 20 and 22 are num_threads and starttime. Split after the final ')'
    // because the command can contain spaces and parentheses. pthread_exit can
    // leave a zombie leader while other threads still execute protected work.
    // Z (zombie) or X (dead) proves exit only with one reported thread. Malformed
    // fields give no identity, so owner liveness remains conservative.
    let fields = stat.rsplit_once(") ")?.1.split_ascii_whitespace();
    let state = fields.clone().next()?;
    if state.len() != 1 {
        return None;
    }
    let num_threads = fields.clone().nth(17)?.parse::<u64>().ok()?;
    let start_time = fields.clone().nth(19)?.parse::<u64>().ok()?;
    Some((start_time, matches!(state, "Z" | "X") && num_threads == 1))
}

#[cfg(target_os = "linux")]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let (start_time, exited) = linux_process_stat_identity(&stat)?;
    let boot_id = fs::read_to_string("/proc/sys/kernel/random/boot_id")
        .ok()?
        .trim()
        .to_owned();
    if boot_id.is_empty() {
        return None;
    }

    Some(ProcessIdentity {
        start_time,
        boot_id: Some(boot_id),
        exited,
    })
}

#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
const MACOS_KINFO_SIZE: usize = 648;
#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
pub(crate) const SZOMB: u8 = 5;
}
#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
pub(crate) const P_WEXIT: u32 = 0x0000_2000;
}

#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MacosExitState {
    NotExiting,
    Exiting,
    Zombie,
}
}

/// One kernel snapshot supplies both incarnation and exit evidence. libproc's
/// PROC_PIDTBSDINFO can fail for a zombie, which is not evidence of liveness.
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[derive(Clone, Debug)]
pub struct MacosKinfo {
    pub comm: String,
    pub ruid: u32,
    pub pgid: i32,
    #[cfg(any(test, feature = "test-support"))]
    pub state: u8,
    #[cfg(not(any(test, feature = "test-support")))]
    pub(crate) state: u8,
    #[cfg(any(test, feature = "test-support"))]
    pub flags: u32,
    #[cfg(not(any(test, feature = "test-support")))]
    pub(crate) flags: u32,
    #[cfg(any(test, feature = "test-support"))]
    pub started_at_us: Option<u64>,
    #[cfg(not(any(test, feature = "test-support")))]
    pub(crate) started_at_us: Option<u64>,
}

#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
impl MacosKinfo {
    #[rustfmt::skip]
    test_support_visibility! {
    pub(crate) fn exit_state(&self) -> MacosExitState {
        if self.state == SZOMB {
            MacosExitState::Zombie
        } else if self.flags & P_WEXIT != 0 {
            MacosExitState::Exiting
        } else {
            MacosExitState::NotExiting
        }
    }
    }

    /// The kernel exposes exit-started (P_WEXIT) before the process reaches the
    /// zombie state (SZOMB). Both count as exited for lease ownership and for
    /// deciding when a killed background task has finished.
    pub fn has_exited(&self) -> bool {
        self.exit_state() != MacosExitState::NotExiting
    }
}

#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn decode_macos_kinfo(bytes: &[u8]) -> Option<MacosKinfo> {
    // Darwin's kinfo_proc ABI is 648 bytes on arm64 and x86_64. libc does not
    // declare it for Apple targets; reject any other layout rather than guess.
    const P_FLAG_OFFSET: usize = 32;
    const P_STAT_OFFSET: usize = 36;
    const P_COMM_OFFSET: usize = 243;
    const P_COMM_LEN: usize = 17;
    const P_RUID_OFFSET: usize = 392;
    const E_PGID_OFFSET: usize = 564;
    if bytes.len() != MACOS_KINFO_SIZE {
        return None;
    }
    let read_u32 = |offset: usize| {
        u32::from_ne_bytes(bytes[offset..offset + 4].try_into().expect("four bytes"))
    };
    // extern_proc begins with p_un.p_starttime (timeval): 64-bit seconds and
    // 32-bit microseconds. Keep microsecond identity distinct from ms callers.
    let seconds = i64::from_ne_bytes(bytes[0..8].try_into().ok()?);
    let micros = i32::from_ne_bytes(bytes[8..12].try_into().ok()?);
    let started_at_us = if seconds > 0 && (0..1_000_000).contains(&micros) {
        (seconds as u64)
            .checked_mul(1_000_000)?
            .checked_add(micros as u64)
    } else {
        None
    };
    let comm = &bytes[P_COMM_OFFSET..P_COMM_OFFSET + P_COMM_LEN];
    let end = comm
        .iter()
        .position(|byte| *byte == 0)
        .unwrap_or(comm.len());
    Some(MacosKinfo {
        comm: String::from_utf8_lossy(&comm[..end]).into_owned(),
        ruid: read_u32(P_RUID_OFFSET),
        pgid: read_u32(E_PGID_OFFSET) as i32,
        state: bytes[P_STAT_OFFSET],
        flags: read_u32(P_FLAG_OFFSET),
        started_at_us,
    })
}

/// kern.proc.pid also answers for other users and unreaped processes. A failed
/// or partial read is inconclusive, never a fabricated live/dead identity.
#[cfg(target_os = "macos")]
pub fn macos_kinfo(pid: u32) -> Option<MacosKinfo> {
    if pid == 0 || pid > i32::MAX as u32 {
        return None;
    }
    let mut mib = [
        libc::CTL_KERN,
        libc::KERN_PROC,
        libc::KERN_PROC_PID,
        pid as i32,
    ];
    let mut bytes = [0_u8; MACOS_KINFO_SIZE];
    let mut size = bytes.len();
    // SAFETY: sysctl receives the real buffer size and may write at most it.
    let status = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as u32,
            bytes.as_mut_ptr().cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if status != 0 || size != bytes.len() {
        return None;
    }
    decode_macos_kinfo(&bytes)
}

#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn macos_process_identity(snapshot: Option<MacosKinfo>) -> Option<ProcessIdentity> {
    let info = snapshot?;
    Some(ProcessIdentity {
        start_time: info.started_at_us?,
        boot_id: None,
        exited: info.has_exited(),
    })
}

#[rustfmt::skip]
test_support_visibility! {

#[cfg(target_os = "macos")]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
    macos_process_identity(macos_kinfo(pid))
}
}

#[cfg(windows)]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
    windows_process_creation_time(pid)
        .ok()
        .flatten()
        .map(|start_time| ProcessIdentity {
            start_time,
            boot_id: None,
            exited: false,
        })
}

/// Exact birth and boot identity for speech redemption. Missing evidence is denial,
/// unlike the deliberately conservative "still alive" policy used by lock cleanup.
pub fn speech_process_identity(pid: u32) -> Option<String> {
    let identity = process_identity(pid)?;
    if identity.exited {
        return None;
    }
    #[cfg(target_os = "linux")]
    let boot = identity.boot_id?;
    #[cfg(target_os = "macos")]
    let boot = crate::volume::boot_id()?;
    #[cfg(windows)]
    let boot = speech_windows_boot_id()?;
    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
    let boot = return None;
    Some(format!(
        "{}:{boot}:{}",
        std::env::consts::OS,
        identity.start_time
    ))
}

#[cfg(windows)]
fn speech_windows_boot_id() -> Option<String> {
    #[repr(C)]
    struct BootInfo {
        id: [u8; 16],
        firmware: u32,
        flags: u64,
    }
    #[link(name = "ntdll")]
    unsafe extern "system" {
        #[link_name = "NtQuerySystemInformation"]
        fn nt_query_system_information(
            class: u32,
            buffer: *mut std::ffi::c_void,
            length: u32,
            returned: *mut u32,
        ) -> i32;
    }
    let mut info = BootInfo {
        id: [0; 16],
        firmware: 0,
        flags: 0,
    };
    let mut returned = 0;
    // SystemBootEnvironmentInformation (90) supplies the kernel's per-boot GUID.
    let status = unsafe {
        nt_query_system_information(
            90,
            (&mut info as *mut BootInfo).cast(),
            std::mem::size_of::<BootInfo>() as u32,
            &mut returned,
        )
    };
    if status < 0 || returned < 16 || info.id == [0; 16] {
        return None;
    }
    Some(info.id.iter().map(|byte| format!("{byte:02x}")).collect())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn process_identity(_pid: u32) -> Option<ProcessIdentity> {
    None
}

#[cfg(all(any(test, feature = "test-support"), target_os = "macos"))]
unsafe extern "C" {
    pub fn proc_pidinfo(
        pid: libc::c_int,
        flavor: libc::c_int,
        arg: u64,
        buffer: *mut libc::c_void,
        buffersize: libc::c_int,
    ) -> libc::c_int;
}

#[cfg(unix)]
pub fn process_alive(pid: u32) -> bool {
    if pid == 0 || pid > i32::MAX as u32 {
        return false;
    }

    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
    if result == 0 {
        return true;
    }

    io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
}

#[cfg(windows)]
pub fn process_alive(pid: u32) -> bool {
    // A denied or inconclusive probe must not permit reclaiming a live owner.
    windows_process_creation_time(pid).map_or(true, |created| created.is_some())
}

#[cfg(windows)]
fn windows_process_creation_time(pid: u32) -> io::Result<Option<u64>> {
    use windows_sys::Win32::Foundation::{
        CloseHandle, ERROR_INVALID_PARAMETER, FILETIME, WAIT_OBJECT_0, WAIT_TIMEOUT,
    };
    use windows_sys::Win32::System::Threading::{
        GetProcessTimes, OpenProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION,
    };
    if pid == 0 {
        return Ok(None);
    }
    const SYNCHRONIZE_RIGHT: u32 = 0x0010_0000;
    let handle = unsafe {
        OpenProcess(
            PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE_RIGHT,
            0,
            pid,
        )
    };
    if handle.is_null() {
        let error = io::Error::last_os_error();
        return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
            Ok(None)
        } else {
            Err(error)
        };
    }
    struct ProcessHandle(windows_sys::Win32::Foundation::HANDLE);
    impl Drop for ProcessHandle {
        fn drop(&mut self) {
            unsafe {
                CloseHandle(self.0);
            }
        }
    }
    let handle = ProcessHandle(handle);
    // Waiting on the process object distinguishes exit from liveness even when
    // an application exits with 259, the ambiguous STILL_ACTIVE exit-code value.
    match unsafe { WaitForSingleObject(handle.0, 0) } {
        WAIT_OBJECT_0 => return Ok(None),
        WAIT_TIMEOUT => {}
        _ => return Err(io::Error::last_os_error()),
    }
    let mut created = FILETIME {
        dwLowDateTime: 0,
        dwHighDateTime: 0,
    };
    let mut exited = created;
    let mut kernel = created;
    let mut user = created;
    if unsafe { GetProcessTimes(handle.0, &mut created, &mut exited, &mut kernel, &mut user) } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(Some(
        (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
    ))
}

#[cfg(windows)]
pub(crate) fn windows_process_start_time_ms(pid: u32) -> Option<u64> {
    windows_creation_ticks_to_unix_ms(windows_process_creation_time(pid).ok().flatten()?)
}

#[cfg(windows)]
fn windows_creation_ticks_to_unix_ms(ticks: u64) -> Option<u64> {
    // FILETIME counts 100-nanosecond intervals since 1601; manifests use Unix ms.
    const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000;
    ticks
        .checked_sub(UNIX_EPOCH_FILETIME)
        .map(|ticks| ticks / 10_000)
}

#[cfg(not(any(unix, windows)))]
pub fn process_alive(_pid: u32) -> bool {
    true
}

#[cfg(any(test, feature = "test-support"))]
pub mod retry_clock {
    use super::*;

    struct State {
        started: Instant,
        now: Instant,
        preparation_delay: Duration,
        sleeps: Vec<Duration>,
        attempts: usize,
    }

    thread_local! {
        static CLOCK: std::cell::RefCell<Option<State>> = const { std::cell::RefCell::new(None) };
    }

    pub struct Guard;

    impl Guard {
        pub fn install(preparation_delay: Duration) -> Self {
            CLOCK.with(|clock| {
                let mut clock = clock.borrow_mut();
                assert!(clock.is_none(), "retry clock already installed");
                let started = Instant::now();
                *clock = Some(State {
                    started,
                    now: started,
                    preparation_delay,
                    sleeps: Vec::new(),
                    attempts: 0,
                });
            });
            Self
        }

        pub fn observations(&self) -> (Duration, Vec<Duration>, usize) {
            CLOCK.with(|clock| {
                let clock = clock.borrow();
                let state = clock.as_ref().unwrap();
                (
                    state.now - state.started,
                    state.sleeps.clone(),
                    state.attempts,
                )
            })
        }
    }

    impl Drop for Guard {
        fn drop(&mut self) {
            CLOCK.with(|clock| *clock.borrow_mut() = None);
        }
    }

    pub fn now() -> Option<Instant> {
        CLOCK.with(|clock| clock.borrow().as_ref().map(|state| state.now))
    }

    pub fn before_acquire() {
        CLOCK.with(|clock| {
            if let Some(state) = clock.borrow_mut().as_mut() {
                // Model filesystem preparation after the caller chose its deadline.
                state.now += std::mem::take(&mut state.preparation_delay);
            }
        });
    }

    pub fn note_attempt() {
        CLOCK.with(|clock| {
            if let Some(state) = clock.borrow_mut().as_mut() {
                state.attempts += 1;
            }
        });
    }

    pub fn sleep(duration: Duration) -> bool {
        CLOCK.with(|clock| {
            let mut clock = clock.borrow_mut();
            let Some(state) = clock.as_mut() else {
                return false;
            };
            state.sleeps.push(duration);
            state.now += duration;
            assert!(
                state.sleeps.len() <= 1_000,
                "retry loop ignored its deadline"
            );
            true
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::BufRead as _;
    use std::io::Write;
    use std::process::Child;
    use std::process::ChildStdin;
    use std::process::Stdio;
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering;
    use std::sync::mpsc;
    use std::sync::Arc;
    use std::sync::Barrier;

    #[cfg(target_os = "linux")]
    #[test]
    #[ignore = "opt-in live-owner wait CPU measurement"]
    fn measurement_live_owner_wait_cpu() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("held.lock");
        let _owner = acquire(&path).unwrap();
        let sleeps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeps));
        let cpu = || {
            let mut time = libc::timespec {
                tv_sec: 0,
                tv_nsec: 0,
            };
            assert_eq!(
                unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) },
                0
            );
            time.tv_sec as f64 + time.tv_nsec as f64 / 1e9
        };
        let cpu_started = cpu();
        let started = Instant::now();
        assert!(matches!(
            try_acquire(&path, Duration::from_millis(1050)),
            Err(AcquireError::Timeout)
        ));
        eprintln!(
            "LOCK_WAIT_MEASUREMENT poll_ms={} sleeps={} wall_ms={:.3} thread_cpu_ms={:.3}",
            POLL_INTERVAL_MS,
            sleeps.load(Ordering::SeqCst),
            started.elapsed().as_secs_f64() * 1000.0,
            (cpu() - cpu_started) * 1000.0
        );
        assert!(sleeps.load(Ordering::SeqCst) > 0);
    }

    #[test]
    fn live_owner_poll_sleeps_to_the_original_deadline() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("held.lock");
        let _owner = acquire(&path).unwrap();
        let clock = retry_clock::Guard::install(Duration::ZERO);
        assert!(matches!(
            try_acquire(&path, Duration::from_millis(1050)),
            Err(AcquireError::Timeout)
        ));
        let (elapsed, sleeps, attempts) = clock.observations();
        assert_eq!(elapsed, Duration::from_millis(1050));
        assert_eq!(attempts, 11);
        let mut expected = vec![Duration::from_millis(100); 10];
        expected.push(Duration::from_millis(50));
        assert_eq!(sleeps, expected);
    }

    fn macos_snapshot_bytes(state: u8, flags: u32) -> [u8; 648] {
        let mut bytes = [0; 648];
        bytes[0..8].copy_from_slice(&1_700_000_000_i64.to_ne_bytes());
        bytes[8..12].copy_from_slice(&123_456_i32.to_ne_bytes());
        bytes[32..36].copy_from_slice(&flags.to_ne_bytes());
        bytes[36] = state;
        bytes[243..248].copy_from_slice(b"owner");
        bytes[392..396].copy_from_slice(&42_u32.to_ne_bytes());
        bytes[564..568].copy_from_slice(&123_i32.to_ne_bytes());
        bytes
    }

    #[test]
    fn semantic_batch_lease_macos_snapshot_keeps_birth_and_exit_phase() {
        let info = decode_macos_kinfo(&macos_snapshot_bytes(SZOMB, P_WEXIT)).unwrap();
        assert_eq!(info.comm, "owner");
        assert_eq!((info.ruid, info.pgid), (42, 123));
        assert_eq!(info.exit_state(), MacosExitState::Zombie);
        let identity = macos_process_identity(Some(info)).unwrap();
        assert_eq!(identity.start_time, 1_700_000_000_123_456);
        assert!(identity.exited);
        assert!(identity.boot_id.is_none());

        let exiting = decode_macos_kinfo(&macos_snapshot_bytes(2, P_WEXIT)).unwrap();
        assert_eq!(exiting.exit_state(), MacosExitState::Exiting);
        assert!(macos_process_identity(Some(exiting)).unwrap().exited);
        let running = decode_macos_kinfo(&macos_snapshot_bytes(2, 0)).unwrap();
        assert_eq!(running.exit_state(), MacosExitState::NotExiting);
        assert!(!macos_process_identity(Some(running)).unwrap().exited);
    }

    #[test]
    fn semantic_batch_lease_macos_missing_identity_stays_inconclusive() {
        assert!(macos_process_identity(None).is_none());
        let mut bytes = macos_snapshot_bytes(SZOMB, P_WEXIT);
        assert!(decode_macos_kinfo(&bytes[..16]).is_none());
        bytes[8..12].copy_from_slice(&1_000_000_i32.to_ne_bytes());
        assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
        bytes[8..12].copy_from_slice(&0_i32.to_ne_bytes());
        bytes[0..8].copy_from_slice(&0_i64.to_ne_bytes());
        assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
    }

    #[cfg(unix)]
    #[test]
    fn advisory_lock_guard_releases_lock_with_a_live_duplicate() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("advisory.lock");
        for shared in [true, false] {
            let file = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&path)
                .unwrap();
            if shared {
                file.lock_shared().unwrap();
            } else {
                file.lock().unwrap();
            }
            // A duplicate shares the open file description, just like fork's copy.
            let duplicate = file.try_clone().unwrap();
            let guard = AdvisoryLockGuard::from_locked_file(file);
            let probe = OpenOptions::new()
                .read(true)
                .write(true)
                .open(&path)
                .unwrap();
            assert!(matches!(
                probe.try_lock(),
                Err(fs::TryLockError::WouldBlock)
            ));
            drop(guard);
            probe
                .try_lock()
                .expect("the owner released exclusion even with a live duplicate");
            assert!(duplicate.metadata().is_ok());
            probe.unlock().unwrap();
        }
    }

    #[cfg(windows)]
    #[test]
    fn windows_native_process_probe_records_creation_identity() {
        let pid = std::process::id();
        let identity = process_identity(pid).expect("current Windows process creation identity");
        assert!(identity.start_time > 0);
        assert!(windows_process_start_time_ms(pid).unwrap() > 0);
        assert_eq!(
            windows_creation_ticks_to_unix_ms(116_444_736_000_000_000),
            Some(0)
        );
        assert_eq!(
            windows_creation_ticks_to_unix_ms(116_444_736_010_000_000),
            Some(1000)
        );
        assert_eq!(windows_creation_ticks_to_unix_ms(0), None);
        assert!(process_alive(pid));
        assert!(!process_alive(0));
        assert!(!process_alive(u32::MAX));
        let mut metadata = current_process_metadata();
        metadata.process_start_time = Some(identity.start_time.saturating_add(1));
        assert!(
            !lock_owner_is_alive(&metadata),
            "recycled PID must not keep an old lease alive"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_native_process_probe_recognizes_exited_status_259() {
        let mut child = std::process::Command::new("cmd.exe")
            .args(["/C", "exit 259"])
            .spawn()
            .unwrap();
        let pid = child.id();
        assert_eq!(child.wait().unwrap().code(), Some(259));
        assert!(
            !process_alive(pid),
            "a signaled process object is exited even when its exit code is STILL_ACTIVE"
        );
    }

    #[test]
    fn malformed_reclaim_preserves_replacement_epoch() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"malformed").unwrap();
        let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
        let expected_epoch = replacement.writer_epoch.clone();
        let replace_path = path.clone();
        BEFORE_MALFORMED_RECLAIM.with(|slot| {
            *slot.borrow_mut() = Some(Box::new(move || {
                fs::remove_file(&replace_path).unwrap();
                write_synthetic_lock(&replace_path, &replacement);
            }))
        });
        let result = acquire_with_config(&path, Some(Duration::from_millis(100)), test_config());
        assert!(
            matches!(result, Err(AcquireError::Timeout)),
            "replacement owner must block acquisition"
        );
        assert_eq!(
            read_lock_metadata(&path).unwrap().writer_epoch,
            expected_epoch
        );
    }

    #[test]
    fn heartbeat_spawn_failure_removes_own_lock() {
        let (_dir, path) = test_lock_path();
        BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| *slot.borrow_mut() = Some(Box::new(|| {})));
        assert!(create_new_lock(&path, &current_hostname(), test_config()).is_err());
        assert!(
            !path.exists(),
            "failed acquisition must not leave a live-PID lock"
        );
        drop(create_new_lock(&path, &current_hostname(), test_config()).unwrap());
    }

    #[test]
    fn heartbeat_spawn_failure_preserves_replacement_lock() {
        let (_dir, path) = test_lock_path();
        let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
        let expected_epoch = replacement.writer_epoch.clone();
        let replace_path = path.clone();
        BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| {
            *slot.borrow_mut() = Some(Box::new(move || {
                fs::remove_file(&replace_path).unwrap();
                write_synthetic_lock(&replace_path, &replacement);
            }))
        });
        assert!(create_new_lock(&path, &current_hostname(), test_config()).is_err());
        assert_eq!(
            read_lock_metadata(&path).unwrap().writer_epoch,
            expected_epoch
        );
    }

    /// A lock file whose metadata cannot be read because another actor is
    /// mid-create/delete is contention, not a failure. The create arm already
    /// treated it that way; the metadata read beside it did not, so on Windows
    /// a pending-deletion lock denied the read and propagated a hard error to a
    /// caller that then panicked mid-write. Permission-denied is classified as
    /// contention on every platform, so this reproduces without Windows: with
    /// the retry the acquisition spends its budget and times out; without it
    /// the raw permission error escapes immediately.
    #[cfg(unix)]
    #[test]
    fn unreadable_lock_metadata_is_retried_as_contention_not_propagated() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("cache.lock");
        std::fs::write(&path, b"{}\n").expect("seed lock file");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))
            .expect("deny reads");
        if std::fs::read(&path).is_ok() {
            // Running as a user that bypasses the mode bits (root in some CI
            // images); the premise cannot hold, so assert nothing.
            return;
        }

        let outcome = try_acquire(&path, Duration::from_millis(250));

        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).ok();
        match outcome {
            Err(AcquireError::Timeout) => {}
            Err(AcquireError::Io(error)) => {
                panic!("contended metadata read propagated instead of retrying: {error:?}")
            }
            Ok(_) => panic!("acquired a lock whose metadata could not be read"),
        }
    }

    const HARNESS_TEST: &str = "fs_lock::tests::fs_lock_separate_process_harness";
    const HARNESS_MODE_INSPECT: &str = "inspect";

    fn test_config() -> LockConfig {
        LockConfig {
            heartbeat_interval_ms: 25,
            heartbeat_refresh_interval_ms: 25,
            stale_heartbeat_ms: 2_000,
            live_owner_warn_ms: LIVE_OWNER_WARN_MS,
            poll_interval_ms: 10,
        }
    }

    fn test_lock_path() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().expect("create temp dir");
        let path = dir.path().join("test.lock");
        (dir, path)
    }

    fn write_synthetic_lock(path: &Path, metadata: &LockMetadata) {
        let mut file = open_new_lock_file(path).expect("create synthetic lock");
        write_lock_metadata_to_file(&mut file, metadata).expect("write synthetic lock");
    }

    #[derive(Serialize)]
    struct LegacyLockMetadata<'a> {
        pid: u32,
        hostname: &'a str,
        created_at_ms: u64,
        heartbeat_at_ms: u64,
        writer_epoch: &'a str,
    }

    fn write_legacy_lock(path: &Path, metadata: &LockMetadata) -> String {
        let legacy = LegacyLockMetadata {
            pid: metadata.pid,
            hostname: &metadata.hostname,
            created_at_ms: metadata.created_at_ms,
            heartbeat_at_ms: metadata.heartbeat_at_ms,
            writer_epoch: &metadata.writer_epoch,
        };
        let contents = format!(
            "{}\n",
            serde_json::to_string(&legacy).expect("serialize legacy lock")
        );
        fs::write(path, &contents).expect("write legacy synthetic lock");
        contents
    }

    fn synthetic_metadata(pid: u32, hostname: String, created_at_ms: u64) -> LockMetadata {
        LockMetadata {
            pid,
            hostname,
            // Synthetic metadata defaults to the legacy shape so tests must opt
            // in when they need to exercise process-instance identity.
            process_start_time: None,
            boot_id: None,
            created_at_ms,
            heartbeat_at_ms: created_at_ms,
            writer_epoch: format!("synthetic-{pid}-{created_at_ms}"),
        }
    }

    fn current_process_metadata() -> LockMetadata {
        let now = now_ms();
        let pid = std::process::id();
        let process_identity = process_identity(pid);
        let mut metadata = synthetic_metadata(pid, current_hostname(), now);
        metadata.process_start_time = process_identity
            .as_ref()
            .map(|identity| identity.start_time);
        metadata.boot_id = process_identity.and_then(|identity| identity.boot_id);
        metadata
    }

    fn different_start_time(start_time: u64) -> u64 {
        start_time.checked_add(1).unwrap_or(start_time - 1)
    }

    fn write_reclaim_token(lock_path: &Path, metadata: &LockMetadata) -> PathBuf {
        let token_path = reclaim_token_path(lock_path);
        write_synthetic_lock(&token_path, metadata);
        token_path
    }

    fn take_reclaim_test_logs() -> Vec<String> {
        RECLAIM_TEST_LOGS.with(|logs| std::mem::take(&mut *logs.borrow_mut()))
    }

    #[test]
    fn lock_operation_trace_lines_are_debug_not_info() {
        let source = include_str!("fs_lock.rs");
        assert!(source.contains("slog_debug!(\"acquired filesystem lock at {}\", path.display())"));
        assert!(
            source.contains("slog_debug!(\"released filesystem lock at {}\", self.path.display())")
        );
        assert!(!source.contains("slog_info!(\"acquired filesystem lock at {}\", path.display())"));
        assert!(
            !source.contains("slog_info!(\"released filesystem lock at {}\", self.path.display())")
        );
    }

    #[test]
    fn acquire_creates_lockfile_and_unlocks_on_drop() {
        let (_dir, path) = test_lock_path();

        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
        let metadata = read_lock_metadata(&path).expect("read lock metadata");
        assert_eq!(metadata.pid, std::process::id());
        assert_eq!(metadata.hostname, current_hostname());
        assert_eq!(metadata.created_at_ms, guard.metadata.created_at_ms);
        assert_eq!(metadata.writer_epoch, guard.metadata.writer_epoch);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
                0o600
            );
        }

        drop(guard);
        assert!(!path.exists());
    }

    #[test]
    fn permission_denied_is_treated_as_transient_create_contention() {
        // Windows surfaces a contended create/delete on the same lock path as
        // access-denied; acquire must retry these rather than fail the caller.
        let err = io::Error::from(io::ErrorKind::PermissionDenied);
        assert!(is_transient_create_contention(&err));
    }

    #[test]
    fn unrelated_io_errors_are_not_treated_as_contention() {
        // A genuinely fatal error (e.g. the parent dir is missing) must still
        // propagate, not spin in the transient-retry arm.
        let err = io::Error::from(io::ErrorKind::NotFound);
        assert!(!is_transient_create_contention(&err));
    }

    #[cfg(windows)]
    #[test]
    fn windows_sharing_violation_is_treated_as_transient_create_contention() {
        // ERROR_SHARING_VIOLATION (32) is the other contention code Windows
        // returns when a concurrent actor holds the path open mid-create.
        let err = io::Error::from_raw_os_error(32);
        assert!(is_transient_create_contention(&err));
    }

    #[test]
    fn reclaim_refuses_to_delete_a_different_owners_lock() {
        let (_dir, path) = test_lock_path();

        // A lock currently owned by "owner B".
        let owner_b = synthetic_metadata(4242, "host-b".to_string(), now_ms());
        create_lock_file_atomically(&path, &owner_b).expect("write owner B lock");

        // We judged a DIFFERENT (older) owner A as stale. Reclaiming must NOT
        // delete B's lock (the TOCTOU split-brain guard).
        let judged_a = synthetic_metadata(1111, "host-a".to_string(), now_ms() - 1_000_000);
        let outcome = reclaim_lock_file(&path, &judged_a).expect("reclaim");
        assert!(
            matches!(outcome, ReclaimResult::Unchanged),
            "must not remove a different owner's lock"
        );
        assert!(path.exists(), "owner B's lock must survive");
        let still = read_lock_metadata(&path).expect("still readable");
        assert_eq!(still.pid, 4242, "owner B's lock intact");
    }

    #[test]
    fn reclaim_deletes_when_identity_still_matches() {
        let (_dir, path) = test_lock_path();
        let owner = synthetic_metadata(1111, "host-a".to_string(), 5_000);
        create_lock_file_atomically(&path, &owner).expect("write lock");

        // Same identity we judged → safe to remove.
        let outcome = reclaim_lock_file(&path, &owner).expect("reclaim");
        assert!(
            matches!(outcome, ReclaimResult::Removed),
            "matching-identity stale lock should be removed"
        );
        assert!(!path.exists());

        // Reclaiming a now-absent lock is a no-op, not an error.
        assert!(matches!(
            reclaim_lock_file(&path, &owner).expect("reclaim missing"),
            ReclaimResult::Unchanged
        ));
    }

    #[test]
    fn try_acquire_once_reclaims_malformed_after_one_grace_read() {
        for contents in [
            b"".as_slice(),
            b"{\"pid\":999999999,\"hostname\":".as_slice(),
        ] {
            let (_dir, path) = test_lock_path();
            fs::write(&path, contents).unwrap();
            let sleeper_entries = Arc::new(AtomicUsize::new(0));
            let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
            let guard = try_acquire_once(&path).expect("stable malformed lease must be reclaimed");
            assert!(guard.verify_writer_epoch().unwrap());
            assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    fn try_acquire_once_malformed_reclaim_stops_when_token_is_held() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"malformed").unwrap();
        write_reclaim_token(&path, &current_process_metadata());
        let sleeper_entries = Arc::new(AtomicUsize::new(0));
        let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
        assert!(matches!(
            try_acquire_once(&path),
            Err(AcquireError::Timeout)
        ));
        assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
        assert_eq!(fs::read(&path).unwrap(), b"malformed");
    }

    #[test]
    fn try_acquire_once_malformed_reclaim_preserves_live_replacement() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"malformed").unwrap();
        let replacement = current_process_metadata();
        let expected_epoch = replacement.writer_epoch.clone();
        let replace_path = path.clone();
        BEFORE_MALFORMED_RECLAIM.with(|slot| {
            *slot.borrow_mut() = Some(Box::new(move || {
                fs::remove_file(&replace_path).unwrap();
                write_synthetic_lock(&replace_path, &replacement);
            }))
        });
        assert!(matches!(
            try_acquire_once(&path),
            Err(AcquireError::Timeout)
        ));
        assert_eq!(
            read_lock_metadata(&path).unwrap().writer_epoch,
            expected_epoch
        );
    }

    #[test]
    fn try_acquire_once_never_waits_behind_live_owner() {
        const OUTER_THREAD_JOIN_TIMEOUT: Duration = Duration::from_secs(30);

        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
        let contender_path = path.clone();
        let sleeper_entries = Arc::new(AtomicUsize::new(0));
        let contender_sleeper_entries = Arc::clone(&sleeper_entries);
        let (announced_tx, announced_rx) = mpsc::sync_channel(1);
        let (enter_tx, enter_rx) = mpsc::sync_channel::<()>(1);
        let (result_tx, result_rx) = mpsc::sync_channel(1);
        let contender = std::thread::spawn(move || {
            let _ = announced_tx.send(());
            let _ = enter_rx.recv();
            let _observer = observe_retry_sleeps_for_test(contender_sleeper_entries);
            let _ = result_tx.send(try_acquire_once(&contender_path));
        });

        announced_rx
            .recv_timeout(OUTER_THREAD_JOIN_TIMEOUT)
            .expect("contender should announce before the controlled enter gate");
        // Keep the announce-to-enter gap under channel control rather than
        // charging an arbitrary scheduler pause to the acquisition decision.
        enter_tx
            .send(())
            .expect("contender should wait at the controlled enter gate");

        let result = match result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT) {
            Ok(result) => result,
            Err(error) => {
                drop(guard);
                let _ = result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT);
                let _ = contender.join();
                panic!("contender did not finish before the outer join bound: {error}");
            }
        };

        contender.join().expect("contender should exit");
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(
            sleeper_entries.load(Ordering::SeqCst),
            0,
            "zero-timeout acquisition must return Timeout without sleeping"
        );
    }

    #[test]
    fn acquire_serializes_concurrent_callers() {
        let (_dir, path) = test_lock_path();
        let path = Arc::new(path);
        let barrier = Arc::new(Barrier::new(3));
        let inside = Arc::new(AtomicUsize::new(0));
        let entered = Arc::new(AtomicUsize::new(0));
        let max_inside = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for _ in 0..2 {
            let path = Arc::clone(&path);
            let barrier = Arc::clone(&barrier);
            let inside = Arc::clone(&inside);
            let entered = Arc::clone(&entered);
            let max_inside = Arc::clone(&max_inside);
            handles.push(thread::spawn(move || {
                barrier.wait();
                let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
                    .expect("thread acquire lock");
                let previous = inside.fetch_add(1, Ordering::SeqCst);
                assert_eq!(previous, 0, "two lock holders overlapped");
                entered.fetch_add(1, Ordering::SeqCst);
                max_inside.fetch_max(previous + 1, Ordering::SeqCst);
                thread::sleep(Duration::from_millis(75));
                inside.fetch_sub(1, Ordering::SeqCst);
                drop(guard);
            }));
        }

        barrier.wait();
        for handle in handles {
            handle.join().expect("join worker");
        }

        assert_eq!(entered.load(Ordering::SeqCst), 2);
        assert_eq!(max_inside.load(Ordering::SeqCst), 1);
        assert!(!path.exists());
    }

    #[test]
    fn failed_atomic_replacement_preserves_existing_destination() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let source = dir.path().join("source.tmp");
        let destination = dir.path().join("artifact.bin");
        fs::write(&source, b"new artifact").expect("write source");
        fs::write(&destination, b"valid old artifact").expect("write destination");

        let error = rename_over_with(&source, &destination, |_from, _to| {
            Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "injected replacement failure",
            ))
        })
        .expect_err("replacement must fail");

        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
        assert_eq!(
            fs::read(&destination).expect("read preserved destination"),
            b"valid old artifact"
        );
        assert_eq!(
            fs::read(&source).expect("read retained source"),
            b"new artifact"
        );
    }

    /// Number of lease files and beats per lease that model sixty seconds of
    /// heartbeats at the production interval.
    const LEDGER_LEASES: usize = 8;
    const LEDGER_BEATS_PER_LEASE: usize = (60_000 / HEARTBEAT_INTERVAL_MS) as usize;

    fn create_owned_lock(path: &Path) -> LockMetadata {
        let metadata = current_process_metadata();
        create_lock_file_atomically(path, &metadata).expect("create lock");
        metadata
    }

    #[cfg(unix)]
    fn inode(path: &Path) -> u64 {
        use std::os::unix::fs::MetadataExt;
        fs::metadata(path).expect("lock metadata").ino()
    }

    #[test]
    fn healthy_refresh_cadence_does_not_trigger_stale_warning() {
        let config = LockConfig::default();
        assert_eq!(config.live_owner_warning_age_ms(), 30_000);
        assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
        assert_eq!(test_config().live_owner_warning_age_ms(), 2_000);
    }

    #[test]
    fn idle_writer_lease_writes_twice_in_sixty_seconds() {
        let (_dir, path) = test_lock_path();
        let owner = create_owned_lock(&path);
        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
        let config = LockConfig::default();
        let start = Instant::now();
        let interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);
        let mut next = start + interval;
        let bytes = fs::metadata(&path).unwrap().len();
        let _ = io_ledger::take();
        let mut writes = 0;
        // Drive the production scheduler with a virtual minute; actual lease
        // writes still go through the kept descriptor and I/O ledger.
        for seconds in (5..=60).step_by(5) {
            writes += usize::from(
                refresh_heartbeat_if_due(
                    &pump,
                    &mut next,
                    interval,
                    start + Duration::from_secs(seconds),
                )
                .unwrap(),
            );
        }
        let ledger = io_ledger::take();
        assert_eq!(writes, 2, "one idle lease must write at 25s and 50s only");
        assert_eq!(ledger.bytes_written, bytes * 2);
        assert_eq!(
            (ledger.file_syncs, ledger.dir_syncs, ledger.new_files),
            (0, 0, 0)
        );
        eprintln!("idle writer lease / virtual 60s: before=12 after={writes} {ledger:?}");
        unregister_lease_slot(pump.slot, &path);
    }

    #[test]
    fn delayed_refresh_preserves_live_owner_and_foreign_freshness() {
        let (_dir, path) = test_lock_path();
        let mut owner = create_owned_lock(&path);
        let now = now_ms();
        // A wake delayed 40s beyond the 25s target is still inside the unchanged
        // 75s foreign-host window. Local identity remains protected even later.
        owner.heartbeat_at_ms = now - 65_000;
        fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
        let config = LockConfig::default();
        assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
        assert!(metadata_blocks_acquisition(
            &owner,
            "foreign-observer",
            config,
            now
        ));
        assert!(metadata_blocks_acquisition(
            &owner,
            &owner.hostname,
            config,
            now + 3_600_000
        ));
        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
        let wake = Instant::now();
        let mut next = wake - Duration::from_secs(40);
        assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).unwrap());
        let refreshed = read_lock_metadata(&path).unwrap();
        assert!(refreshed.heartbeat_at_ms >= now);
        assert!(metadata_blocks_acquisition(
            &refreshed,
            "foreign-observer",
            config,
            now + 70_000
        ));
        unregister_lease_slot(pump.slot, &path);
    }

    #[test]
    fn failed_refresh_retries_on_next_short_wake() {
        let (_dir, path) = test_lock_path();
        let owner = create_owned_lock(&path);
        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
        let wake = Instant::now();
        let mut next = wake;
        fs::write(&path, b"partial").unwrap();
        assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).is_err());
        assert_eq!(next, wake, "a failed write must not postpone the retry");
        fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
        assert!(refresh_heartbeat_if_due(
            &pump,
            &mut next,
            Duration::from_secs(25),
            wake + Duration::from_secs(5)
        )
        .unwrap());
        unregister_lease_slot(pump.slot, &path);
    }

    /// Sixty seconds of forced heartbeats on several leases must not fsync anything
    /// and must not create a new file per beat. The ledger totals are printed
    /// so the cost can be compared across changes.
    #[test]
    fn heartbeat_ledger_for_sixty_seconds_has_no_fsync_and_no_new_inodes() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let leases = (0..LEDGER_LEASES)
            .map(|index| {
                let path = dir.path().join(format!("writer-{index}.lease"));
                let owner = create_owned_lock(&path);
                (path, owner)
            })
            .collect::<Vec<_>>();
        #[cfg(unix)]
        let inodes_before = leases
            .iter()
            .map(|(path, _)| inode(path))
            .collect::<Vec<_>>();
        let file_bytes: u64 = leases
            .iter()
            .map(|(path, _)| fs::metadata(path).expect("lock size").len())
            .sum();

        let _ = io_ledger::take();
        for _ in 0..LEDGER_BEATS_PER_LEASE {
            for (path, owner) in &leases {
                heartbeat_once(path, owner, &Mutex::new(None)).expect("heartbeat");
            }
        }
        let ledger = io_ledger::take();
        eprintln!(
            "fs_lock heartbeat ledger: leases={LEDGER_LEASES} beats_per_lease={LEDGER_BEATS_PER_LEASE} {ledger:?}"
        );

        assert_eq!(ledger.file_syncs, 0, "heartbeats must not fsync the lease");
        assert_eq!(
            ledger.dir_syncs, 0,
            "heartbeats must not fsync the directory"
        );
        assert_eq!(ledger.new_files, 0, "heartbeats must rewrite in place");
        assert_eq!(
            ledger.bytes_written,
            file_bytes * LEDGER_BEATS_PER_LEASE as u64,
            "each beat rewrites exactly one lease's bytes"
        );
        #[cfg(unix)]
        assert_eq!(
            leases
                .iter()
                .map(|(path, _)| inode(path))
                .collect::<Vec<_>>(),
            inodes_before,
            "heartbeats must keep the lease inode"
        );
        for (path, owner) in &leases {
            let current = read_lock_metadata(path).expect("read lease");
            assert!(lock_identity_matches(&current, owner));
            assert!(current.heartbeat_at_ms >= owner.heartbeat_at_ms);
        }
    }

    /// The old contract asserted file + directory syncs at creation and during
    /// reclaim. Ownership instead depends on the live process identity: after
    /// power loss the owner is dead, and torn leases are stale. The atomic hard
    /// link and reclaim token still serialize live contenders without making
    /// those process-lifetime records power-loss durable.
    #[test]
    fn durability_lease_create_and_reclaim_unsynced() {
        let (_dir, path) = test_lock_path();
        let _ = io_ledger::take();
        crate::durability::take();
        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
            .expect("create lease");
        let created = io_ledger::take();
        drop(guard);
        assert_eq!(
            (created.file_syncs, created.dir_syncs, created.new_files),
            (0, 0, 1),
            "lease creation must not sync: {created:?}"
        );
        assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);

        let dead = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &dead);
        let _ = io_ledger::take();
        crate::durability::take();
        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
            .expect("reclaim dead lease");
        let reclaimed = io_ledger::take();
        drop(guard);
        // The failed create's temp file, reclaim token and new lease still
        // require three inodes, but none need to survive their owner's death.
        assert_eq!(
            (
                reclaimed.file_syncs,
                reclaimed.dir_syncs,
                reclaimed.new_files
            ),
            (0, 0, 3),
            "lease reclaim must not sync: {reclaimed:?}"
        );
        assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);
    }

    /// Leases a live daemon of this size holds at once: one root-keyed inspect
    /// writer lease and one root-keyed callgraph writer lease per bound project,
    /// for about a hundred projects with both caches open.
    const DAEMON_SCALE_LEASES: usize = 200;

    /// Fails if a beat opened or closed a descriptor instead of writing through
    /// the handle the guard keeps, which is what a regression to open-per-beat
    /// would show up as in the ledger.
    fn assert_beat_opens_no_descriptor(beat: &io_ledger::IoLedger) {
        assert_eq!(
            (beat.opens, beat.closes),
            (0, 0),
            "a beat must write through the kept handle, without opening or \
             closing a descriptor: {beat:?}"
        );
    }

    /// What the heartbeat costs for a daemon-shaped set of long-lived leases.
    ///
    /// Before the kept handle, every beat of every lease opened the file,
    /// read it, wrote it and closed it: 200 opens and 200 closes per beat, 40
    /// per second at the five-second interval, and the macOS `close()` that
    /// pulls the page write-back ran on the heartbeat thread. A beat now writes
    /// through the handle the heartbeat already holds. `kept_descriptors` counts
    /// how many descriptor opens occur across all the beats, so a regression to
    /// open-per-beat moves it from zero to the number of beats.
    #[test]
    fn daemon_scale_heartbeats_keep_descriptors_open_between_beats() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let _ = io_ledger::take();
        let guards = (0..DAEMON_SCALE_LEASES)
            .map(|index| {
                acquire_with_config(
                    &dir.path().join(format!("root-{index}.writer.lease")),
                    Some(Duration::from_secs(2)),
                    test_config(),
                )
                .expect("acquire live lease")
            })
            .collect::<Vec<_>>();
        // Open-only: every lease created here had no prior contents, so its
        // heartbeat started from the handle acquisition opened. A kept
        // descriptor released since would have taken the close path below.
        let setup = io_ledger::take();
        assert_eq!(
            setup.closes, 0,
            "acquiring a fresh lease must not close a descriptor: {setup:?}"
        );

        let beats = 3;
        let _ = io_ledger::take();
        for _ in 0..beats {
            for guard in &guards {
                guard.heartbeat_once().expect("beat");
            }
        }
        let beat_cost = io_ledger::take();
        eprintln!(
            "fs_lock heartbeat cost: leases={DAEMON_SCALE_LEASES} beats_per_lease={beats} \
             opens={} closes={} bytes={} (open+close per beat would be opens={} closes={})",
            beat_cost.opens,
            beat_cost.closes,
            beat_cost.bytes_written,
            DAEMON_SCALE_LEASES * beats,
            DAEMON_SCALE_LEASES * beats,
        );
        assert_beat_opens_no_descriptor(&beat_cost);
        assert!(beat_cost.bytes_written > 0, "{beat_cost:?}");

        for guard in &guards {
            let current = read_lock_metadata(guard.path()).expect("read lease");
            assert!(lock_identity_matches(&current, &guard.metadata));
        }

        drop(guards);
        let released = io_ledger::take();
        // Release closes each handle once. Other tests in this process run
        // their own leases on their own threads, so this asks only that the
        // releases are accounted for, never for exactly this test's count.
        assert!(
            released.closes >= DAEMON_SCALE_LEASES as u64,
            "each live lease closes its handle once, at release: {released:?}"
        );
    }

    /// A crash after an unsynced rename can leave a zero-length lease. Readers
    /// must treat it as stale: acquisition removes it and takes the lock, the
    /// owner's heartbeat reports a transient malformed read, and nothing panics.
    #[test]
    fn zero_length_lease_is_treated_as_stale() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"").expect("write empty lease");
        let owner = current_process_metadata();
        assert!(matches!(
            heartbeat_once(&path, &owner, &Mutex::new(None)),
            Err(HeartbeatError::Malformed(_))
        ));
        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
            serde_json::from_slice::<LockMetadata>(b"").unwrap_err()
        )));

        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
            .expect("empty lease must be reclaimed");
        assert!(guard.verify_writer_epoch().expect("verify new owner"));
    }

    /// When the new timestamp would change the file length, the heartbeat
    /// falls back to an atomic rename, still without fsync.
    #[test]
    fn heartbeat_length_change_falls_back_to_unsynced_rename() {
        let (_dir, path) = test_lock_path();
        let mut owner = current_process_metadata();
        owner.heartbeat_at_ms = 7;
        create_lock_file_atomically(&path, &owner).expect("create lock");

        let _ = io_ledger::take();
        heartbeat_once(&path, &owner, &Mutex::new(None)).expect("heartbeat");
        let ledger = io_ledger::take();
        assert_eq!((ledger.file_syncs, ledger.dir_syncs), (0, 0), "{ledger:?}");
        assert_eq!(ledger.new_files, 1, "{ledger:?}");
        let current = read_lock_metadata(&path).expect("read lease");
        assert!(lock_identity_matches(&current, &owner));
        assert!(current.heartbeat_at_ms > 7);
        let leftovers = fs::read_dir(path.parent().unwrap()).unwrap().count();
        assert_eq!(leftovers, 1, "temp file must not be left behind");
    }

    #[test]
    fn heartbeat_updates_lockfile_timestamp() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
        let initial_metadata = read_lock_metadata(&path).expect("read initial metadata");
        let initial = initial_metadata.heartbeat_at_ms;

        // Poll for up to 2s rather than sleeping a fixed multiple of the
        // heartbeat interval. `park_timeout` is a *maximum* wait, not a
        // guaranteed periodic timer — under load (shared macOS CI runners
        // running other cargo-test threads concurrently) the heartbeat
        // thread may not fire 3 times within 75ms even though
        // heartbeat_interval_ms=25. The contract being asserted is "the
        // heartbeat advances eventually", not "it advances within N
        // heartbeat intervals".
        //
        let deadline = std::time::Instant::now() + Duration::from_millis(2_000);
        let mut updated = initial;
        while std::time::Instant::now() < deadline {
            thread::sleep(Duration::from_millis(50));
            match read_lock_metadata(&path) {
                Ok(meta) => {
                    updated = meta.heartbeat_at_ms;
                    if updated > initial {
                        break;
                    }
                }
                Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
                    // Heartbeat thread is mid-rewrite (Windows
                    // remove-then-rename window). Retry next iteration.
                    continue;
                }
                Err(other) => panic!("read updated metadata: {other:?}"),
            }
        }
        assert!(
            updated > initial,
            "heartbeat timestamp did not advance within 2s"
        );
        let updated_metadata = read_lock_metadata(&path).expect("read final metadata");
        assert_eq!(
            updated_metadata.process_start_time, guard.metadata.process_start_time,
            "heartbeat rewrite must preserve the owner's process start time"
        );
        assert_eq!(
            updated_metadata.boot_id, guard.metadata.boot_id,
            "heartbeat rewrite must preserve the owner's boot identity"
        );
        drop(guard);
    }

    #[test]
    fn dead_pid_lock_is_reclaimed() {
        let (_dir, path) = test_lock_path();
        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &metadata);

        let (guard, lines) = crate::logging::capture_log_lines(|| {
            acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
                .expect("reclaim dead pid lock")
        });
        let reclaim_lines: Vec<_> = lines
            .iter()
            .filter(|line| line.contains("removing filesystem lock"))
            .collect();
        assert_eq!(
            reclaim_lines,
            vec![&format!(
                "INFO removing filesystem lock at {} from dead or recycled PID {}",
                path.display(),
                metadata.pid
            )]
        );
        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
        assert_eq!(metadata.pid, std::process::id());
        drop(guard);
    }

    #[test]
    fn zero_timeout_dead_pid_reclaim_acquires_after_removing_stale_file() {
        let (_dir, path) = test_lock_path();
        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &metadata);

        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
            .expect("zero-timeout acquire should claim the reaped stale lock");
        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
        assert_eq!(metadata.pid, std::process::id());
        drop(guard);
    }

    #[test]
    fn dead_same_host_reclaim_token_is_reaped_with_stale_lock() {
        let (_dir, path) = test_lock_path();
        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &stale);
        let token_path = write_reclaim_token(&path, &stale);

        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
            .expect("dead token must not wedge stale-lock reclamation");
        assert!(!token_path.exists(), "stale reclaim token must be removed");
        drop(guard);
        assert!(!path.exists(), "acquired lock must be released normally");
    }

    #[test]
    fn live_reclaim_token_blocks_and_is_untouched() {
        let (_dir, path) = test_lock_path();
        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &stale);
        let live = current_process_metadata();
        let token_path = write_reclaim_token(&path, &live);

        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(read_lock_metadata(&token_path).expect("live token"), live);
    }

    #[test]
    fn foreign_host_reclaim_token_is_authoritative() {
        let (_dir, path) = test_lock_path();
        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &stale);
        let mut foreign = stale.clone();
        foreign.hostname = format!("{}-foreign", current_hostname());
        let token_path = write_reclaim_token(&path, &foreign);

        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(
            read_lock_metadata(&token_path).expect("foreign token"),
            foreign
        );
    }

    #[test]
    fn malformed_reclaim_token_is_held_until_older_than_sixty_seconds() {
        use filetime::{set_file_mtime, FileTime};

        let (_dir, path) = test_lock_path();
        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &stale);
        let token_path = reclaim_token_path(&path);
        fs::write(&token_path, b"{ malformed").expect("write malformed token");

        let young_result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
        assert!(matches!(young_result, Err(AcquireError::Timeout)));
        assert_eq!(fs::read(&token_path).expect("young token"), b"{ malformed");

        let old = SystemTime::now()
            .checked_sub(RECLAIM_TOKEN_MALFORMED_STALE_AGE + Duration::from_secs(1))
            .expect("old timestamp");
        set_file_mtime(&token_path, FileTime::from_system_time(old)).expect("age token");
        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
            .expect("old malformed token should be reclaimed");
        assert!(!token_path.exists());
        drop(guard);
    }

    #[test]
    fn held_reclaim_token_logs_blocked_without_claiming_lock_removal() {
        let (_dir, path) = test_lock_path();
        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &stale);
        let live = current_process_metadata();
        write_reclaim_token(&path, &live);
        take_reclaim_test_logs();

        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        let logs = take_reclaim_test_logs();
        assert!(logs.iter().any(|line| {
            line.contains(&format!("reclaim of {} blocked", path.display()))
                && line.contains(&format!("pid {} (alive)", live.pid))
        }));
        assert!(!logs
            .iter()
            .any(|line| line.contains("removing filesystem lock")));
    }

    #[test]
    fn dead_unreclaimable_lock_retry_backoff_stays_bounded() {
        let mut elapsed_ms = 0_u64;
        let mut attempts = 0_u32;
        while elapsed_ms < 60_000 {
            elapsed_ms = elapsed_ms.saturating_add(dead_reclaim_backoff_ms(attempts, 100));
            attempts += 1;
        }

        assert!(
            attempts <= 17,
            "{attempts} retries exceed the one-minute bound"
        );
        assert_eq!(dead_reclaim_backoff_ms(0, 100), 250);
        assert_eq!(dead_reclaim_backoff_ms(20, 100), 5_000);
    }

    #[test]
    fn stale_heartbeat_from_live_pid_blocks() {
        let (_dir, path) = test_lock_path();
        let mut metadata = current_process_metadata();
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            let identity = process_identity(std::process::id())
                .expect("current process should have a start-time identity");
            assert_eq!(metadata.process_start_time, Some(identity.start_time));
            assert_eq!(metadata.boot_id, identity.boot_id);
        }
        metadata.created_at_ms = now_ms().saturating_sub(60_000);
        metadata.heartbeat_at_ms = now_ms().saturating_sub(60_000);
        write_synthetic_lock(&path, &metadata);

        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);

        remove_lock_file(&path).expect("cleanup synthetic lock");
    }

    #[test]
    fn availability_probe_preserves_a_live_owner_with_stale_heartbeat() {
        let (_dir, path) = test_lock_path();
        let mut metadata = current_process_metadata();
        metadata.heartbeat_at_ms = 0;
        write_synthetic_lock(&path, &metadata);
        let original = fs::read(&path).unwrap();
        assert_eq!(
            lock_availability(&path).unwrap(),
            LockAvailability::LiveOwner
        );
        assert_eq!(fs::read(&path).unwrap(), original);
    }

    #[test]
    fn availability_probe_observes_dead_and_missing_owners_without_reclaiming() {
        let (_dir, path) = test_lock_path();
        assert_eq!(
            lock_availability(&path).unwrap(),
            LockAvailability::Available
        );
        assert!(!path.exists());
        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        write_synthetic_lock(&path, &metadata);
        let original = fs::read(&path).unwrap();
        assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
        assert_eq!(fs::read(&path).unwrap(), original);
    }

    #[test]
    fn availability_probe_uses_extended_cross_host_heartbeat_policy() {
        let (_dir, path) = test_lock_path();
        let mut metadata = synthetic_metadata(
            999_999_999,
            format!("other-{}", current_hostname()),
            now_ms(),
        );
        write_synthetic_lock(&path, &metadata);
        assert!(
            lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
            "a local PID probe cannot attest a remote owner"
        );
        metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 2);
        fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
        assert!(
            lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
            "cross-host reclamation needs the extended threshold"
        );
        metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 5 + 1_000);
        fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
        assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
        assert_eq!(read_lock_metadata(&path).unwrap(), metadata);
    }

    #[test]
    fn availability_probe_does_not_treat_malformed_metadata_as_available() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"not-json").unwrap();
        assert_eq!(
            lock_availability(&path).unwrap(),
            LockAvailability::Malformed
        );
        assert_eq!(fs::read(&path).unwrap(), b"not-json");
    }

    #[test]
    fn availability_probe_keeps_io_errors_distinct_and_can_retry() {
        let (_dir, path) = test_lock_path();
        fs::create_dir(&path).unwrap();
        assert!(lock_availability(&path).is_err());
        assert!(path.is_dir());
        fs::remove_dir(&path).unwrap();
        assert_eq!(
            lock_availability(&path).unwrap(),
            LockAvailability::Available
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    #[test]
    fn live_pid_with_wrong_start_time_is_reclaimed() {
        let (_dir, path) = test_lock_path();
        let mut metadata = current_process_metadata();
        let current_identity = process_identity(std::process::id())
            .expect("current process should have a start-time identity");
        metadata.process_start_time = Some(different_start_time(current_identity.start_time));
        metadata.boot_id = current_identity.boot_id;
        write_synthetic_lock(&path, &metadata);

        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
            .expect("zero-timeout acquire should reclaim a reused PID");
        assert_eq!(guard.metadata.pid, std::process::id());
        assert_eq!(
            guard.metadata.process_start_time,
            Some(current_identity.start_time)
        );
        drop(guard);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn live_pid_with_wrong_boot_id_is_reclaimed() {
        let (_dir, path) = test_lock_path();
        let mut metadata = current_process_metadata();
        let current_identity = process_identity(std::process::id())
            .expect("current process should have a start-time identity");
        metadata.boot_id = Some(format!("wrong-{}", current_identity.boot_id.unwrap()));
        write_synthetic_lock(&path, &metadata);

        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
            .expect("zero-timeout acquire should reclaim a rebooted PID identity");
        assert_eq!(guard.metadata.pid, std::process::id());
        drop(guard);
    }

    #[test]
    fn legacy_live_pid_lock_keeps_pid_only_liveness() {
        let (_dir, path) = test_lock_path();
        let stale_at = now_ms().saturating_sub(60_000);
        let mut metadata = synthetic_metadata(std::process::id(), current_hostname(), stale_at);
        metadata.heartbeat_at_ms = stale_at;
        let original = write_legacy_lock(&path, &metadata);
        assert!(!original.contains("process_start_time"));
        assert!(!original.contains("boot_id"));

        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(
            fs::read_to_string(&path).expect("read legacy lock"),
            original
        );

        remove_lock_file(&path).expect("cleanup legacy lock");
    }

    #[test]
    fn legacy_dead_pid_lock_is_reclaimed() {
        let (_dir, path) = test_lock_path();
        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
        let original = write_legacy_lock(&path, &metadata);
        assert!(!original.contains("process_start_time"));
        assert!(!original.contains("boot_id"));

        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
            .expect("zero-timeout acquire should reclaim a legacy dead PID lock");
        assert_eq!(guard.metadata.pid, std::process::id());
        drop(guard);
    }

    #[test]
    fn healthy_live_owner_blocks() {
        let (_dir, path) = test_lock_path();
        let metadata = current_process_metadata();
        write_synthetic_lock(&path, &metadata);

        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));

        remove_lock_file(&path).expect("cleanup synthetic lock");
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn semantic_batch_lease_exited_unreaped_owner_is_dead() {
        use std::io::Write;
        use std::process::{Command, Stdio};
        for legacy in [false, true] {
            let (_root, path) = test_lock_path();
            let mut child = Command::new("sh")
                .args(["-c", "read gate; exit 0"])
                .stdin(Stdio::piped())
                .spawn()
                .unwrap();
            let identity = process_identity(child.id()).unwrap();
            let mut metadata = synthetic_metadata(child.id(), current_hostname(), now_ms());
            metadata.process_start_time = Some(identity.start_time);
            metadata.boot_id = identity.boot_id;
            if legacy {
                write_legacy_lock(&path, &metadata);
            } else {
                write_synthetic_lock(&path, &metadata);
            }
            writeln!(child.stdin.take().unwrap(), "exit").unwrap();
            // WNOWAIT proves exit without reaping: kill(pid, 0) can still see
            // this PID, but the process can no longer execute protected work.
            let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
            let observed = unsafe {
                libc::waitid(
                    libc::P_PID,
                    libc::id_t::try_from(child.id()).unwrap(),
                    info.as_mut_ptr(),
                    libc::WEXITED | libc::WNOWAIT,
                )
            };
            let wait_error = io::Error::last_os_error();
            let exited = process_identity(child.id()).is_some_and(|identity| identity.exited);
            let recovered = try_acquire_once(&path);
            child.wait().unwrap();
            assert_eq!(observed, 0, "waitid failed: {wait_error}");
            assert!(exited, "the native identity probe did not observe exit");
            assert!(
                recovered.is_ok(),
                "an exited unreaped owner blocked recovery (legacy={legacy})"
            );
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn semantic_batch_lease_linux_stat_requires_quiescent_zombie() {
        let one =
            "4242 (worker (lease owner)) Z 1 1 1 0 -1 4194304 10 0 0 0 0 0 0 0 20 0 1 0 1234 0";
        assert_eq!(linux_process_stat_identity(one), Some((1234, true)));
        let live_threads = one.replace(" 1 0 1234 ", " 2 0 1234 ");
        assert_eq!(
            linux_process_stat_identity(&live_threads),
            Some((1234, false)),
            "a zombie leader does not prove its worker threads exited"
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace(" 1 0 1234 ", " 0 0 1234 ")),
            Some((1234, false))
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace(") Z ", ") X ")),
            Some((1234, true))
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace(") Z ", ") S ")),
            Some((1234, false))
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace(" 1 0 1234 ", " bad 0 1234 ")),
            None
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace("1234", "bad")),
            None
        );
        assert_eq!(
            linux_process_stat_identity(&one.replace(") Z ", ") bad ")),
            None
        );
    }

    #[test]
    fn malformed_lockfile_is_reclaimed() {
        let (_dir, path) = test_lock_path();
        fs::write(&path, b"not valid json").expect("write malformed lock");

        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
            .expect("reclaim malformed lock");
        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
        assert_eq!(metadata.pid, std::process::id());
        drop(guard);
    }

    #[test]
    fn cross_host_lock_is_not_stolen_before_extended_stale_threshold() {
        let (_dir, path) = test_lock_path();
        let now = now_ms();
        let mut metadata = current_process_metadata();
        metadata.hostname = format!("{}-other", current_hostname());
        metadata.process_start_time = metadata.process_start_time.map(different_start_time);
        metadata.created_at_ms = now;
        metadata.heartbeat_at_ms = now;
        metadata.writer_epoch = format!("cross-host-{now}");
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        assert_ne!(
            metadata.process_start_time,
            process_identity(std::process::id()).map(|identity| identity.start_time)
        );
        write_synthetic_lock(&path, &metadata);

        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);

        remove_lock_file(&path).expect("cleanup synthetic lock");
    }

    #[test]
    fn stale_cross_host_lock_is_reclaimed_after_extended_threshold() {
        let (_dir, path) = test_lock_path();
        let stale_at =
            now_ms().saturating_sub(test_config().cross_host_stale_heartbeat_ms() + 1_000);
        let mut metadata = current_process_metadata();
        metadata.hostname = format!("{}-other", current_hostname());
        metadata.process_start_time = metadata.process_start_time.map(different_start_time);
        metadata.created_at_ms = stale_at;
        metadata.heartbeat_at_ms = stale_at;
        metadata.writer_epoch = format!("cross-host-{stale_at}");
        write_synthetic_lock(&path, &metadata);

        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
            .expect("reclaim stale cross-host lock");
        let reclaimed = read_lock_metadata(&path).expect("read reclaimed lock");
        assert_eq!(reclaimed.hostname, current_hostname());
        assert_ne!(reclaimed.created_at_ms, metadata.created_at_ms);
        drop(guard);
    }

    #[test]
    fn live_owner_over_10min_warns_but_blocks() {
        let (_dir, path) = test_lock_path();
        let mut metadata = current_process_metadata();
        metadata.created_at_ms = now_ms().saturating_sub(11 * 60 * 1_000);
        metadata.heartbeat_at_ms = now_ms();
        write_synthetic_lock(&path, &metadata);

        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
        assert!(matches!(result, Err(AcquireError::Timeout)));
        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);

        remove_lock_file(&path).expect("cleanup synthetic lock");
    }

    #[derive(Debug, serde::Serialize, serde::Deserialize)]
    struct HeartbeatObservation {
        step: usize,
        observed_at_ms: u64,
        heartbeat_at_ms: Option<u64>,
        volume: Option<u64>,
        inode: Option<u64>,
        modified_at_ms: Option<u64>,
        error: Option<String>,
    }

    fn observe_heartbeat(path: &Path, step: usize) -> HeartbeatObservation {
        let mut observation = HeartbeatObservation {
            step,
            observed_at_ms: now_ms(),
            heartbeat_at_ms: None,
            volume: None,
            inode: None,
            modified_at_ms: None,
            error: None,
        };
        let mut file = match File::open(path) {
            Ok(file) => file,
            Err(error) => {
                observation.error = Some(error.to_string());
                return observation;
            }
        };
        // Identity and contents come from the same open, including if the path
        // is atomically replaced while the observer is reading it.
        if let Some(identity) = LeaseFileIdentity::of_file(&file) {
            observation.volume = Some(identity.volume);
            observation.inode = Some(identity.file);
        }
        observation.modified_at_ms = file
            .metadata()
            .and_then(|metadata| metadata.modified())
            .ok()
            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
            .map(|elapsed| elapsed.as_millis() as u64);
        let mut bytes = Vec::new();
        match file.read_to_end(&mut bytes) {
            Ok(_) => match serde_json::from_slice::<LockMetadata>(&bytes) {
                Ok(metadata) => observation.heartbeat_at_ms = Some(metadata.heartbeat_at_ms),
                Err(error) => observation.error = Some(error.to_string()),
            },
            Err(error) => observation.error = Some(error.to_string()),
        }
        observation
    }

    struct HeartbeatHarness {
        child: Child,
        input: Option<ChildStdin>,
        lines: mpsc::Receiver<String>,
        reader: Option<JoinHandle<()>>,
        transcript: Vec<String>,
    }

    impl HeartbeatHarness {
        fn read_observation(
            &mut self,
            prefix: &str,
            deadline: Instant,
        ) -> Result<HeartbeatObservation, String> {
            loop {
                let line = self
                    .lines
                    .recv_timeout(deadline.saturating_duration_since(Instant::now()))
                    .map_err(|error| format!("observer response: {error}"))?;
                self.transcript.push(line.clone());
                if let Some(json) = line.strip_prefix(prefix) {
                    return serde_json::from_str(json)
                        .map_err(|error| format!("observer JSON: {error}"));
                }
            }
        }

        fn observe(
            &mut self,
            step: usize,
            deadline: Instant,
        ) -> Result<HeartbeatObservation, String> {
            let input = self.input.as_mut().expect("observer input is open");
            writeln!(input, "{step}").map_err(|error| error.to_string())?;
            input.flush().map_err(|error| error.to_string())?;
            self.read_observation("sample:", deadline)
        }

        fn diagnostics(&self, path: &Path, guard: &LockGuard, step: usize) -> String {
            let held_identity = guard.heartbeat_file.try_lock().ok().and_then(|mut slot| {
                slot.as_mut()
                    .and_then(|lease| LeaseFileIdentity::of_file(lease.file()))
            });
            format!(
                "parent={:?} held_identity={held_identity:?} stopped={} visible={}\nchild observations:\n{}",
                observe_heartbeat(path, step),
                guard.pump.heartbeat_stopped(),
                guard.heartbeat_is_visible(),
                self.transcript.join("\n")
            )
        }

        fn finish(&mut self) -> std::process::ExitStatus {
            self.input.take();
            let status = self.child.wait().expect("observer exit");
            self.reader.take().unwrap().join().expect("observer reader");
            self.transcript.extend(self.lines.try_iter());
            status
        }
    }

    impl Drop for HeartbeatHarness {
        fn drop(&mut self) {
            // An assertion can unwind before normal EOF/wait cleanup. Reap the
            // observer and join its stdout reader before the owner releases the
            // lease, so no child retains the test runner's inherited stderr.
            self.input.take();
            if !matches!(self.child.try_wait(), Ok(Some(_))) {
                let _ = self.child.kill();
            }
            let _ = self.child.wait();
            if let Some(reader) = self.reader.take() {
                let _ = reader.join();
            }
        }
    }

    /// Run the Rust test binary as an independent lease observer. Each request
    /// opens the lease afresh and returns its content timestamp and file identity.
    fn spawn_test_harness(mode: &str, path: &Path) -> HeartbeatHarness {
        let mut command = std::process::Command::new(std::env::current_exe().expect("test exe"));
        command
            .args(["--exact", HARNESS_TEST, "--nocapture", "--test-threads=1"])
            .env("FS_LOCK_HARNESS_MODE", mode)
            .env("FS_LOCK_HARNESS_PATH", path)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped());
        for name in [
            "AFT_TEST_REQUIRE_RUST_ANALYZER",
            "AFT_TEST_STORAGE_ROOT",
            "AFT_STORAGE_DIR",
        ] {
            command.env_remove(name);
        }
        let mut child = command.spawn().expect("spawn test harness process");
        let stdin = child.stdin.take().expect("harness stdin");
        let stdout = child.stdout.take().expect("harness stdout");
        let (sender, receiver) = mpsc::channel();
        let reader = thread::spawn(move || {
            for line in io::BufReader::new(stdout).lines() {
                let Ok(line) = line else { break };
                if sender.send(line).is_err() {
                    break;
                }
            }
        });
        HeartbeatHarness {
            child,
            input: Some(stdin),
            lines: receiver,
            reader: Some(reader),
            transcript: Vec::new(),
        }
    }

    /// Another process must see background heartbeats through the kept handle.
    /// A beat interval is not a scheduling guarantee: allow progress within the
    /// configured stale bound, and never substitute a parent-side read for the
    /// observer's actual timestamp and inode.
    #[test]
    fn separate_process_sees_heartbeat_advance() {
        if std::env::var_os(HARNESS_TEST).is_some() {
            return;
        }
        assert_separate_process_heartbeat_advances(test_config());
    }

    #[test]
    fn separate_process_waits_for_heartbeat_within_stale_bound() {
        assert_separate_process_heartbeat_advances(LockConfig {
            heartbeat_interval_ms: 400,
            ..test_config()
        });
    }

    fn assert_separate_process_heartbeat_advances(config: LockConfig) {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, config).expect("acquire lock");
        guard.heartbeat_once().expect("initial beat");
        let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
        let ready = harness
            .read_observation("ready:", Instant::now() + Duration::from_secs(10))
            .unwrap_or_else(|error| {
                panic!(
                    "observer startup failed: {error}\n{}",
                    harness.diagnostics(&path, &guard, 0)
                )
            });
        let mut previous = ready.heartbeat_at_ms.unwrap_or_else(|| {
            panic!(
                "observer could not read initial lease\n{}",
                harness.diagnostics(&path, &guard, 0)
            )
        });
        for step in 1..=4 {
            let deadline = Instant::now() + Duration::from_millis(config.stale_heartbeat_ms);
            loop {
                let observation = harness.observe(step, deadline).unwrap_or_else(|error| {
                    panic!(
                        "observer step {step} failed: {error}\n{}",
                        harness.diagnostics(&path, &guard, step)
                    )
                });
                if let Some(seen) = observation.heartbeat_at_ms.filter(|seen| *seen > previous) {
                    eprintln!("heartbeat observer advanced: {observation:?}");
                    previous = seen;
                    break;
                }
                assert!(
                    Instant::now() < deadline,
                    "observer heartbeat did not advance from {previous} within {}ms at step {step}\n{}",
                    config.stale_heartbeat_ms,
                    harness.diagnostics(&path, &guard, step)
                );
                thread::sleep(
                    Duration::from_millis(25)
                        .min(deadline.saturating_duration_since(Instant::now())),
                );
            }
        }
        let status = harness.finish();
        assert!(
            status.success(),
            "observer failed: {status:?}\n{}",
            harness.diagnostics(&path, &guard, 4)
        );
    }

    #[cfg(unix)]
    #[test]
    fn separate_process_harness_drop_reaps_observer() {
        let (_dir, path) = test_lock_path();
        write_synthetic_lock(&path, &current_process_metadata());
        let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
        harness
            .read_observation("ready:", Instant::now() + Duration::from_secs(10))
            .expect("observer ready");
        let pid = harness.child.id() as libc::pid_t;
        drop(harness);
        let mut status = 0;
        // SAFETY: pid names the child this test just spawned; status is a valid
        // out pointer. A completed Drop must already have waited for this child.
        let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
        let error = io::Error::last_os_error().raw_os_error();
        if waited == 0 {
            // SAFETY: only our still-running child can be waitable under pid.
            unsafe {
                libc::kill(pid, libc::SIGKILL);
                libc::waitpid(pid, &mut status, 0);
            }
        }
        assert_eq!(waited, -1, "observer survived harness drop");
        assert_eq!(error, Some(libc::ECHILD), "observer was not reaped");
    }

    /// A replacement by another part of this process must leave the owner's
    /// heartbeat working: writers keep publishing through the same guard, and a
    /// heartbeat that stopped would let another process reclaim the lease after
    /// the stale window while the writer is still running. The test replaces the
    /// lease (which releases the published handle), then opens a fresh handle
    /// and publishes it, and requires the next beat to refresh through it.
    #[test]
    fn replacing_the_lease_keeps_the_next_beat_working_for_the_owner() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
        let mut restored = guard.metadata.clone();
        // Same digit count as the live heartbeat, so the serialized lease keeps
        // its byte length; the replacement itself is still an atomic rename.
        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
        let fresh = {
            let bytes = lock_metadata_bytes(&restored).expect("serialize");
            with_lease_handles_closed(&path, || {
                replace_lock_bytes_unsynced(&path, &bytes).map(|()| open_lease_for_heartbeat(&path))
            })
            .expect("replace the lease")
            .expect("open the replacement lease")
        };
        // The owner keeps a reference, as `LockGuard` does, so the handle
        // survives until the guard is released.
        let replacement = Arc::new(Mutex::new(Some(fresh)));
        register_lease_slot(guard.pump.slot, &path, &replacement);

        let stale_at = restored.heartbeat_at_ms;
        let deadline = Instant::now() + Duration::from_secs(3);
        let mut advanced = false;
        while Instant::now() < deadline {
            thread::sleep(Duration::from_millis(
                test_config().heartbeat_interval_ms * 2,
            ));
            if read_lock_metadata(&path)
                .map(|meta| meta.heartbeat_at_ms > stale_at)
                .unwrap_or(false)
            {
                advanced = true;
                break;
            }
        }
        assert!(
            advanced,
            "the heartbeat did not refresh the lease through the replacement \
             handle: {:?}",
            read_lock_metadata(&path)
        );
        assert!(
            guard.verify_writer_epoch().expect("verify lease"),
            "writers must still verify their epoch after a replacement"
        );
    }

    /// Body of the separate-process harness this module's tests spawn.
    #[test]
    fn fs_lock_separate_process_harness() {
        let Some(mode) = std::env::var_os("FS_LOCK_HARNESS_MODE") else {
            return;
        };
        let path = PathBuf::from(std::env::var_os("FS_LOCK_HARNESS_PATH").expect("harness path"));
        println!("mode:{mode:?} path={}", path.display());
        match mode.to_string_lossy().as_ref() {
            HARNESS_MODE_INSPECT => {
                println!(
                    "ready:{}",
                    serde_json::to_string(&observe_heartbeat(&path, 0)).unwrap()
                );
                io::stdout().flush().unwrap();
                for line in io::stdin().lock().lines() {
                    let step = line.unwrap().parse().expect("observation step");
                    println!(
                        "sample:{}",
                        serde_json::to_string(&observe_heartbeat(&path, step)).unwrap()
                    );
                    io::stdout().flush().unwrap();
                }
            }
            other => panic!("unknown harness mode {other}"),
        }
    }

    /// A beat reads ownership through the descriptor the heartbeat keeps, not
    /// through the path. When another process reclaims the lease, the rename
    /// gives the path a new file while the kept descriptor still refers to the
    /// old, unlinked one. Reading through it would still see this owner's
    /// identity, so the beat would refresh the orphan and report success while
    /// the live lease went stale. The beat must instead see that the path is no
    /// longer the file it holds and stop.
    #[test]
    fn beat_stops_when_another_owner_replaces_the_lease_file() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
        guard
            .heartbeat_once()
            .expect("beat through the kept descriptor");

        // Another process's reclaim: it writes its own lease beside the file and
        // renames it over the path. It cannot see this process's open
        // descriptors, so the heartbeat keeps the old, now unlinked file.
        let mut foreign = current_process_metadata();
        foreign.pid = foreign.pid.wrapping_add(1);
        foreign.created_at_ms = now_ms().saturating_add(1_000);
        foreign.writer_epoch = format!("foreign-{}", now_ms());
        assert!(!lock_identity_matches(&foreign, &guard.metadata));
        let staging = path.with_extension("foreign");
        fs::write(
            &staging,
            lock_metadata_bytes(&foreign).expect("serialize foreign lease"),
        )
        .expect("write the foreign owner's lease");
        rename_over(&staging, &path).expect("foreign reclaim renames over the lease");

        assert!(
            matches!(guard.heartbeat_once(), Err(HeartbeatError::NotOwner)),
            "a beat must not accept the orphaned descriptor it still holds"
        );
        assert_eq!(
            read_lock_metadata(&path).expect("read foreign lease"),
            foreign,
            "a beat must never write over the foreign owner's lease"
        );
    }

    /// Replacing or removing another lease must not cost this lease its kept
    /// descriptor. Every replacement releases the handle it publishes for its
    /// own path; releasing every published handle instead would drop this one
    /// and the next beat would reopen the file, restoring the per-beat
    /// descriptor churn the kept handle exists to remove.
    #[test]
    fn unrelated_lease_churn_keeps_the_kept_descriptor() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let mut guards = (0..2)
            .map(|index| {
                acquire_with_config(
                    &dir.path().join(format!("tenant-{index}.lease")),
                    Some(Duration::from_secs(2)),
                    test_config(),
                )
                .expect("acquire")
            })
            .collect::<Vec<_>>();
        let neighbour = dir.path().join("neighbour.lease");

        for _ in 0..3 {
            // Another tenant is acquired, replaced and released while this
            // lease keeps its own descriptor.
            let churn = acquire_with_config(&neighbour, None, test_config()).expect("churn lease");
            let mut restored = churn.metadata.clone();
            restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
            let bytes = lock_metadata_bytes(&restored).expect("serialize");
            with_lease_handles_closed(&neighbour, || {
                replace_lock_bytes_unsynced(&neighbour, &bytes)
            })
            .expect("replace the neighbour");
            drop(churn);
            let _ = io_ledger::take();
        }

        let _ = io_ledger::take();
        for guard in &guards {
            guard.heartbeat_once().expect("beat");
        }
        let cost = io_ledger::take();
        assert_beat_opens_no_descriptor(&cost);
        guards.clear();
    }

    /// The identity check runs on every beat, so it must not open or close the
    /// lease a second time. Unix needs a stat for it; on Windows the path lookup
    /// takes one short-lived attribute handle, which this ledger only counts if
    /// it went through the heartbeat's own open. What it pins is that the beat
    /// neither reopens the lease for reading nor closes the descriptor it
    /// keeps.
    #[test]
    fn descriptor_identity_check_opens_no_descriptor() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
        let _ = io_ledger::take();
        for _ in 0..3 {
            guard.heartbeat_once().expect("beat");
        }
        let ledger = io_ledger::take();
        assert_beat_opens_no_descriptor(&ledger);
    }

    #[test]
    fn stopped_heartbeat_releases_handle_without_unlocking_or_touching_replacement() {
        let dir = tempfile::tempdir().expect("temp dir");
        let cache = dir.path().join("cache");
        fs::create_dir(&cache).expect("cache dir");
        let path = cache.join("writer.lease");
        let mut guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
        let _ = io_ledger::take();

        guard.stop_heartbeat_for_removal();
        assert_eq!(io_ledger::take().closes, 1, "close the kept handle now");
        assert!(guard.heartbeat.is_none(), "join before closing the handle");
        assert!(guard.heartbeat_file.lock().unwrap().is_none());
        assert!(!guard
            .verify_writer_epoch()
            .expect("stopped guard is not writable"));
        assert!(matches!(
            guard.pump.heartbeat_once(),
            Err(HeartbeatError::NotPumped)
        ));
        assert!(matches!(
            try_acquire_once(&path),
            Err(AcquireError::Timeout)
        ));
        assert!(lock_identity_matches(
            &read_lock_metadata(&path).expect("lease remains until removal"),
            &guard.metadata
        ));

        // Windows refuses this directory rename while the heartbeat handle is
        // open. Keep the lease on disk until the directory has moved so another
        // writer cannot enter the old cache during retirement.
        let retired = dir.path().join("retired");
        fs::rename(&cache, &retired).expect("retire with the lease guard still alive");
        fs::create_dir(&cache).expect("replacement cache");
        let replacement = acquire_with_config(&path, None, test_config()).expect("new owner");
        let canary = cache.join("canary");
        fs::write(&canary, b"replacement").expect("canary");
        drop(guard);
        assert!(replacement
            .verify_writer_epoch()
            .expect("replacement owns lease"));
        assert_eq!(
            fs::read(canary).expect("replacement preserved"),
            b"replacement"
        );
        fs::remove_dir_all(retired).expect("reap without a lingering lease handle");
    }

    #[test]
    fn drop_stops_heartbeat_thread() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
        drop(guard);

        thread::sleep(Duration::from_millis(
            test_config().heartbeat_interval_ms * 3,
        ));
        assert!(
            !path.exists(),
            "heartbeat recreated or kept updating lockfile"
        );
    }

    #[test]
    fn heartbeat_error_classification_terminal_vs_transient() {
        // Terminal: the lock is provably no longer ours to refresh.
        assert!(heartbeat_error_is_terminal(&HeartbeatError::LockGone));
        assert!(heartbeat_error_is_terminal(&HeartbeatError::NotOwner));
        // Transient: a temporary I/O hiccup or a read that raced a concurrent
        // writer. These must NOT kill the heartbeat — it retries instead.
        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Io(
            io::Error::other("disk blip")
        )));
        let malformed: serde_json::Error =
            serde_json::from_str::<LockMetadata>("not json").unwrap_err();
        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
            malformed
        )));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn released_lease_closes_all_descriptors_synchronously() {
        let (dir, path) = test_lock_path();
        let open_under_root = || {
            fs::read_dir("/proc/self/fd")
                .expect("descriptor census")
                .filter_map(Result::ok)
                .filter_map(|entry| fs::read_link(entry.path()).ok())
                .filter(|target| target.starts_with(dir.path()))
                .collect::<Vec<_>>()
        };
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
        let handle = Arc::downgrade(&guard.heartbeat_file);
        assert!(!open_under_root().is_empty(), "live lease keeps its handle");
        drop(guard);
        assert!(
            handle.upgrade().is_none(),
            "heartbeat must release its handle"
        );
        assert!(open_under_root().is_empty(), "no descriptors after release");
    }

    #[test]
    fn malformed_beat_reopens_atomic_replacement_on_next_beat() {
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(
            &path,
            None,
            LockConfig {
                heartbeat_interval_ms: 60_000,
                ..test_config()
            },
        )
        .expect("acquire lease");
        let live = fs::read(&path).expect("read lease");
        fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lease");

        assert!(matches!(
            guard.pump.heartbeat_once(),
            Err(HeartbeatError::Malformed(_))
        ));
        assert!(guard.heartbeat_file.lock().unwrap().is_none());
        assert!(guard.heartbeat_is_visible());

        let mut restored = guard.metadata.clone();
        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
        let replacement = path.with_extension("replacement");
        fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
        rename_over(&replacement, &path).expect("atomic recovery outside the lease registry");
        let _ = io_ledger::take();
        guard
            .pump
            .heartbeat_once()
            .expect("retry through live inode");
        let recovered = read_lock_metadata(&path).expect("independently read recovered lease");
        assert!(lock_identity_matches(&recovered, &guard.metadata));
        assert!(recovered.heartbeat_at_ms > restored.heartbeat_at_ms);
        let recovery = io_ledger::take();
        assert_eq!((recovery.opens, recovery.closes), (1, 0));

        guard.pump.heartbeat_once().expect("healthy next beat");
        assert_beat_opens_no_descriptor(&io_ledger::take());
    }

    #[test]
    fn valid_same_owner_replacement_refreshes_within_stale_bound() {
        let (_dir, path) = test_lock_path();
        let config = test_config();
        let guard = acquire_with_config(
            &path,
            None,
            LockConfig {
                heartbeat_interval_ms: 60_000,
                ..config
            },
        )
        .expect("acquire lease");
        let held_identity = LeaseFileIdentity::of_file(
            guard
                .heartbeat_file
                .lock()
                .unwrap()
                .as_mut()
                .unwrap()
                .file(),
        );
        let mut restored = guard.metadata.clone();
        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
        let replacement = path.with_extension("replacement");
        fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
        // Do not release or re-index the kept handle: an atomic replacement by
        // another process cannot notify this process's lease registry either.
        rename_over(&replacement, &path).expect("replace valid same-owner lease");
        let live_identity = LeaseFileIdentity::of_path(&path).expect("replacement identity");
        assert_ne!(held_identity, Some(live_identity));

        let _ = io_ledger::take();
        let started = Instant::now();
        let result = guard.pump.heartbeat_once();
        let elapsed = started.elapsed();
        let on_disk = read_lock_metadata(&path).expect("independent path read");
        let cost = io_ledger::take();
        eprintln!(
            "valid replacement beat: elapsed={elapsed:?} result={result:?} held={held_identity:?} live={live_identity:?} sentinel={} observed={} cost={cost:?}",
            restored.heartbeat_at_ms, on_disk.heartbeat_at_ms
        );
        assert!(
            elapsed < Duration::from_millis(config.stale_heartbeat_ms),
            "same-owner replacement delayed a beat beyond its stale bound: {elapsed:?}"
        );
        result.expect("refresh replacement through reopened handle");
        assert!(on_disk.heartbeat_at_ms > restored.heartbeat_at_ms);
        assert!(lock_identity_matches(&on_disk, &guard.metadata));
        assert_eq!((cost.opens, cost.closes), (1, 1));
        let reopened_identity = LeaseFileIdentity::of_file(
            guard
                .heartbeat_file
                .lock()
                .unwrap()
                .as_mut()
                .unwrap()
                .file(),
        );
        assert_eq!(reopened_identity, Some(live_identity));
        guard.pump.heartbeat_once().expect("healthy next beat");
        assert_beat_opens_no_descriptor(&io_ledger::take());
    }

    #[test]
    fn heartbeat_survives_transient_malformed_and_recovers() {
        // Regression: a single transient failure (e.g. a read that races a
        // concurrent writer and sees a momentarily-unparseable file) used to
        // permanently kill the heartbeat thread. The guard holder would then
        // run its critical section with a stale heartbeat_at_ms, letting
        // another process reclaim the lock after the stale window — concurrent
        // writers / split-brain. The heartbeat must instead retry and resume
        // refreshing once the file is readable again.
        let (_dir, path) = test_lock_path();
        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
        let owner = guard.metadata.clone();

        // Corrupt the lockfile out from under the heartbeat (simulates a
        // concurrent-writer race producing a momentarily-unparseable read).
        // The heartbeat reads-then-writes, so it observes Malformed and, with
        // the fix, retries instead of dying. The corruption keeps the lease's
        // byte length: a length change takes the process-wide replacement path,
        // which releases the beat's kept handle and leaves the ownership check
        // to the next open, and this test is about retrying a read that failed.
        let live = fs::read(&path).expect("read live lease");
        fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lockfile");

        // Give the heartbeat several intervals to observe the malformed file.
        // Pre-fix, the thread is dead by now.
        thread::sleep(Duration::from_millis(
            test_config().heartbeat_interval_ms * 4,
        ));

        // Restore the owner's own lease bytes with a clearly-stale heartbeat
        // timestamp. The replacement bytes keep the lease's byte length, so the
        // next beat takes its in-place path. The restore's timestamp only has to
        // be older than the beat that follows, so a value from before the
        // corruption is enough.
        let mut restored = owner.clone();
        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
        let sentinel = restored.heartbeat_at_ms;
        // Use an atomic replacement to exercise reopening the lease, rather
        // than only rewriting the inode that the heartbeat previously held.
        {
            let bytes = lock_metadata_bytes(&restored).expect("serialize restored metadata");
            with_lease_handles_closed(&path, || replace_lock_bytes_unsynced(&path, &bytes))
                .expect("restore lock metadata");
        }

        // If the heartbeat thread is still alive (the fix), it will overwrite
        // heartbeat_at_ms with a current value. Poll for that recovery. The
        // window covers the beat that finds the restored lease but is still
        // failing on the earlier corrupt state, plus several retries after it.
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        let mut recovered = false;
        while std::time::Instant::now() < deadline {
            thread::sleep(Duration::from_millis(25));
            match read_lock_metadata(&path) {
                Ok(meta)
                    if meta.created_at_ms == owner.created_at_ms
                        && meta.heartbeat_at_ms > sentinel =>
                {
                    recovered = true;
                    break;
                }
                _ => continue,
            }
        }
        assert!(
            recovered,
            "heartbeat did not recover after a transient malformed read — thread likely died: \
             stopped={} visible={} on_disk={:?}",
            guard.pump.heartbeat_stopped(),
            guard.heartbeat_is_visible(),
            read_lock_metadata(&path)
        );
        drop(guard);
    }
}