hermit-run 0.5.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
use std::cell::RefCell;
use std::panic::AssertUnwindSafe;
use std::sync::Barrier;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use super::*;

type Records = Arc<Mutex<Vec<Vec<u8>>>>;

fn baseline_limits() -> FormatterLimits {
    FormatterLimits::new(4096, 1024).unwrap()
}

fn record_subscriber<Sink>(
    filter: EnvFilter,
    ansi: bool,
    sink: Sink,
) -> (impl Subscriber + Send + Sync, RecordStatus)
where
    Sink: Fn(&[u8]) -> io::Result<()> + Send + Sync + 'static,
{
    assert!(!ansi, "complete records have canonical non-ANSI formatting");
    super::record_subscriber_with_failure(filter, baseline_limits(), sink, || {})
}

struct TestFormat<Timer = SystemTime> {
    timer: Timer,
    timestamp: bool,
}
fn format() -> TestFormat {
    TestFormat {
        timer: SystemTime,
        timestamp: true,
    }
}
impl<Timer> TestFormat<Timer> {
    fn with_timer<T>(self, timer: T) -> TestFormat<T> {
        TestFormat {
            timer,
            timestamp: self.timestamp,
        }
    }
    fn without_time(self) -> TestFormat<()> {
        TestFormat {
            timer: (),
            timestamp: false,
        }
    }
}

fn subscriber_with_format<Sink, Timer>(
    filter: EnvFilter,
    ansi: bool,
    sink: Sink,
    formatter: TestFormat<Timer>,
) -> (impl Subscriber + Send + Sync, RecordStatus)
where
    Sink: Fn(&[u8]) -> io::Result<()> + Send + Sync + 'static,
    Timer: FormatTime + Send + Sync + 'static,
{
    assert!(!ansi);
    super::subscriber_with_status(
        filter,
        baseline_limits(),
        sink,
        formatter.timer,
        formatter.timestamp,
        RecordStatus::default(),
    )
}

fn filter() -> EnvFilter {
    EnvFilter::new("host_record=info").add_directive(tracing::metadata::LevelFilter::OFF.into())
}

#[test]
fn failed_complete_record_notifies_transport_once_before_returning() {
    let records = Records::default();
    let notifications = Arc::new(AtomicUsize::new(0));
    let seen = notifications.clone();
    let (subscriber, status) = super::record_subscriber_with_failure(
        filter(),
        baseline_limits(),
        capture(&records),
        move || {
            seen.fetch_add(1, Ordering::SeqCst);
        },
    );
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", broken = ?BrokenFormat);
        assert_eq!(notifications.load(Ordering::SeqCst), 1);
        tracing::info!(target: "host_record", "refused-after-failure");
    });
    assert!(status.failure().is_some());
    assert_eq!(notifications.load(Ordering::SeqCst), 1);
    assert!(records.lock().unwrap().is_empty());
}

fn capture(records: &Records) -> impl Fn(&[u8]) -> io::Result<()> + Send + Sync + 'static {
    let records = records.clone();
    move |bytes| {
        records.lock().unwrap().push(bytes.to_vec());
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
struct FixedTime;

impl tracing_subscriber::fmt::time::FormatTime for FixedTime {
    fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
        writer.write_str("unchanged-time")
    }
}

struct Chunks;

impl fmt::Debug for Chunks {
    fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
        writer.write_str("first")?;
        writer.write_str("\nsecond")?;
        writer.write_str("\x1b[31mthird")
    }
}

fn structured_events() {
    let span =
        tracing::info_span!(target: "host_record", "work", task = 7, later = tracing::field::Empty);
    let _entered = span.enter();
    tracing::info!(target: "host_record", chunks = ?Chunks, number = 1.0, "multi\nline");
    span.record("later", 9);
    tracing::info!(target: "host_record", "after span update");
    tracing::debug!(target: "host_record", "must remain filtered");
    tracing::warn!(target: "other_record", "must remain filtered too");
}

#[test]
fn public_preparation_is_scoped_and_drop_does_not_publish() {
    let records = Records::default();
    let (subscriber, status) = record_subscriber(filter(), false, capture(&records));
    assert!(records.lock().unwrap().is_empty());
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", "public host record");
    });
    let records = records.lock().unwrap();
    assert_eq!(records.len(), 1);
    assert!(
        String::from_utf8_lossy(&records[0]).ends_with("INFO host_record: public host record\n")
    );
    assert!(status.failure().is_none());
}

struct BrokenFormat;

impl fmt::Debug for BrokenFormat {
    fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
        writer.write_str("partial format must not commit")?;
        Err(fmt::Error)
    }
}

#[test]
fn formatting_error_rejects_partial_and_later_records() {
    let records = Records::default();
    let (subscriber, status) = record_subscriber(filter(), false, capture(&records));
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", broken = ?BrokenFormat);
        tracing::info!(target: "host_record", "not silently recovered");
    });
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Formatting)
    ));
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn span_creation_and_update_errors_are_inspectable() {
    for update in [false, true] {
        let records = Records::default();
        let (subscriber, status) = record_subscriber(filter(), false, capture(&records));
        tracing::subscriber::with_default(subscriber, || {
            if update {
                let span = tracing::info_span!(target: "host_record", "broken", value = tracing::field::Empty);
                span.record("value", tracing::field::debug(BrokenFormat));
                let _entered = span.enter();
                tracing::info!(target: "host_record", "in malformed span");
            } else {
                let span =
                    tracing::info_span!(target: "host_record", "broken", value = ?BrokenFormat);
                let _entered = span.enter();
                tracing::info!(target: "host_record", "in malformed span");
            }
        });
        assert!(matches!(
            status.failure().as_deref(),
            Some(RecordFailure::Formatting)
        ));
        assert!(records.lock().unwrap().is_empty());
    }
}

#[test]
fn partial_sink_error_is_sticky_and_never_retried() {
    struct Partial(Vec<u8>);
    impl Write for Partial {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            if self.0.is_empty() {
                self.0.extend_from_slice(&bytes[..3]);
                Ok(3)
            } else {
                Err(io::Error::new(io::ErrorKind::BrokenPipe, "after prefix"))
            }
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    let partial = Arc::new(Mutex::new(Partial(Vec::new())));
    let attempted = Records::default();
    let attempts = Arc::new(AtomicUsize::new(0));
    let sink = partial.clone();
    let calls = attempts.clone();
    let attempted_record = attempted.clone();
    let (subscriber, status) = record_subscriber(filter(), false, move |bytes| {
        calls.fetch_add(1, Ordering::Relaxed);
        attempted_record.lock().unwrap().push(bytes.to_vec());
        sink.lock().unwrap().write_all(bytes)
    });
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", "partially accepted");
        tracing::info!(target: "host_record", "no automatic replay");
    });
    assert_eq!(attempts.load(Ordering::Relaxed), 1);
    assert_eq!(partial.lock().unwrap().0.len(), 3);
    assert_eq!(attempted.lock().unwrap().len(), 1);
    assert_eq!(partial.lock().unwrap().0, attempted.lock().unwrap()[0][..3]);
    let failure = status.failure().unwrap();
    let RecordFailure::Sink(error) = failure.as_ref() else {
        panic!("missing sink cause")
    };
    assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
    assert_eq!(error.to_string(), "after prefix");
}

#[test]
fn interrupted_record_commit_is_not_retried_like_a_byte_write() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let calls = attempts.clone();
    let (subscriber, status) = record_subscriber(filter(), false, move |_| {
        calls.fetch_add(1, Ordering::Relaxed);
        Err(io::Error::from(io::ErrorKind::Interrupted))
    });
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", "uncertain commit");
    });
    assert_eq!(attempts.load(Ordering::Relaxed), 1);
    assert!(
        matches!(status.failure().as_deref(), Some(RecordFailure::Sink(error)) if error.kind() == io::ErrorKind::Interrupted)
    );
}

#[test]
fn unused_writer_flush_and_drop_do_not_commit_or_finalize() {
    let records = Records::default();
    let factory = RecordWriterFactory {
        sink: capture(&records),
        status: RecordStatus::default(),
    };
    {
        let mut writer = factory.make_writer();
        writer.flush().unwrap();
    }
    assert!(records.lock().unwrap().is_empty());
    {
        let mut writer = factory.make_writer();
        writer.write_all(b"complete\nmultiline\n").unwrap();
        writer.flush().unwrap();
    }
    assert_eq!(
        *records.lock().unwrap(),
        [b"complete\nmultiline\n".to_vec()]
    );
}

#[test]
fn concurrent_records_are_distinct_not_a_determinism_claim() {
    let records = Records::default();
    let (subscriber, status) =
        subscriber_with_format(filter(), false, capture(&records), format().without_time());
    let dispatch = tracing::Dispatch::new(subscriber);
    let barrier = Arc::new(Barrier::new(4));
    std::thread::scope(|scope| {
        for producer in 0..4 {
            let barrier = barrier.clone();
            let dispatch = dispatch.clone();
            scope.spawn(move || {
                tracing::dispatcher::with_default(&dispatch, || {
                    barrier.wait();
                    for sequence in 0..16 {
                        tracing::info!(target: "host_record", producer, sequence, "distinct");
                    }
                });
            });
        }
    });
    let records = records.lock().unwrap();
    assert_eq!(records.len(), 64);
    for producer in 0..4 {
        for sequence in 0..16 {
            let expected =
                format!(" INFO host_record: distinct producer={producer} sequence={sequence}\n");
            assert_eq!(
                records
                    .iter()
                    .filter(|record| **record == expected.as_bytes())
                    .count(),
                1
            );
        }
    }
    assert!(status.failure().is_none());
}

#[test]
fn formatting_unwind_is_preserved_and_cannot_publish_stale_buffer() {
    struct Panics;
    impl fmt::Debug for Panics {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("unfinished")?;
            panic!("format panic")
        }
    }
    let records = Records::default();
    let (subscriber, status) = record_subscriber(filter(), false, capture(&records));
    tracing::subscriber::with_default(subscriber, || {
        assert!(
            std::panic::catch_unwind(|| tracing::info!(target: "host_record", value = ?Panics))
                .is_err()
        );
        tracing::info!(target: "host_record", "must not inherit stale formatting");
    });
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Unwinding)
    ));
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn sink_unwind_is_preserved_and_status_outlives_subscriber() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let calls = attempts.clone();
    let (subscriber, status) = record_subscriber(filter(), false, move |_| {
        calls.fetch_add(1, Ordering::Relaxed);
        panic!("sink panic")
    });
    assert!(
        std::panic::catch_unwind(AssertUnwindSafe(|| {
            tracing::subscriber::with_default(
                subscriber,
                || tracing::info!(target: "host_record", "panics"),
            );
        }))
        .is_err()
    );
    assert_eq!(attempts.load(Ordering::Relaxed), 1);
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Unwinding)
    ));
}

#[test]
fn reentry_is_rejected_without_holding_a_sink_lock() {
    let status = RecordStatus::default();
    let records = Records::default();
    let sink = capture(&records);
    let nested_status = status.clone();
    let factory = RecordWriterFactory {
        status: status.clone(),
        sink: move |_: &[u8]| {
            let nested = RecordWriterFactory {
                sink: &sink,
                status: nested_status.clone(),
            };
            assert!(nested.make_writer().write_all(b"recursive").is_err());
            Ok(())
        },
    };
    factory.make_writer().write_all(b"outer").unwrap();
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Reentrant)
    ));
    assert!(records.lock().unwrap().is_empty());
    assert!(with_active(&RecordStatus::default(), || Ok(())).is_ok());
}

#[test]
fn real_formatting_reentry_poison_prevents_outer_commit() {
    struct Reenters(RecordStatus);
    impl fmt::Debug for Reenters {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            let nested = RecordWriterFactory {
                status: self.0.clone(),
                sink: |_: &[u8]| panic!("reentrant sink must not be reached"),
            };
            assert!(nested.make_writer().write_all(b"recursive").is_err());
            writer.write_str("outer formatting continued")
        }
    }
    let records = Records::default();
    let (subscriber, status) = record_subscriber(filter(), false, capture(&records));
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", value = ?Reenters(status.clone()));
    });
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Reentrant)
    ));
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn later_sink_error_is_dropped_without_holding_the_status_lock() {
    struct ObserveDrop {
        status: RecordStatus,
        observed: Arc<AtomicUsize>,
    }
    impl fmt::Debug for ObserveDrop {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("later error")
        }
    }
    impl fmt::Display for ObserveDrop {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt::Debug::fmt(self, writer)
        }
    }
    impl std::error::Error for ObserveDrop {}
    impl Drop for ObserveDrop {
        fn drop(&mut self) {
            assert!(self.status.failure().is_some());
            self.observed.fetch_add(1, Ordering::Relaxed);
        }
    }
    let status = RecordStatus::default();
    let observed = Arc::new(AtomicUsize::new(0));
    status.fail(RecordFailure::Formatting);
    status.fail(RecordFailure::Sink(io::Error::other(ObserveDrop {
        status: status.clone(),
        observed: observed.clone(),
    })));
    assert_eq!(observed.load(Ordering::Relaxed), 1);
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Formatting)
    ));
}

fn bounded_subscriber(
    records: &Records,
    event_bytes: usize,
    span_bytes: usize,
) -> (impl Subscriber + Send + Sync, RecordStatus) {
    super::subscriber_with_status(
        filter(),
        FormatterLimits::new(event_bytes, span_bytes).unwrap(),
        capture(records),
        (),
        false,
        RecordStatus::default(),
    )
}

fn cached_span(span: &tracing::Span) -> (String, usize) {
    span.with_subscriber(|(identity, dispatch)| {
        let registry = dispatch
            .downcast_ref::<tracing_subscriber::Registry>()
            .unwrap();
        let span = registry.span(identity).unwrap();
        let extensions = span.extensions();
        let caches = extensions.get::<SpanCaches>().unwrap();
        assert_eq!(
            caches.0.len(),
            1,
            "this helper inspects a single-layer fixture"
        );
        let state = caches.0[0].1.0.lock().unwrap();
        (state.fields.fields.clone(), state.fields.fields.capacity())
    })
    .unwrap()
}

#[test]
fn formatter_limits_refuse_zero_and_overflow_without_allocating() {
    for (event, span) in [
        (0, 1),
        (1, 0),
        (usize::MAX, 1),
        (1, usize::MAX),
        (isize::MAX as usize, 1),
    ] {
        assert_eq!(
            FormatterLimits::new(event, span).unwrap_err().kind(),
            io::ErrorKind::InvalidInput
        );
    }
    assert!(FormatterLimits::new(1, 1).is_ok());
}

#[test]
fn fixed_storage_rejects_before_copy_and_stays_poisoned() {
    use std::fmt::Write as _;

    let status = RecordStatus::default();
    let mut buffer = BoundedBuffer::new(3, BufferKind::Event, &status).unwrap();
    assert_eq!(buffer.bytes.len(), 0);
    assert_eq!(buffer.bytes.capacity(), 3);
    let pointer = buffer.bytes.as_ptr();
    buffer.write_str("é").unwrap();
    assert_eq!(buffer.text(), "é");
    assert!(buffer.write_str("é").is_err());
    assert_eq!(buffer.text(), "é");
    assert_eq!(buffer.bytes.len(), 2);
    assert!(buffer.write_str("x").is_err());
    assert_eq!(buffer.bytes, "é".as_bytes());
    assert_eq!(buffer.bytes.capacity(), 3);
    assert_eq!(buffer.bytes.as_ptr(), pointer);
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Event,
            limit: 3
        })
    ));
}

#[test]
fn fixed_storage_moves_to_string_without_capacity_growth() {
    use std::fmt::Write as _;

    for capacity in [1, 3, 8, 31, 1024] {
        let status = RecordStatus::default();
        let mut buffer = BoundedBuffer::new(capacity, BufferKind::Span, &status).unwrap();
        buffer.write_str("x").unwrap();
        let text = buffer.into_string();
        assert_eq!(text, "x");
        assert_eq!(text.capacity(), capacity);
        assert!(status.failure().is_none());
    }
}

#[test]
fn real_event_exact_boundary_and_one_byte_overflow() {
    let expected = b" INFO host_record: exact\n";
    for limit in [expected.len(), expected.len() - 1] {
        let records = Records::default();
        let (subscriber, status) = bounded_subscriber(&records, limit, 32);
        tracing::subscriber::with_default(
            subscriber,
            || tracing::info!(target: "host_record", "exact"),
        );
        if limit == expected.len() {
            assert_eq!(*records.lock().unwrap(), [expected.to_vec()]);
            assert!(status.failure().is_none());
        } else {
            assert!(records.lock().unwrap().is_empty());
            assert!(
                matches!(status.failure().as_deref(), Some(RecordFailure::Size { buffer: BufferKind::Event, limit: found }) if *found == limit)
            );
        }
    }
}

#[test]
fn oversized_single_field_refuses_without_partial_sink_record() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 32, 32);
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", "{}", "x".repeat(256));
        tracing::info!(target: "host_record", "later");
    });
    assert!(records.lock().unwrap().is_empty());
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Event,
            limit: 32
        })
    ));
}

#[test]
fn ignored_chunk_errors_cannot_turn_oversize_into_success() {
    struct Ignores(Arc<AtomicUsize>);
    impl fmt::Debug for Ignores {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            for _ in 0..16 {
                self.0.fetch_add(1, Ordering::Relaxed);
                let _ = writer.write_str("xxxxxxxxxxxxxxxx");
            }
            Ok(())
        }
    }
    let calls = Arc::new(AtomicUsize::new(0));
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 64, 32);
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", value = ?Ignores(calls.clone()));
    });
    assert_eq!(calls.load(Ordering::Relaxed), 16);
    assert!(records.lock().unwrap().is_empty());
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Event,
            limit: 64
        })
    ));
}

#[test]
fn span_cache_exact_total_bound_and_failed_update_is_unchanged() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 7);
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", v = 1);
        let initial = cached_span(&span);
        assert_eq!(initial.0, "v=1");
        assert!(initial.1 <= 8);
        span.record("v", 2);
        assert_eq!(cached_span(&span), ("v=1 v=2".to_owned(), 7));
        let _entered = span.enter();
        tracing::info!(target: "host_record", "at boundary");
        span.record("v", 3);
        assert_eq!(cached_span(&span), ("v=1 v=2".to_owned(), 7));
        tracing::info!(target: "host_record", "must not publish");
    });
    assert_eq!(
        *records.lock().unwrap(),
        [b" INFO small{v=1 v=2}: host_record: at boundary\n".to_vec()]
    );
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Span,
            limit: 7
        })
    ));
}

#[test]
fn span_update_counts_separator_before_appending() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 3);
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", v = 1);
        let before = cached_span(&span);
        span.record("v", 2);
        assert_eq!(cached_span(&span), before);
    });
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Span,
            limit: 3
        })
    ));
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn oversized_initial_span_and_updates_never_keep_partial_bytes() {
    for update in [false, true] {
        let records = Records::default();
        let (subscriber, status) = bounded_subscriber(&records, 128, 8);
        tracing::subscriber::with_default(subscriber, || {
            if update {
                let span = tracing::info_span!(target: "host_record", "small", value = tracing::field::Empty);
                let before = cached_span(&span);
                span.record("value", "far too large for the span cache");
                assert_eq!(cached_span(&span), before);
            } else {
                let span = tracing::info_span!(target: "host_record", "small", value = "far too large for the span cache");
                assert_eq!(cached_span(&span), (String::new(), 0));
            }
            tracing::info!(target: "host_record", "refused");
        });
        assert!(matches!(
            status.failure().as_deref(),
            Some(RecordFailure::Size {
                buffer: BufferKind::Span,
                limit: 8
            })
        ));
        assert!(records.lock().unwrap().is_empty());
    }
}

#[test]
fn utf8_span_exact_boundary_preserves_whole_value() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 6);
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", v = "é");
        assert_eq!(cached_span(&span).0, "v=\"é\"");
        let _entered = span.enter();
        tracing::info!(target: "host_record", "UTF-8");
    });
    assert!(status.failure().is_none());
    assert_eq!(
        *records.lock().unwrap(),
        [" INFO small{v=\"é\"}: host_record: UTF-8\n"
            .as_bytes()
            .to_vec()]
    );
}

#[test]
fn formatting_occurs_once_per_new_value_not_a_sizing_pass() {
    struct Once(Arc<AtomicUsize>);
    impl fmt::Debug for Once {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            let observed = self.0.fetch_add(1, Ordering::Relaxed);
            write!(writer, "value-{observed}")
        }
    }
    let calls = Arc::new(AtomicUsize::new(0));
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 256, 128);
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "once", value = ?Once(calls.clone()));
        span.record("value", tracing::field::debug(Once(calls.clone())));
        let _entered = span.enter();
        tracing::info!(target: "host_record", value = ?Once(calls.clone()), "once");
    });
    assert_eq!(calls.load(Ordering::Relaxed), 3);
    assert!(status.failure().is_none());
    assert_eq!(
        *records.lock().unwrap(),
        [b" INFO once{value=value-0 value=value-1}: host_record: once value=value-2\n".to_vec()]
    );
}

#[test]
fn commit_adapter_also_refuses_oversize_before_sink() {
    let records = Records::default();
    let factory = RecordWriterFactory {
        sink: capture(&records),
        status: RecordStatus::default(),
    };
    assert!(factory.write_record(b"too large", 3).is_err());
    assert!(records.lock().unwrap().is_empty());
    assert!(matches!(
        factory.status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Event,
            limit: 3
        })
    ));
}

#[test]
fn event_fields_are_not_subject_to_the_smaller_span_budget() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 1);
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", value = 123456, "event only");
    });
    assert!(status.failure().is_none());
    assert_eq!(
        *records.lock().unwrap(),
        [b" INFO host_record: event only value=123456\n".to_vec()]
    );
}

#[test]
fn cached_span_prefixes_are_included_in_the_event_budget() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 32, 16);
    tracing::subscriber::with_default(subscriber, || {
        let outer = tracing::info_span!(target: "host_record", "outer", value = 1);
        let _outer = outer.enter();
        let inner = tracing::info_span!(target: "host_record", "inner", value = 2);
        let _inner = inner.enter();
        assert_eq!(cached_span(&outer).0, "value=1");
        assert_eq!(cached_span(&inner).0, "value=2");
        tracing::info!(target: "host_record", "too much combined output");
    });
    assert!(records.lock().unwrap().is_empty());
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Event,
            limit: 32
        })
    ));
}

#[test]
fn ignored_span_errors_cannot_commit_partial_cache() {
    struct Ignores;
    impl fmt::Debug for Ignores {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            for _ in 0..8 {
                let _ = writer.write_str("xxxxxxxx");
            }
            Ok(())
        }
    }
    for update in [false, true] {
        let records = Records::default();
        let (subscriber, status) = bounded_subscriber(&records, 128, 16);
        tracing::subscriber::with_default(subscriber, || {
            if update {
                let span = tracing::info_span!(target: "host_record", "small", value = 1);
                let before = cached_span(&span);
                span.record("value", tracing::field::debug(Ignores));
                assert_eq!(cached_span(&span), before);
            } else {
                let span = tracing::info_span!(target: "host_record", "small", value = ?Ignores);
                assert_eq!(cached_span(&span), (String::new(), 0));
            }
        });
        assert!(records.lock().unwrap().is_empty());
        assert!(matches!(
            status.failure().as_deref(),
            Some(RecordFailure::Size {
                buffer: BufferKind::Span,
                limit: 16
            })
        ));
    }
}

#[test]
fn panicking_span_update_preserves_cache_without_poisoning_registry() {
    let expected_poisoning = match std::env::var("HERMIT_FORMATTER_TEST_REGISTRY_LOCK") {
        Ok(lock) if lock == "std" => Some(true),
        Ok(lock) if lock == "parking_lot" => Some(false),
        Err(std::env::VarError::NotPresent) => None,
        other => panic!("invalid formatter test registry lock contract: {other:?}"),
    };
    assert_span_update_panic_contract(expected_poisoning);
}

fn assert_span_update_panic_contract(expected_poisoning: Option<bool>) {
    struct Panics;
    impl fmt::Debug for Panics {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("partial")?;
            panic!("span update panic")
        }
    }
    fn exercise(check_cache: bool) -> (String, bool) {
        let span = tracing::info_span!(target: "host_record", "small", value = 1);
        let before = check_cache.then(|| cached_span(&span));
        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| {
            span.record("value", tracing::field::debug(Panics));
        }))
        .unwrap_err();
        let message = panic.downcast_ref::<&str>().unwrap().to_string();
        let poisoned = std::panic::catch_unwind(AssertUnwindSafe(|| {
            span.with_subscriber(|(identity, dispatch)| {
                let registry = dispatch
                    .downcast_ref::<tracing_subscriber::Registry>()
                    .unwrap();
                let span = registry.span(identity).unwrap();
                let _extensions = span.extensions();
            });
        }))
        .is_err();
        if let Some(before) = before {
            assert_eq!(cached_span(&span), before);
        }
        (message, poisoned)
    }

    let original = tracing_subscriber::fmt()
        .with_env_filter(filter())
        .with_writer(io::sink)
        .finish();
    let baseline = tracing::subscriber::with_default(original, || exercise(false));
    assert_eq!(baseline.0, "span update panic");
    if let Some(expected) = expected_poisoning {
        assert_eq!(baseline.1, expected);
    }
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 32);
    tracing::subscriber::with_default(subscriber, || {
        let observed = exercise(true);
        assert_eq!(observed.0, baseline.0);
        assert!(
            !observed.1,
            "user formatting must not poison Registry locks"
        );
        tracing::info!(target: "host_record", "not a recovered record");
    });
    assert!(records.lock().unwrap().is_empty());
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Unwinding)
    ));
}

struct AllocationControl {
    attempts: usize,
    refuse: Option<usize>,
    before: Option<Box<dyn FnOnce()>>,
}

thread_local! {
    static PAYLOAD_ALLOCATIONS: RefCell<Option<AllocationControl>> = const { RefCell::new(None) };
}

struct PayloadAllocations;

impl PayloadAllocations {
    fn new(refuse: Option<usize>) -> Self {
        PAYLOAD_ALLOCATIONS.with(|control| {
            assert!(control.borrow().is_none());
            *control.borrow_mut() = Some(AllocationControl {
                attempts: 0,
                refuse,
                before: None,
            });
        });
        Self
    }

    fn attempts(&self) -> usize {
        PAYLOAD_ALLOCATIONS.with(|control| control.borrow().as_ref().unwrap().attempts)
    }
}

impl Drop for PayloadAllocations {
    fn drop(&mut self) {
        PAYLOAD_ALLOCATIONS.with(|control| *control.borrow_mut() = None);
    }
}

pub(super) fn before_payload_allocation() -> Result<(), std::collections::TryReserveError> {
    let before = PAYLOAD_ALLOCATIONS
        .try_with(|control| {
            control
                .borrow_mut()
                .as_mut()
                .and_then(|control| control.before.take())
        })
        .ok()
        .flatten();
    if let Some(before) = before {
        before();
    }
    let refused = PAYLOAD_ALLOCATIONS
        .try_with(|control| {
            let mut control = control.borrow_mut();
            let Some(control) = control.as_mut() else {
                return false;
            };
            control.attempts += 1;
            control.refuse == Some(control.attempts)
        })
        .unwrap_or(false);
    if refused {
        Vec::<u8>::new().try_reserve_exact(usize::MAX)
    } else {
        Ok(())
    }
}

fn remove_span_cache(span: &tracing::Span) {
    span.with_subscriber(|(identity, dispatch)| {
        let registry = dispatch
            .downcast_ref::<tracing_subscriber::Registry>()
            .unwrap();
        let span = registry.span(identity).unwrap();
        let caches = span.extensions_mut().remove::<SpanCaches>().unwrap();
        assert_eq!(
            caches.0.len(),
            1,
            "this helper removes a single-layer cache"
        );
    })
    .unwrap();
}

fn allocation_failure(status: &RecordStatus) -> Arc<RecordFailure> {
    let failure = status.failure().unwrap();
    assert!(matches!(&*failure, RecordFailure::Allocation));
    failure
}

#[test]
fn event_scratch_allocation_refusal_is_sticky_and_never_publishes() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 32);
    let allocations = PayloadAllocations::new(Some(1));
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(target: "host_record", "refused before formatting");
        let first = allocation_failure(&status);
        tracing::info!(target: "host_record", "subsequent refusal");
        assert!(Arc::ptr_eq(&first, &allocation_failure(&status)));
    });
    assert_eq!(allocations.attempts(), 1);
    allocation_failure(&status);
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn initial_cache_backing_allocation_refusal_keeps_empty_fields_and_status() {
    struct Counted<'count>(&'count AtomicUsize);
    impl fmt::Debug for Counted<'_> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("value")
        }
    }
    let calls = AtomicUsize::new(0);
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 32);
    let allocations = PayloadAllocations::new(Some(1));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", value = ?Counted(&calls));
        assert_eq!(cached_span(&span), (String::new(), 0));
        let first = allocation_failure(&status);
        span.record("value", tracing::field::debug(Counted(&calls)));
        assert_eq!(cached_span(&span), (String::new(), 0));
        let later = tracing::info_span!(target: "host_record", "later", value = ?Counted(&calls));
        assert_eq!(cached_span(&later), (String::new(), 0));
        tracing::info!(target: "host_record", "cannot publish");
        assert!(Arc::ptr_eq(&first, &allocation_failure(&status)));
    });
    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert_eq!(allocations.attempts(), 1);
    allocation_failure(&status);
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn update_scratch_allocation_refusal_preserves_complete_previous_cache() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 32);
    let allocations = PayloadAllocations::new(Some(2));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", value = 1);
        let before = cached_span(&span);
        assert_eq!(before, ("value=1".to_owned(), 32));
        assert!(status.failure().is_none());
        span.record("value", 2);
        assert_eq!(cached_span(&span), before);
        let first = allocation_failure(&status);
        span.record("value", 3);
        assert_eq!(cached_span(&span), before);
        tracing::info!(target: "host_record", "cannot publish");
        assert!(Arc::ptr_eq(&first, &allocation_failure(&status)));
    });
    assert_eq!(allocations.attempts(), 2);
    allocation_failure(&status);
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn missing_cache_on_record_uses_the_same_fallible_initial_hook() {
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 32);
    let allocations = PayloadAllocations::new(Some(2));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "small", value = 1);
        remove_span_cache(&span);
        span.record("value", 2);
        assert_eq!(cached_span(&span), (String::new(), 0));
        let first = allocation_failure(&status);
        span.record("value", 3);
        assert_eq!(cached_span(&span), (String::new(), 0));
        tracing::info!(target: "host_record", "cannot publish");
        assert!(Arc::ptr_eq(&first, &allocation_failure(&status)));
    });
    assert_eq!(allocations.attempts(), 2);
    allocation_failure(&status);
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn initial_cache_has_exact_capacity_and_no_second_payload_allocation() {
    for limit in [3, 7, 8, 31, 1024] {
        let records = Records::default();
        let (subscriber, status) = bounded_subscriber(&records, 128, limit);
        let allocations = PayloadAllocations::new(Some(2));
        tracing::subscriber::with_default(subscriber, || {
            let span = tracing::info_span!(target: "host_record", "small", v = 1);
            assert_eq!(cached_span(&span), ("v=1".to_owned(), limit));
        });
        assert_eq!(allocations.attempts(), 1);
        assert!(status.failure().is_none());
        assert!(records.lock().unwrap().is_empty());
    }
}

#[test]
fn owned_scratch_transfer_preserves_allocation_identity_and_utf8() {
    use std::fmt::Write as _;

    let status = RecordStatus::default();
    let allocations = PayloadAllocations::new(Some(2));
    let mut buffer = BoundedBuffer::new(7, BufferKind::Span, &status).unwrap();
    buffer.write_str("é").unwrap();
    let pointer = buffer.bytes.as_ptr();
    let text = buffer.into_string();
    assert_eq!(text.as_ptr(), pointer);
    assert_eq!(text, "é");
    assert_eq!(text.capacity(), 7);
    assert_eq!(allocations.attempts(), 1);
    assert!(status.failure().is_none());
}

#[derive(Clone, Default)]
struct Output(Arc<Mutex<Vec<u8>>>);

impl Write for Output {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(bytes);
        Ok(bytes.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn compare_with_stock(filter_text: &str, emit: impl Fn()) -> Vec<Vec<u8>> {
    let expected = Output::default();
    let writer = expected.clone();
    let stock = tracing_subscriber::fmt()
        .with_timer(FixedTime)
        .with_env_filter(EnvFilter::new(filter_text))
        .with_ansi(false)
        .with_writer(move || writer.clone())
        .finish();
    tracing::subscriber::with_default(stock, &emit);
    let records = Records::default();
    let (subscriber, status) = subscriber_with_format(
        EnvFilter::new(filter_text),
        false,
        capture(&records),
        format().with_timer(FixedTime),
    );
    tracing::subscriber::with_default(subscriber, emit);
    let records = records.lock().unwrap().clone();
    assert_eq!(records.concat(), *expected.0.lock().unwrap());
    assert!(status.failure().is_none());
    records
}

#[test]
fn complete_records_during_unrelated_outer_unwind_match_stock() {
    struct EmitOnDrop;

    impl Drop for EmitOnDrop {
        fn drop(&mut self) {
            tracing::info!(target: "host_record", "outer panic event");
            let span = tracing::info_span!(target: "host_record", "during_drop", value = 1);
            let _entered = span.enter();
            span.record("value", 2);
            tracing::info!(target: "host_record", "updated span event");
        }
    }

    let records = compare_with_stock("info", || {
        let panic = std::panic::catch_unwind(|| {
            let _emit = EmitOnDrop;
            panic!("unrelated outer panic");
        });
        assert_eq!(
            panic.unwrap_err().downcast_ref::<&str>(),
            Some(&"unrelated outer panic")
        );
        tracing::info!(target: "host_record", "after catch_unwind");
    });
    assert_eq!(
        records,
        [
            b"unchanged-time  INFO host_record: outer panic event\n".to_vec(),
            b"unchanged-time  INFO during_drop{value=1 value=2}: host_record: updated span event\n"
                .to_vec(),
            b"unchanged-time  INFO host_record: after catch_unwind\n".to_vec(),
        ]
    );
}

#[test]
fn complete_bytes_match_stock_fields_spans_filter_and_sanitization() {
    let records = compare_with_stock("off,host_record=info", structured_events);
    assert_eq!(records.len(), 2);
    assert_eq!(records[0], b"unchanged-time  INFO work{task=7}: host_record: multi\nline chunks=first\nsecond\x1b[31mthird number=1.0\n");
    assert_eq!(
        records[1],
        b"unchanged-time  INFO work{task=7 later=9}: host_record: after span update\n"
    );
}

#[test]
fn complete_bytes_match_all_levels_types_errors_and_raw_names() {
    #[derive(Debug)]
    struct Root;
    impl fmt::Display for Root {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("source\x1b[32m")
        }
    }
    impl std::error::Error for Root {}
    #[derive(Debug)]
    struct Failure(Root);
    impl fmt::Display for Failure {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("failure\x1b[31m")
        }
    }
    impl std::error::Error for Failure {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.0)
        }
    }
    let records = compare_with_stock("trace", || {
        tracing::trace!(target: "host_record", "trace");
        tracing::debug!(target: "host_record", "debug");
        tracing::info!(target: "host_record", signed = -2i64, unsigned = 3u64, large = i128::MAX,
            float = 1.25f64, boolean = true, r#type = "é", bytes = ?[0u8, 255], "types");
        tracing::warn!(target: "host_record", "message\x1b[31m");
        let failure = Failure(Root);
        tracing::error!(target: "host_record", error = &failure as &(dyn std::error::Error + 'static), "failed");
    });
    assert_eq!(records.len(), 5);
    assert_eq!(records[0], b"unchanged-time TRACE host_record: trace\n");
    assert_eq!(records[1], b"unchanged-time DEBUG host_record: debug\n");
    assert_eq!(records[2], "unchanged-time  INFO host_record: types signed=-2 unsigned=3 large=170141183460469231731687303715884105727 float=1.25 boolean=true type=\"é\" bytes=[0, 255]\n".as_bytes());
    assert!(!records[3].contains(&0x1b));
    assert!(!records[4].contains(&0x1b));
    assert!(String::from_utf8_lossy(&records[4]).contains("error.sources="));
}

#[test]
fn nested_explicit_and_root_parents_match_stock() {
    let records = compare_with_stock("info", || {
        let root = tracing::info_span!(target: "host_record", "root", id = 1);
        let _root = root.enter();
        let child = tracing::info_span!(target: "host_record", "child", id = 2);
        let _child = child.enter();
        tracing::info!(target: "host_record", "context");
        tracing::info!(target: "host_record", parent: &root, "explicit");
        tracing::info!(target: "host_record", parent: None, "root event");
        root.record("id", 3);
        tracing::info!(target: "host_record", "updated ancestor");
    });
    assert_eq!(
        records,
        [
            b"unchanged-time  INFO root{id=1}:child{id=2}: host_record: context\n".to_vec(),
            b"unchanged-time  INFO root{id=1}: host_record: explicit\n".to_vec(),
            b"unchanged-time  INFO host_record: root event\n".to_vec(),
            b"unchanged-time  INFO root{id=1 id=3}:child{id=2}: host_record: updated ancestor\n"
                .to_vec(),
        ]
    );
}

#[test]
fn dynamic_filter_matching_and_span_updates_match_stock() {
    let records = compare_with_stock("off,host_record[work{task=7}]=info", || {
        tracing::info!(target: "host_record", "outside");
        let rejected = tracing::info_span!(target: "host_record", "work", task = 8);
        rejected.in_scope(|| tracing::info!(target: "host_record", "wrong value"));
        let selected =
            tracing::info_span!(target: "host_record", "work", task = tracing::field::Empty);
        selected.record("task", 7);
        selected.in_scope(|| {
            tracing::info!(target: "host_record", "selected");
            tracing::debug!(target: "host_record", "wrong level");
        });
    });
    assert_eq!(
        records,
        [b"unchanged-time  INFO work{task=7}: host_record: selected\n".to_vec()]
    );
}

#[test]
fn log_bridge_metadata_is_normalized_without_reclassifying_tracing_events() {
    let records = compare_with_stock("trace", || {
        // The public Log implementation creates the real bridge callsite, not a
        // tracing event heuristically identified by its target or field names.
        let record = tracing_log::log::Record::builder()
            .args(format_args!("bridged"))
            .level(tracing_log::log::Level::Info)
            .target("actual_log_target")
            .module_path(Some("source_module"))
            .file(Some("source.rs"))
            .line(Some(27))
            .build();
        tracing_log::log::Log::log(&tracing_log::LogTracer::new(), &record);
        tracing::event!(target: "log", tracing::Level::INFO, { message = "ordinary tracing", log.target = "must_not_replace_target" });
    });
    assert_eq!(
        records,
        [
            b"unchanged-time  INFO actual_log_target: bridged\n".to_vec(),
            b"unchanged-time  INFO log: ordinary tracing\n".to_vec(),
        ]
    );
}

fn stock_layer_output<F>(filter: F, emit: impl FnOnce()) -> Vec<u8>
where
    F: tracing_subscriber::layer::Filter<tracing_subscriber::Registry> + Send + Sync + 'static,
{
    let output = Output::default();
    let writer = output.clone();
    let layer = tracing_subscriber::fmt::layer()
        .with_timer(FixedTime)
        .with_ansi(false)
        .with_writer(move || writer.clone())
        .with_filter(filter);
    tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), emit);
    output.0.lock().unwrap().clone()
}

fn bounded_record_callback_child(test: &str, case: &str) {
    use std::process::Command;
    use std::process::Stdio;
    use std::time::Duration;
    use std::time::Instant;

    let mut child = Command::new(std::env::current_exe().unwrap())
        .args(["--exact", test, "--nocapture", "--test-threads=1"])
        .env("HERMIT_RECORD_LOCK_CASE", case)
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(10);
    while child.try_wait().unwrap().is_none() {
        if Instant::now() >= deadline {
            child.kill().unwrap();
            let output = child.wait_with_output().unwrap();
            panic!("{case}: callback did not return: {output:?}");
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    let output = child.wait_with_output().unwrap();
    assert!(output.status.success(), "{case}: {output:?}");
    assert!(output.stderr.is_empty(), "{case}: {output:?}");
}

// Publish the actual registered ID using a public Layer callback. The writer
// below uses Dispatch::record; it does not manufacture a Span before creation.
struct ObserveInitializingSpan {
    span: std::sync::mpsc::Sender<(Id, &'static tracing::Metadata<'static>)>,
    event: Option<std::sync::mpsc::Sender<()>>,
}

impl<S: Subscriber> Layer<S> for ObserveInitializingSpan {
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, _: Context<'_, S>) {
        self.span.send((id.clone(), attrs.metadata())).unwrap();
    }

    fn on_event(&self, _: &Event<'_>, _: Context<'_, S>) {
        if let Some(event) = &self.event {
            event.send(()).unwrap();
        }
    }
}

fn record_initializing_span(
    dispatch: &tracing::Dispatch,
    id: &Id,
    metadata: &'static tracing::Metadata<'static>,
    value: Option<u64>,
) {
    let field = metadata.fields().field("v").unwrap();
    let empty = tracing::field::Empty;
    let value: &dyn tracing::field::Value = match &value {
        Some(value) => value,
        None => &empty,
    };
    let values = [(&field, Some(value))];
    dispatch.record(id, &Record::new(&metadata.fields().value_set(&values)));
}

thread_local! {
    static BEFORE_SPAN_INITIALIZATION: RefCell<Option<Box<dyn FnOnce()>>> =
        const { RefCell::new(None) };
}

pub(super) fn before_span_initialization() {
    let before = BEFORE_SPAN_INITIALIZATION.with(|control| control.borrow_mut().take());
    if let Some(before) = before {
        before();
    }
}

#[test]
fn records_before_the_new_span_callback_match_stock_without_initial_formatting() {
    use std::sync::mpsc;
    use std::time::Duration;

    const TEST: &str = "liteinst_record::tests::records_before_the_new_span_callback_match_stock_without_initial_formatting";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("before-new-span") {
        bounded_record_callback_child(TEST, "before-new-span");
        return;
    }
    struct Before {
        id: mpsc::Sender<(Id, &'static tracing::Metadata<'static>)>,
        done: Mutex<mpsc::Receiver<()>>,
    }
    impl<S: Subscriber> Layer<S> for Before {
        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, _: Context<'_, S>) {
            self.id.send((id.clone(), attrs.metadata())).unwrap();
            self.done
                .lock()
                .unwrap()
                .recv_timeout(Duration::from_secs(2))
                .unwrap();
        }
    }
    struct Initial(Arc<AtomicUsize>);
    impl fmt::Debug for Initial {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("1")
        }
    }
    for updates in [
        vec![],
        vec![Some(2)],
        vec![None],
        vec![None, None],
        vec![None, None, Some(2), None, Some(3)],
    ] {
        let mut expected = None;
        for stock in [true, false] {
            let output = Output::default();
            let records = Records::default();
            let status = RecordStatus::default();
            let (id_tx, id_rx) = mpsc::channel();
            let (done_tx, done_rx) = mpsc::channel();
            let registry = tracing_subscriber::registry().with(Before {
                id: id_tx,
                done: Mutex::new(done_rx),
            });
            let dispatch = if stock {
                let writer = output.clone();
                tracing::Dispatch::new(
                    registry.with(
                        tracing_subscriber::fmt::layer()
                            .without_time()
                            .with_ansi(false)
                            .with_writer(move || writer.clone()),
                    ),
                )
            } else {
                tracing::Dispatch::new(registry.with(super::layer_with_status(
                    baseline_limits(),
                    capture(&records),
                    (),
                    false,
                    status.clone(),
                )))
            };
            let writer_dispatch = dispatch.clone();
            let values = updates.clone();
            let writer = std::thread::spawn(move || {
                let (id, metadata) = id_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                for value in values {
                    record_initializing_span(&writer_dispatch, &id, metadata, value);
                }
                done_tx.send(()).unwrap();
            });
            let calls = Arc::new(AtomicUsize::new(0));
            tracing::dispatcher::with_default(&dispatch, || {
                let span =
                    tracing::info_span!(target: "host_record", "work", v = ?Initial(calls.clone()));
                writer.join().unwrap();
                tracing::info!(target: "host_record", parent: &span, "created");
            });
            assert_eq!(
                calls.load(Ordering::SeqCst),
                usize::from(updates.is_empty()),
                "stock={stock}, updates={updates:?}"
            );
            assert!(status.failure().is_none());
            if stock {
                let bytes = output.0.lock().unwrap().clone();
                assert_eq!(bytes.iter().filter(|byte| **byte == b'\n').count(), 1);
                assert!(bytes.ends_with(b": host_record: created\n"));
                expected = Some(bytes);
            } else {
                assert_eq!(
                    *records.lock().unwrap(),
                    vec![expected.take().unwrap()],
                    "updates={updates:?}"
                );
            }
        }
    }
}

#[test]
fn events_wait_for_a_record_that_creates_the_first_span_cache() {
    use std::sync::mpsc;
    use std::time::Duration;

    const TEST: &str =
        "liteinst_record::tests::events_wait_for_a_record_that_creates_the_first_span_cache";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("first-record-event") {
        bounded_record_callback_child(TEST, "first-record-event");
        return;
    }
    struct First {
        started: mpsc::Sender<()>,
        release: Mutex<mpsc::Receiver<()>>,
        calls: Arc<AtomicUsize>,
    }
    impl fmt::Debug for First {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            assert_eq!(self.calls.fetch_add(1, Ordering::SeqCst), 0);
            self.started.send(()).unwrap();
            self.release
                .lock()
                .unwrap()
                .recv_timeout(Duration::from_secs(2))
                .unwrap();
            writer.write_str("2")
        }
    }
    struct Before {
        id: mpsc::Sender<Id>,
        first: First,
        event: mpsc::Sender<()>,
        dispatch: Arc<std::sync::OnceLock<tracing::dispatcher::WeakDispatch>>,
    }
    impl<S: Subscriber> Layer<S> for Before {
        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, _: Context<'_, S>) {
            self.id.send(id.clone()).unwrap();
            let field = attrs.metadata().fields().field("v").unwrap();
            let value = tracing::field::debug(&self.first);
            let values = [(&field, Some(&value as &dyn tracing::field::Value))];
            // The ambient dispatcher deliberately suppresses recursive lookup
            // from a callback. Use the actual registered dispatcher explicitly,
            // retaining it weakly so this observer cannot keep it alive forever.
            self.dispatch.get().unwrap().upgrade().unwrap().record(
                id,
                &Record::new(&attrs.metadata().fields().value_set(&values)),
            );
        }

        fn on_event(&self, _: &Event<'_>, _: Context<'_, S>) {
            self.event.send(()).unwrap();
        }
    }
    let mut expected = None;
    for stock in [true, false] {
        let output = Output::default();
        let records = Records::default();
        let status = RecordStatus::default();
        let (id_tx, id_rx) = mpsc::channel();
        let (started_tx, started_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();
        let (event_tx, event_rx) = mpsc::channel();
        let (done_tx, done_rx) = mpsc::channel();
        let calls = Arc::new(AtomicUsize::new(0));
        let observer_dispatch = Arc::new(std::sync::OnceLock::new());
        let registry = tracing_subscriber::registry().with(Before {
            id: id_tx,
            dispatch: observer_dispatch.clone(),
            first: First {
                started: started_tx,
                release: Mutex::new(release_rx),
                calls: calls.clone(),
            },
            event: event_tx,
        });
        let dispatch = if stock {
            let writer = output.clone();
            tracing::Dispatch::new(
                registry.with(
                    tracing_subscriber::fmt::layer()
                        .without_time()
                        .with_ansi(false)
                        .with_writer(move || writer.clone()),
                ),
            )
        } else {
            tracing::Dispatch::new(registry.with(super::layer_with_status(
                baseline_limits(),
                capture(&records),
                (),
                false,
                status.clone(),
            )))
        };
        assert!(observer_dispatch.set(dispatch.downgrade()).is_ok());
        let initializer_dispatch = dispatch.clone();
        let initializer = std::thread::spawn(move || {
            tracing::dispatcher::with_default(
                &initializer_dispatch,
                || tracing::info_span!(target: "host_record", "work", v = 1),
            )
        });
        let id = id_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        let event_dispatch = dispatch.clone();
        let event = std::thread::spawn(move || {
            tracing::dispatcher::with_default(&event_dispatch, || {
                tracing::info!(target: "host_record", parent: &id, "first record");
            });
            done_tx.send(()).unwrap();
        });
        event_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        let early = done_rx.recv_timeout(Duration::from_millis(30));
        let early_stock = output.0.lock().unwrap().clone();
        let early_records = records.lock().unwrap().clone();
        release_tx.send(()).unwrap();
        let span = initializer.join().unwrap();
        event.join().unwrap();
        assert!(
            matches!(early, Err(mpsc::RecvTimeoutError::Timeout)),
            "stock={stock}: event completed before its first fields: {early:?}"
        );
        done_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(early_stock.is_empty());
        assert!(early_records.is_empty());
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert!(status.failure().is_none());
        if stock {
            let bytes = output.0.lock().unwrap().clone();
            assert_eq!(bytes, b" INFO work{v=2}: host_record: first record\n");
            expected = Some(bytes);
        } else {
            assert_eq!(*records.lock().unwrap(), vec![expected.take().unwrap()]);
        }
        drop(span);
    }
}

#[test]
fn span_initialization_keeps_early_updates_and_exact_stock_empty_spaces() {
    use std::sync::mpsc;
    use std::time::Duration;

    const TEST: &str = "liteinst_record::tests::span_initialization_keeps_early_updates_and_exact_stock_empty_spaces";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("initial-updates") {
        bounded_record_callback_child(TEST, "initial-updates");
        return;
    }
    for initial in [None, Some(1)] {
        for updates in [
            vec![None, None],
            vec![None, None, Some(2), None, Some(3)],
            vec![None; 1030],
        ] {
            let expected_overflow = initial.is_some() && updates.len() == 1030;
            let expected_output = Output::default();
            let writer = expected_output.clone();
            let stock = tracing_subscriber::fmt()
                .without_time()
                .with_ansi(false)
                .with_writer(move || writer.clone())
                .finish();
            tracing::subscriber::with_default(stock, || {
                let span = tracing::info_span!(target: "host_record", "work", v = initial);
                for update in &updates {
                    match update {
                        Some(value) => {
                            span.record("v", value);
                        }
                        None => {
                            span.record("v", tracing::field::Empty);
                        }
                    }
                }
                tracing::info!(target: "host_record", parent: &span, "initialized");
            });
            let expected = expected_output.0.lock().unwrap().clone();
            let records = Records::default();
            let status = RecordStatus::default();
            let (id_tx, id_rx) = mpsc::channel();
            let (started_tx, started_rx) = mpsc::channel();
            let (done_tx, done_rx) = mpsc::channel();
            let registry = tracing_subscriber::registry().with(ObserveInitializingSpan {
                span: id_tx,
                event: None,
            });
            let layer = super::layer_with_status(
                baseline_limits(),
                capture(&records),
                (),
                false,
                status.clone(),
            );
            let dispatch = tracing::Dispatch::new(registry.with(layer));
            let writer_dispatch = dispatch.clone();
            let writer = std::thread::spawn(move || {
                let (id, metadata) = id_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                for value in updates {
                    record_initializing_span(&writer_dispatch, &id, metadata, value);
                }
                done_tx.send(()).unwrap();
            });
            tracing::dispatcher::with_default(&dispatch, || {
                let allocations = PayloadAllocations::new(None);
                // Pausing before initial allocation also covers a truly empty
                // initial field set, which has no user Debug callback to pause.
                PAYLOAD_ALLOCATIONS.with(|control| {
                    control.borrow_mut().as_mut().unwrap().before = Some(Box::new(move || {
                        started_tx.send(()).unwrap();
                        done_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                    }));
                });
                let span = tracing::info_span!(target: "host_record", "work", v = initial);
                assert_eq!(allocations.attempts(), 1);
                drop(allocations);
                writer.join().unwrap();
                tracing::info!(target: "host_record", parent: &span, "initialized");
            });
            if expected_overflow {
                assert!(matches!(
                    status.failure().as_deref(),
                    Some(RecordFailure::Size {
                        buffer: BufferKind::Span,
                        limit: 1024,
                    })
                ));
                assert!(records.lock().unwrap().is_empty());
            } else {
                assert!(status.failure().is_none());
                assert_eq!(
                    *records.lock().unwrap(),
                    vec![expected],
                    "initial {initial:?}"
                );
            }
        }
    }
}

#[test]
fn early_span_update_returns_before_initial_debug_and_formats_each_value_once() {
    use std::sync::mpsc;
    use std::time::Duration;

    const TEST: &str = "liteinst_record::tests::early_span_update_returns_before_initial_debug_and_formats_each_value_once";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("initial-debug") {
        bounded_record_callback_child(TEST, "initial-debug");
        return;
    }
    struct Initial {
        started: mpsc::Sender<()>,
        done: Mutex<mpsc::Receiver<()>>,
        calls: Arc<AtomicUsize>,
    }
    impl fmt::Debug for Initial {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            assert_eq!(self.calls.fetch_add(1, Ordering::SeqCst), 0);
            self.started.send(()).unwrap();
            self.done
                .lock()
                .unwrap()
                .recv_timeout(Duration::from_secs(2))
                .unwrap();
            writer.write_str("1")
        }
    }
    let records = Records::default();
    let status = RecordStatus::default();
    let (id_tx, id_rx) = mpsc::channel();
    let (started_tx, started_rx) = mpsc::channel();
    let (done_tx, done_rx) = mpsc::channel();
    let registry = tracing_subscriber::registry().with(ObserveInitializingSpan {
        span: id_tx,
        event: None,
    });
    let layer = super::layer_with_status(
        baseline_limits(),
        capture(&records),
        (),
        false,
        status.clone(),
    );
    let dispatch = tracing::Dispatch::new(registry.with(layer));
    struct Update(Arc<AtomicUsize>);
    impl fmt::Debug for Update {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("2")
        }
    }
    let update_calls = Arc::new(AtomicUsize::new(0));
    let worker_calls = update_calls.clone();
    let worker_dispatch = dispatch.clone();
    let writer = std::thread::spawn(move || {
        let (id, metadata) = id_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        let field = metadata.fields().field("v").unwrap();
        let value = tracing::field::debug(Update(worker_calls));
        let values = [(&field, Some(&value as &dyn tracing::field::Value))];
        worker_dispatch.record(&id, &Record::new(&metadata.fields().value_set(&values)));
        done_tx.send(()).unwrap();
    });
    let calls = Arc::new(AtomicUsize::new(0));
    tracing::dispatcher::with_default(&dispatch, || {
        let span = tracing::info_span!(target: "host_record", "work", v = ?Initial {
            started: started_tx, done: Mutex::new(done_rx), calls: calls.clone(),
        });
        writer.join().unwrap();
        tracing::info!(target: "host_record", parent: &span, "initialized");
    });
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert_eq!(update_calls.load(Ordering::SeqCst), 1);
    assert!(status.failure().is_none());
    assert_eq!(
        *records.lock().unwrap(),
        vec![b" INFO work{v=1 v=2}: host_record: initialized\n".to_vec()]
    );
}

#[test]
fn event_waits_for_span_initialization_and_wakes_before_failure_notification() {
    use std::sync::mpsc;
    use std::time::Duration;

    const TEST: &str = "liteinst_record::tests::event_waits_for_span_initialization_and_wakes_before_failure_notification";
    let cases = [
        "initial-event",
        "initial-publication",
        "initial-error",
        "initial-panic",
        "initial-overflow",
        "initial-allocation",
    ];
    let Ok(case) = std::env::var("HERMIT_RECORD_LOCK_CASE") else {
        for case in cases {
            bounded_record_callback_child(TEST, case);
        }
        return;
    };
    if !cases.contains(&case.as_str()) {
        return;
    }
    std::panic::set_hook(Box::new(|_| {}));
    struct Initial {
        started: mpsc::Sender<()>,
        release: Mutex<mpsc::Receiver<()>>,
        calls: Arc<AtomicUsize>,
        case: String,
    }
    impl fmt::Debug for Initial {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.calls.fetch_add(1, Ordering::SeqCst);
            self.started.send(()).unwrap();
            self.release
                .lock()
                .unwrap()
                .recv_timeout(Duration::from_secs(2))
                .unwrap();
            match self.case.as_str() {
                "initial-error" => Err(fmt::Error),
                "initial-panic" => panic!("initial field panic retained"),
                _ => writer.write_str("1"),
            }
        }
    }
    let records = Records::default();
    let status = RecordStatus::default();
    let notifications = Arc::new(AtomicUsize::new(0));
    let notified = notifications.clone();
    let (id_tx, id_rx) = mpsc::channel();
    let (started_tx, started_rx) = mpsc::channel();
    let (release_tx, release_rx) = mpsc::channel();
    let (event_tx, event_rx) = mpsc::channel();
    let (done_tx, done_rx) = mpsc::channel();
    let done_rx = Arc::new(Mutex::new(done_rx));
    let callback_done = done_rx.clone();
    assert!(
        status
            .1
            .set(Box::new(move || {
                notified.fetch_add(1, Ordering::SeqCst);
                callback_done
                    .lock()
                    .unwrap()
                    .recv_timeout(Duration::from_secs(2))
                    .unwrap();
            }))
            .is_ok()
    );
    let registry = tracing_subscriber::registry().with(ObserveInitializingSpan {
        span: id_tx,
        event: Some(event_tx),
    });
    let layer = super::layer_with_status(
        FormatterLimits::new(4096, if case == "initial-overflow" { 3 } else { 128 }).unwrap(),
        capture(&records),
        (),
        false,
        status.clone(),
    );
    let dispatch = tracing::Dispatch::new(registry.with(layer));
    let initializer_dispatch = dispatch.clone();
    let calls = Arc::new(AtomicUsize::new(0));
    let initial_calls = calls.clone();
    let initial_case = case.clone();
    let initializer = std::thread::spawn(move || {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            tracing::dispatcher::with_default(&initializer_dispatch, || {
                if initial_case == "initial-publication" {
                    // Pause immediately before marking the cache as initializing,
                    // while the real Registry extension guard still protects its
                    // publication. The event must not observe an empty ready cache.
                    BEFORE_SPAN_INITIALIZATION.with(|control| {
                        *control.borrow_mut() = Some(Box::new(move || {
                            started_tx.send(()).unwrap();
                            release_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                        }));
                    });
                    return tracing::info_span!(target: "host_record", "work", v = 1);
                }
                let allocation = (initial_case == "initial-allocation")
                    .then(|| PayloadAllocations::new(Some(1)));
                if allocation.is_some() {
                    PAYLOAD_ALLOCATIONS.with(|control| {
                        let started = started_tx.clone();
                        control.borrow_mut().as_mut().unwrap().before = Some(Box::new(move || {
                            started.send(()).unwrap();
                            release_rx.recv_timeout(Duration::from_secs(2)).unwrap();
                        }));
                    });
                    tracing::info_span!(target: "host_record", "work", v = 1)
                } else {
                    tracing::info_span!(target: "host_record", "work", v = ?Initial {
                        started: started_tx, release: Mutex::new(release_rx),
                        calls: initial_calls, case: initial_case,
                    })
                }
            })
        }))
    });
    let (id, metadata) = id_rx.recv_timeout(Duration::from_secs(2)).unwrap();
    started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
    if case == "initial-overflow" {
        record_initializing_span(&dispatch, &id, metadata, Some(2));
    }
    let inspect_id = id.clone();
    let event_dispatch = dispatch.clone();
    let event = std::thread::spawn(move || {
        tracing::dispatcher::with_default(&event_dispatch, || {
            tracing::info!(target: "host_record", parent: &id, "during initialization");
        });
        done_tx.send(()).unwrap();
    });
    event_rx.recv_timeout(Duration::from_secs(2)).unwrap();
    let before_initial = done_rx
        .lock()
        .unwrap()
        .recv_timeout(Duration::from_millis(30));
    let records_before_initial = records.lock().unwrap().clone();
    release_tx.send(()).unwrap();
    let created = initializer.join().unwrap();
    event.join().unwrap();
    assert!(matches!(
        before_initial,
        Err(mpsc::RecvTimeoutError::Timeout)
    ));
    assert!(records_before_initial.is_empty());
    if matches!(case.as_str(), "initial-event" | "initial-publication") {
        done_rx
            .lock()
            .unwrap()
            .recv_timeout(Duration::from_secs(2))
            .unwrap();
        assert!(created.is_ok());
        assert_eq!(
            calls.load(Ordering::SeqCst),
            usize::from(case == "initial-event")
        );
        assert!(status.failure().is_none());
        assert_eq!(notifications.load(Ordering::SeqCst), 0);
        assert_eq!(
            *records.lock().unwrap(),
            vec![b" INFO work{v=1}: host_record: during initialization\n".to_vec()]
        );
    } else {
        assert_eq!(notifications.load(Ordering::SeqCst), 1);
        assert!(records.lock().unwrap().is_empty());
        assert_eq!(
            calls.load(Ordering::SeqCst),
            usize::from(case != "initial-allocation")
        );
        let registry = dispatch
            .downcast_ref::<tracing_subscriber::Registry>()
            .unwrap();
        let span = registry.span(&inspect_id).unwrap();
        let extensions = span.extensions();
        let caches = extensions.get::<SpanCaches>().unwrap();
        let cache = caches.0[0].1.0.lock().unwrap();
        assert!(cache.pending.is_none());
        assert_eq!(cache.fields.fields, "");
        assert_eq!(cache.fields.fields.capacity(), 0);
        drop(cache);
        drop(extensions);
        match case.as_str() {
            "initial-error" => assert!(matches!(
                status.failure().as_deref(),
                Some(RecordFailure::Formatting)
            )),
            "initial-panic" => {
                let panic = created.expect_err("original panic propagated");
                assert_eq!(
                    panic.downcast_ref::<&str>(),
                    Some(&"initial field panic retained")
                );
                assert!(matches!(
                    status.failure().as_deref(),
                    Some(RecordFailure::Unwinding)
                ));
            }
            "initial-allocation" => assert!(matches!(
                status.failure().as_deref(),
                Some(RecordFailure::Allocation)
            )),
            "initial-overflow" => assert!(matches!(
                status.failure().as_deref(),
                Some(RecordFailure::Size {
                    buffer: BufferKind::Span,
                    limit: 3
                })
            )),
            _ => unreachable!(),
        }
    }
}

#[test]
fn span_field_logging_with_two_layers_returns_and_retains_reentry_failure() {
    const TEST: &str = "liteinst_record::tests::span_field_logging_with_two_layers_returns_and_retains_reentry_failure";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("record") {
        bounded_record_callback_child(TEST, "record");
        return;
    }
    struct Emits(tracing::Span, Arc<AtomicUsize>);
    impl fmt::Debug for Emits {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.1.fetch_add(1, Ordering::SeqCst);
            tracing::info!(target: "host_record", parent: &self.0, "nested");
            writer.write_str("updated")
        }
    }
    let first = Records::default();
    let second = Records::default();
    let first_status = RecordStatus::default();
    let second_status = RecordStatus::default();
    let notifications = Arc::new(AtomicUsize::new(0));
    for status in [&first_status, &second_status] {
        let notifications = notifications.clone();
        assert!(
            status
                .1
                .set(Box::new(move || {
                    notifications.fetch_add(1, Ordering::SeqCst);
                }))
                .is_ok()
        );
    }
    let first_layer = layer_with_status(
        baseline_limits(),
        capture(&first),
        (),
        false,
        first_status.clone(),
    );
    let second_layer = layer_with_status(
        baseline_limits(),
        capture(&second),
        (),
        false,
        second_status.clone(),
    );
    let subscriber = tracing_subscriber::registry()
        .with(first_layer.with_filter(tracing::level_filters::LevelFilter::INFO))
        .with(second_layer.with_filter(tracing::level_filters::LevelFilter::INFO));
    let calls = Arc::new(AtomicUsize::new(0));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "work", value = 1);
        span.record(
            "value",
            tracing::field::debug(Emits(span.clone(), calls.clone())),
        );
        span.with_subscriber(|(id, dispatch)| {
            let registry = dispatch
                .downcast_ref::<tracing_subscriber::Registry>()
                .unwrap();
            let span = registry.span(id).unwrap();
            let extensions = span.extensions();
            let caches = extensions.get::<SpanCaches>().unwrap();
            assert_eq!(caches.0.len(), 2);
            assert!(
                caches
                    .0
                    .iter()
                    .all(|(_, cache)| cache.0.lock().unwrap().fields.fields == "value=1")
            );
        })
        .unwrap();
    });
    assert_eq!(calls.load(Ordering::SeqCst), 2);
    assert_eq!(notifications.load(Ordering::SeqCst), 2);
    for status in [&first_status, &second_status] {
        assert!(matches!(
            status.failure().as_deref(),
            Some(RecordFailure::Reentrant)
        ));
    }
    assert!(first.lock().unwrap().is_empty());
    assert_eq!(
        *second.lock().unwrap(),
        [b" INFO work{value=1}: host_record: nested\n".to_vec()]
    );
}

#[test]
fn new_span_formatter_can_read_its_registry_extensions() {
    const TEST: &str =
        "liteinst_record::tests::new_span_formatter_can_read_its_registry_extensions";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("new") {
        bounded_record_callback_child(TEST, "new");
        return;
    }
    struct Observe(Arc<Mutex<Option<Id>>>);
    impl<S: Subscriber> Layer<S> for Observe {
        fn on_new_span(&self, _: &Attributes<'_>, id: &Id, _: Context<'_, S>) {
            *self.0.lock().unwrap() = Some(id.clone());
        }
    }
    struct Reads {
        dispatch: tracing::Dispatch,
        id: Arc<Mutex<Option<Id>>>,
        calls: Arc<AtomicUsize>,
    }
    impl fmt::Debug for Reads {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            let id = self.id.lock().unwrap().clone().unwrap();
            let registry = self
                .dispatch
                .downcast_ref::<tracing_subscriber::Registry>()
                .unwrap();
            let span = registry.span(&id).unwrap();
            let _extensions = span.extensions();
            self.calls.fetch_add(1, Ordering::SeqCst);
            writer.write_str("readable")
        }
    }
    let id = Arc::new(Mutex::new(None));
    let records = Records::default();
    let status = RecordStatus::default();
    let layer = layer_with_status(
        baseline_limits(),
        capture(&records),
        (),
        false,
        status.clone(),
    );
    let dispatch = tracing::Dispatch::new(
        tracing_subscriber::registry()
            .with(Observe(id.clone()))
            .with(layer),
    );
    let calls = Arc::new(AtomicUsize::new(0));
    tracing::dispatcher::with_default(&dispatch, || {
        let span = tracing::info_span!(target: "host_record", "work", value = ?Reads {
            dispatch: dispatch.clone(), id, calls: calls.clone(),
        });
        tracing::info!(target: "host_record", parent: &span, "complete");
    });
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert!(status.failure().is_none());
    assert_eq!(
        *records.lock().unwrap(),
        [b" INFO work{value=readable}: host_record: complete\n".to_vec()]
    );
}

#[test]
fn concurrent_span_updates_merge_latest_fields_without_reformatting() {
    const TEST: &str =
        "liteinst_record::tests::concurrent_span_updates_merge_latest_fields_without_reformatting";
    if std::env::var("HERMIT_RECORD_LOCK_CASE").as_deref() != Ok("concurrent") {
        bounded_record_callback_child(TEST, "concurrent");
        return;
    }
    struct Paused {
        calls: Arc<AtomicUsize>,
        entered: std::sync::mpsc::SyncSender<()>,
        release: Mutex<std::sync::mpsc::Receiver<()>>,
    }
    impl fmt::Debug for Paused {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
                self.entered.send(()).unwrap();
                self.release.lock().unwrap().recv().unwrap();
            }
            writer.write_str("1")
        }
    }
    struct Counted(Arc<AtomicUsize>);
    impl fmt::Debug for Counted {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("2")
        }
    }
    let first = Records::default();
    let second = Records::default();
    let first_status = RecordStatus::default();
    let second_status = RecordStatus::default();
    let first_layer = layer_with_status(
        baseline_limits(),
        capture(&first),
        (),
        false,
        first_status.clone(),
    );
    let second_layer = layer_with_status(
        baseline_limits(),
        capture(&second),
        (),
        false,
        second_status.clone(),
    );
    let subscriber = tracing_subscriber::registry()
        .with(first_layer)
        .with(second_layer);
    let first_calls = Arc::new(AtomicUsize::new(0));
    let second_calls = Arc::new(AtomicUsize::new(0));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "work", v = 0);
        let (entered_tx, entered_rx) = std::sync::mpsc::sync_channel(0);
        let (release_tx, release_rx) = std::sync::mpsc::sync_channel(0);
        let first_span = span.clone();
        let calls = first_calls.clone();
        let first = std::thread::spawn(move || {
            first_span.record(
                "v",
                tracing::field::debug(Paused {
                    calls,
                    entered: entered_tx,
                    release: Mutex::new(release_rx),
                }),
            );
        });
        entered_rx.recv().unwrap();
        let second_span = span.clone();
        let calls = second_calls.clone();
        std::thread::spawn(move || {
            second_span.record("v", tracing::field::debug(Counted(calls)));
        })
        .join()
        .unwrap();
        release_tx.send(()).unwrap();
        first.join().unwrap();
        tracing::info!(target: "host_record", parent: &span, "all updates");
    });
    assert_eq!(first_calls.load(Ordering::SeqCst), 2);
    assert_eq!(second_calls.load(Ordering::SeqCst), 2);
    assert!(first_status.failure().is_none());
    assert!(second_status.failure().is_none());
    let expected = [b" INFO work{v=0 v=2 v=1}: host_record: all updates\n".to_vec()];
    assert_eq!(*first.lock().unwrap(), expected);
    assert_eq!(*second.lock().unwrap(), expected);
}

#[test]
fn span_merge_overflow_keeps_previous_cache_after_formatting_fragment_once() {
    struct Counted<'a>(&'a AtomicUsize);
    impl fmt::Debug for Counted<'_> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("2")
        }
    }
    let calls = AtomicUsize::new(0);
    let records = Records::default();
    let (subscriber, status) = bounded_subscriber(&records, 128, 3);
    let allocations = PayloadAllocations::new(Some(3));
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "work", v = 1);
        let before = cached_span(&span);
        span.record("v", tracing::field::debug(Counted(&calls)));
        assert_eq!(cached_span(&span), before);
    });
    // Formatting is separate from the serialized merge: unlike stock's
    // prefix-first writer, this invokes the new value even if the prior cache
    // already fills the budget. It never invokes it a second time to retry.
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert_eq!(allocations.attempts(), 2);
    assert!(matches!(
        status.failure().as_deref(),
        Some(RecordFailure::Size {
            buffer: BufferKind::Span,
            limit: 3,
        })
    ));
    assert!(records.lock().unwrap().is_empty());
}

#[test]
fn span_and_event_failure_notifications_can_update_another_layer() {
    const TEST: &str =
        "liteinst_record::tests::span_and_event_failure_notifications_can_update_another_layer";
    let case = std::env::var("HERMIT_RECORD_LOCK_CASE");
    let case = match case.as_deref() {
        Ok("span-notify") => BufferKind::Span,
        Ok("event-notify") => BufferKind::Event,
        _ => {
            for case in ["span-notify", "event-notify"] {
                bounded_record_callback_child(TEST, case);
            }
            return;
        }
    };
    let parent = Arc::new(Mutex::new(None::<tracing::Span>));
    let notifications = Arc::new(AtomicUsize::new(0));
    let failed_status = RecordStatus::default();
    let complete_status = RecordStatus::default();
    let notify_parent = parent.clone();
    let notify_count = notifications.clone();
    assert!(
        failed_status
            .1
            .set(Box::new(move || {
                notify_count.fetch_add(1, Ordering::SeqCst);
                let parent = notify_parent.lock().unwrap().clone().unwrap();
                parent.record("v", 3);
            }))
            .is_ok()
    );
    let failed = Records::default();
    let complete = Records::default();
    let limits = match case {
        BufferKind::Span => FormatterLimits::new(128, 3).unwrap(),
        BufferKind::Event => FormatterLimits::new(14, 32).unwrap(),
    };
    let failed_layer =
        layer_with_status(limits, capture(&failed), (), false, failed_status.clone());
    let complete_layer = layer_with_status(
        baseline_limits(),
        capture(&complete),
        (),
        false,
        complete_status.clone(),
    );
    let subscriber = tracing_subscriber::registry()
        .with(failed_layer)
        .with(complete_layer);
    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::info_span!(target: "host_record", "work", v = 1);
        *parent.lock().unwrap() = Some(span.clone());
        if case == BufferKind::Span {
            span.record("v", 2);
        }
        tracing::info!(target: "host_record", parent: &span, "complete");
        *parent.lock().unwrap() = None;
    });
    assert_eq!(notifications.load(Ordering::SeqCst), 1);
    assert!(
        matches!(failed_status.failure().as_deref(), Some(RecordFailure::Size { buffer, .. }) if *buffer == case)
    );
    assert!(complete_status.failure().is_none());
    assert!(failed.lock().unwrap().is_empty());
    let expected: &[u8] = match case {
        BufferKind::Span => b" INFO work{v=1 v=3 v=2}: host_record: complete\n",
        BufferKind::Event => b" INFO work{v=1 v=3}: host_record: complete\n",
    };
    assert_eq!(*complete.lock().unwrap(), [expected.to_vec()]);
}

#[test]
fn empty_span_update_fragments_preserve_stock_separator_bytes() {
    let records = compare_with_stock("trace", || {
        let span = tracing::info_span!(target: "host_record", "work", v = 1);
        span.record("v", tracing::field::Empty);
        span.record("v", tracing::field::Empty);
        span.record("v", 2);
        tracing::info!(target: "host_record", parent: &span, "spaces");
    });
    assert_eq!(
        records,
        [b"unchanged-time  INFO work{v=1   v=2}: host_record: spaces\n".to_vec()]
    );
}

fn dual_layer_events() {
    tracing::info!(target: "host_record", "outside private INFO");
    let root = tracing::info_span!(target: "host_record", "root", owner = 1);
    let _root = root.enter();
    let work = tracing::info_span!(target: "host_record", "work", task = tracing::field::Empty, later = tracing::field::Empty);
    work.record("task", 7);
    work.in_scope(|| {
        tracing::trace!(target: "host_record", "public TRACE");
        tracing::info!(target: "host_record", "both current");
        let detail = tracing::debug_span!(target: "host_record", "detail", step = 2);
        detail.in_scope(|| tracing::info!(target: "host_record", "different ancestor selection"));
        root.record("owner", 3);
        work.record("later", 9);
        tracing::info!(target: "host_record", "after updates");
        tracing::info!(target: "host_record", parent: &root, "explicit root");
        tracing::info!(target: "host_record", parent: None, "no parent");
        let record = tracing_log::log::Record::builder()
            .args(format_args!("bridged in span"))
            .level(tracing_log::log::Level::Info)
            .target("actual_log_target")
            .module_path(Some("source_module"))
            .file(Some("source.rs"))
            .line(Some(27))
            .build();
        tracing_log::log::Log::log(&tracing_log::LogTracer::new(), &record);
    });
    tracing::info!(target: "host_record", "after private INFO");
}

#[test]
fn complete_layers_keep_independent_stock_bytes_and_filters() {
    const PUBLIC: &str = "off,host_record[work{task=7}]=trace,actual_log_target=info";
    // Independent stock subscribers avoid sharing stock's own per-field-type
    // span cache between the two oracles. Each output defines one layer's bytes.
    let expected_public = stock_layer_output(EnvFilter::new(PUBLIC), dual_layer_events);
    let expected_private =
        stock_layer_output(tracing::metadata::LevelFilter::INFO, dual_layer_events);
    let public = Records::default();
    let private = Records::default();
    let public_status = RecordStatus::default();
    let private_status = RecordStatus::default();
    let public_layer = layer_with_status(
        baseline_limits(),
        capture(&public),
        FixedTime,
        true,
        public_status.clone(),
    )
    .with_filter(EnvFilter::new(PUBLIC));
    let private_layer = layer_with_status(
        baseline_limits(),
        capture(&private),
        FixedTime,
        true,
        private_status.clone(),
    )
    .with_filter(tracing::metadata::LevelFilter::INFO);
    tracing::subscriber::with_default(
        tracing_subscriber::registry()
            .with(public_layer)
            .with(private_layer),
        dual_layer_events,
    );
    let public = public.lock().unwrap();
    let private = private.lock().unwrap();
    assert_eq!(public.concat(), expected_public);
    assert_eq!(private.concat(), expected_private);
    assert!(public_status.failure().is_none());
    assert!(private_status.failure().is_none());
    assert_eq!(public.len(), 7);
    assert_eq!(private.len(), 8);
    assert_eq!(
        public[0],
        b"unchanged-time TRACE work{task=7}: host_record: public TRACE\n"
    );
    assert_eq!(
        private[0],
        b"unchanged-time  INFO host_record: outside private INFO\n"
    );
    assert_eq!(
        public[3],
        b"unchanged-time  INFO work{task=7 later=9}: host_record: after updates\n"
    );
    assert_eq!(
        private[3],
        b"unchanged-time  INFO root{owner=1 owner=3}:work{task=7 later=9}: host_record: after updates\n"
    );
    assert_eq!(
        public[6],
        b"unchanged-time  INFO work{task=7 later=9}: actual_log_target: bridged in span\n"
    );
}

#[test]
fn public_layer_constructor_retains_only_its_own_sink_failure() {
    let private = Records::default();
    let attempts = Arc::new(AtomicUsize::new(0));
    let public_notifications = Arc::new(AtomicUsize::new(0));
    let private_notifications = Arc::new(AtomicUsize::new(0));
    let calls = attempts.clone();
    let public_failed = public_notifications.clone();
    let private_failed = private_notifications.clone();
    let (public_layer, public_status) = super::record_layer_with_failure(
        baseline_limits(),
        move |_| {
            calls.fetch_add(1, Ordering::SeqCst);
            Err(io::Error::from_raw_os_error(libc::EPIPE))
        },
        move || {
            public_failed.fetch_add(1, Ordering::SeqCst);
        },
    );
    let (private_layer, private_status) =
        super::record_layer_with_failure(baseline_limits(), capture(&private), move || {
            private_failed.fetch_add(1, Ordering::SeqCst);
        });
    tracing::subscriber::with_default(
        tracing_subscriber::registry()
            .with(public_layer.with_filter(EnvFilter::new("off,host_record=info")))
            .with(private_layer.with_filter(tracing::metadata::LevelFilter::INFO)),
        || {
            let span = tracing::info_span!(target: "host_record", "work", v = 1);
            let _entered = span.enter();
            tracing::info!(target: "host_record", "first");
            span.record("v", 2);
            tracing::info!(target: "host_record", "second");
        },
    );
    assert_eq!(attempts.load(Ordering::SeqCst), 1);
    assert_eq!(public_notifications.load(Ordering::SeqCst), 1);
    assert_eq!(private_notifications.load(Ordering::SeqCst), 0);
    assert!(matches!(
        public_status.failure().as_deref(),
        Some(RecordFailure::Sink(error)) if error.raw_os_error() == Some(libc::EPIPE)
    ));
    assert!(private_status.failure().is_none());
    let private = private.lock().unwrap();
    assert_eq!(private.len(), 2);
    // The public constructor uses real timestamps. Full bytes with a fixed
    // input timer are checked by the independent stock-oracle test above.
    assert!(private[0].ends_with(b" INFO work{v=1}: host_record: first\n"));
    assert!(private[1].ends_with(b" INFO work{v=1 v=2}: host_record: second\n"));
}

#[test]
fn span_update_failure_keeps_the_other_layer_complete_in_either_order() {
    let expected_first = b"unchanged-time  INFO work{v=1}: host_record: before\n";
    let expected_second = b"unchanged-time  INFO work{v=1 v=2}: host_record: after\n";
    for small_first in [false, true] {
        let first = Records::default();
        let second = Records::default();
        let first_status = RecordStatus::default();
        let second_status = RecordStatus::default();
        let first_layer = layer_with_status(
            FormatterLimits::new(256, if small_first { 3 } else { 64 }).unwrap(),
            capture(&first),
            FixedTime,
            true,
            first_status.clone(),
        );
        let second_layer = layer_with_status(
            FormatterLimits::new(256, if small_first { 64 } else { 3 }).unwrap(),
            capture(&second),
            FixedTime,
            true,
            second_status.clone(),
        );
        tracing::subscriber::with_default(
            tracing_subscriber::registry()
                .with(first_layer.with_filter(tracing::metadata::LevelFilter::INFO))
                .with(second_layer.with_filter(tracing::metadata::LevelFilter::INFO)),
            || {
                let span = tracing::info_span!(target: "host_record", "work", v = 1);
                let _entered = span.enter();
                tracing::info!(target: "host_record", "before");
                span.record("v", 2);
                tracing::info!(target: "host_record", "after");
            },
        );
        let (failed_records, failed_status, complete_records, complete_status) = if small_first {
            (&first, &first_status, &second, &second_status)
        } else {
            (&second, &second_status, &first, &first_status)
        };
        assert_eq!(*failed_records.lock().unwrap(), [expected_first.to_vec()]);
        assert!(matches!(
            failed_status.failure().as_deref(),
            Some(RecordFailure::Size {
                buffer: BufferKind::Span,
                limit: 3,
            })
        ));
        assert_eq!(
            *complete_records.lock().unwrap(),
            [expected_first.to_vec(), expected_second.to_vec()]
        );
        assert!(complete_status.failure().is_none());
    }
}

#[test]
fn timer_failure_preserves_stock_fallback_but_cannot_hide_overflow() {
    struct FailingTime;
    impl FormatTime for FailingTime {
        fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
            writer.write_str("prefix")?;
            Err(fmt::Error)
        }
    }
    for limit in [128, 6] {
        let records = Records::default();
        let (subscriber, status) = super::subscriber_with_status(
            filter(),
            FormatterLimits::new(limit, 8).unwrap(),
            capture(&records),
            FailingTime,
            true,
            RecordStatus::default(),
        );
        tracing::subscriber::with_default(
            subscriber,
            || tracing::info!(target: "host_record", "time"),
        );
        if limit == 128 {
            assert_eq!(
                *records.lock().unwrap(),
                [b"prefix<unknown time>  INFO host_record: time\n".to_vec()]
            );
            assert!(status.failure().is_none());
        } else {
            assert!(records.lock().unwrap().is_empty());
            assert!(matches!(
                status.failure().as_deref(),
                Some(RecordFailure::Size {
                    buffer: BufferKind::Event,
                    limit: 6
                })
            ));
        }
    }
}

fn ansi_layer(
    records: &Records,
    ansi: bool,
    limits: FormatterLimits,
    status: RecordStatus,
) -> RecordLayer<FixedTime, impl Fn(&[u8]) -> io::Result<()> + Send + Sync + 'static> {
    RecordLayer {
        ansi,
        ..layer_with_status(limits, capture(records), FixedTime, true, status)
    }
}

fn stock_ansi_output<F>(ansi: bool, filter: F, emit: impl FnOnce()) -> Vec<u8>
where
    F: tracing_subscriber::layer::Filter<tracing_subscriber::Registry> + Send + Sync + 'static,
{
    let output = Output::default();
    let writer = output.clone();
    let layer = tracing_subscriber::fmt::layer()
        .with_timer(FixedTime)
        .with_ansi(ansi)
        .with_writer(move || writer.clone())
        .with_filter(filter);
    tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), emit);
    output.0.lock().unwrap().clone()
}

fn compare_ansi_with_stock(ansi: bool, filter_text: &str, emit: impl Fn()) -> Vec<Vec<u8>> {
    let expected = stock_ansi_output(ansi, EnvFilter::new(filter_text), &emit);
    let records = Records::default();
    let status = RecordStatus::default();
    let layer = ansi_layer(&records, ansi, baseline_limits(), status.clone())
        .with_filter(EnvFilter::new(filter_text));
    tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), emit);
    let records = records.lock().unwrap().clone();
    assert_eq!(records.concat(), expected, "ansi={ansi}");
    assert!(status.failure().is_none());
    records
}

#[test]
fn ansi_full_bytes_match_stock_levels_scopes_updates_and_log_metadata() {
    for ansi in [false, true] {
        let records = compare_ansi_with_stock(ansi, "trace", || {
            structured_events();
            let root = tracing::info_span!(target: "host_record", "root", id = 1);
            let _root = root.enter();
            let child = tracing::info_span!(target: "host_record", "child", id = 2);
            let _child = child.enter();
            tracing::trace!(target: "host_record", "context");
            tracing::debug!(target: "host_record", parent: &root, "explicit");
            tracing::warn!(target: "host_record", parent: None, "root event");
            root.record("id", 3);
            tracing::error!(target: "host_record", "updated ancestor");
            let empty = tracing::info_span!(target: "", "", v = tracing::field::Empty);
            let _empty = empty.enter();
            empty.record("v", tracing::field::Empty);
            tracing::info!(target: "", "empty span and target");
            let record = tracing_log::log::Record::builder()
                .args(format_args!("bridged"))
                .level(tracing_log::log::Level::Info)
                .target("actual_log_target")
                .module_path(Some("source_module"))
                .file(Some("source.rs"))
                .line(Some(27))
                .build();
            tracing_log::log::Log::log(&tracing_log::LogTracer::new(), &record);
            tracing::event!(target: "log", tracing::Level::INFO, { message = "ordinary tracing", log.target = "must_not_replace_target" });
        });
        assert_eq!(records.len(), 11);
        // Explicit ANSI on adds stock styling; the named Chunks value keeps its
        // own ESC even with ANSI off, so ESC presence alone is not an oracle.
        assert_eq!(records[0].starts_with(b"\x1b[2m"), ansi);
    }
}

#[test]
fn ansi_fields_match_stock_types_dynamic_values_and_error_sanitization() {
    struct Controls;
    impl fmt::Display for Controls {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("\x1b[31m\x07\x08\x0c\x7f")?;
            for value in 0x80..=0x9f {
                fmt::Write::write_char(writer, char::from_u32(value).unwrap())?;
            }
            writer.write_str("\n\r\t é")
        }
    }
    impl fmt::Debug for Controls {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt::Display::fmt(self, writer)
        }
    }
    impl std::error::Error for Controls {}
    #[derive(Debug)]
    struct Cause<T>(T);
    impl<T: fmt::Debug> fmt::Display for Cause<T> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            writer.write_str("cause\x1b[32m")
        }
    }
    impl<T: std::error::Error + 'static> std::error::Error for Cause<T> {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.0)
        }
    }
    for ansi in [false, true] {
        let records = compare_ansi_with_stock(ansi, "trace", || {
            let error = Cause(Cause(Controls));
            let span = tracing::info_span!(target: "host_record", "fields", initial = ?Controls,
                error = &error as &(dyn std::error::Error + 'static), later = tracing::field::Empty);
            let _entered = span.enter();
            span.record("later", tracing::field::display(Controls));
            tracing::info!(target: "host_record", signed = -2i64, unsigned = 3u64, large = i128::MAX,
                float = 1.25f64, boolean = true, r#type = "é", bytes = ?[0u8, 255],
                debug = ?Controls, display = %Controls, "{Controls}");
            tracing::error!(target: "host_record", error = &error as &(dyn std::error::Error + 'static),
                no_source = &Controls as &(dyn std::error::Error + 'static));
            tracing::event!(target: "host_record", tracing::Level::INFO,
                { message = &error as &(dyn std::error::Error + 'static) });
        });
        assert_eq!(records.len(), 3);
        assert!(records.concat().windows(4).any(|part| part == b"\\x1b"));
        assert!(records.concat().windows(5).any(|part| part == b"\x1b[31m"));
    }
}

#[test]
fn ansi_public_and_plain_private_layers_match_independent_stock_outputs() {
    // This reuses the original dual-layer callsites. Concurrent first-use
    // registration can omit dynamic spans in stock EnvFilter before its
    // callsite matcher is installed. Run this additional stock oracle in its
    // own process; keep both candidate layers active together and compare all
    // bytes below. This does not qualify concurrent callsite registration.
    const TEST: &str = "liteinst_record::tests::ansi_public_and_plain_private_layers_match_independent_stock_outputs";
    const CHILD: &str = "HERMIT_RECORD_ANSI_STOCK_CHILD";
    if std::env::var_os(CHILD).is_none() {
        use std::process::Command;
        use std::process::Stdio;
        use std::time::Duration;
        use std::time::Instant;

        let mut child = Command::new(std::env::current_exe().unwrap())
            .args(["--exact", TEST, "--nocapture", "--test-threads=1"])
            .env(CHILD, "1")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let deadline = Instant::now() + Duration::from_secs(10);
        while child.try_wait().unwrap().is_none() {
            if Instant::now() >= deadline {
                child.kill().unwrap();
                let output = child.wait_with_output().unwrap();
                panic!("ANSI stock comparison did not return: {output:?}");
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(output.stderr.is_empty(), "{output:?}");
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(stdout.contains(&format!("test {TEST} ... ok")), "{stdout}");
        assert!(
            stdout.contains("1 passed; 0 failed; 0 ignored;"),
            "{stdout}"
        );
        return;
    }
    const PUBLIC: &str = "off,host_record[work{task=7}]=trace,actual_log_target=info";
    let expected_public = stock_ansi_output(true, EnvFilter::new(PUBLIC), dual_layer_events);
    let expected_private = stock_ansi_output(
        false,
        tracing::metadata::LevelFilter::INFO,
        dual_layer_events,
    );
    let public = Records::default();
    let private = Records::default();
    let public_status = RecordStatus::default();
    let private_status = RecordStatus::default();
    let public_layer = ansi_layer(&public, true, baseline_limits(), public_status.clone())
        .with_filter(EnvFilter::new(PUBLIC));
    let private_layer = ansi_layer(&private, false, baseline_limits(), private_status.clone())
        .with_filter(tracing::metadata::LevelFilter::INFO);
    tracing::subscriber::with_default(
        tracing_subscriber::registry()
            .with(public_layer)
            .with(private_layer),
        dual_layer_events,
    );
    assert_eq!(public.lock().unwrap().concat(), expected_public);
    assert_eq!(private.lock().unwrap().concat(), expected_private);
    assert_eq!(public.lock().unwrap().len(), 7);
    assert_eq!(private.lock().unwrap().len(), 8);
    assert!(public_status.failure().is_none());
    assert!(private_status.failure().is_none());
}

#[test]
fn ansi_event_budget_counts_every_emitted_byte_at_the_boundary() {
    let emit = || tracing::info!(target: "host_record", value = "é", "boundary");
    for ansi in [false, true] {
        let expected = stock_ansi_output(ansi, tracing::metadata::LevelFilter::INFO, emit);
        for limit in [expected.len(), expected.len() - 1] {
            let records = Records::default();
            let status = RecordStatus::default();
            let allocations = PayloadAllocations::new(None);
            let layer = ansi_layer(
                &records,
                ansi,
                FormatterLimits::new(limit, 8).unwrap(),
                status.clone(),
            );
            tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), emit);
            assert_eq!(allocations.attempts(), 1);
            if limit == expected.len() {
                assert_eq!(
                    records.lock().unwrap().as_slice(),
                    std::slice::from_ref(&expected)
                );
                assert!(status.failure().is_none());
            } else {
                assert!(records.lock().unwrap().is_empty());
                assert!(matches!(status.failure().as_deref(),
                    Some(RecordFailure::Size { buffer: BufferKind::Event, limit: actual }) if *actual == limit));
            }
        }
    }
}

#[test]
fn ansi_span_budget_counts_styles_updates_and_spaces_without_reformatting() {
    struct Once<'a>(&'a AtomicUsize, u32);
    impl fmt::Debug for Once<'_> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            write!(writer, "{}", self.1)
        }
    }
    for ansi in [false, true] {
        let expected_fields = Arc::new(Mutex::new(String::new()));
        let expected = stock_ansi_output(ansi, tracing::metadata::LevelFilter::INFO, || {
            let span = tracing::info_span!(target: "host_record", "small", v = 1);
            span.record("v", 2);
            span.with_subscriber(|(id, dispatch)| {
                let registry = dispatch
                    .downcast_ref::<tracing_subscriber::Registry>()
                    .unwrap();
                *expected_fields.lock().unwrap() = registry
                    .span(id)
                    .unwrap()
                    .extensions()
                    .get::<FormattedFields<DefaultFields>>()
                    .unwrap()
                    .fields
                    .clone();
            });
            tracing::info!(target: "host_record", parent: &span, "boundary");
        });
        let expected_fields = expected_fields.lock().unwrap().clone();
        for limit in [expected_fields.len(), expected_fields.len() - 1] {
            let records = Records::default();
            let status = RecordStatus::default();
            let calls = AtomicUsize::new(0);
            let layer = ansi_layer(
                &records,
                ansi,
                FormatterLimits::new(1024, limit).unwrap(),
                status.clone(),
            );
            tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), || {
                let allocations = PayloadAllocations::new(None);
                let span =
                    tracing::info_span!(target: "host_record", "small", v = ?Once(&calls, 1));
                let original = cached_span(&span);
                assert_eq!(original.1, limit);
                span.record("v", tracing::field::debug(Once(&calls, 2)));
                assert_eq!(calls.load(Ordering::SeqCst), 2);
                assert_eq!(allocations.attempts(), 2);
                if limit == expected_fields.len() {
                    assert_eq!(cached_span(&span), (expected_fields.clone(), limit));
                } else {
                    assert_eq!(cached_span(&span), original);
                }
                tracing::info!(target: "host_record", parent: &span, "boundary");
                span.record("v", tracing::field::debug(Once(&calls, 3)));
                assert_eq!(
                    calls.load(Ordering::SeqCst),
                    if limit == expected_fields.len() { 3 } else { 2 }
                );
                tracing::info!(target: "host_record", "refused after span overflow");
            });
            assert!(matches!(status.failure().as_deref(),
                Some(RecordFailure::Size { buffer: BufferKind::Span, limit: actual }) if *actual == limit));
            if limit == expected_fields.len() {
                assert_eq!(
                    records.lock().unwrap().as_slice(),
                    std::slice::from_ref(&expected)
                );
            } else {
                assert!(records.lock().unwrap().is_empty());
            }
        }
    }
}

#[test]
fn ansi_initial_span_and_cached_event_obey_their_exact_stock_byte_limits() {
    for ansi in [false, true] {
        let expected_fields = Arc::new(Mutex::new(String::new()));
        let expected = stock_ansi_output(ansi, tracing::metadata::LevelFilter::INFO, || {
            let span = tracing::info_span!(target: "host_record", "small", v = "é");
            span.with_subscriber(|(id, dispatch)| {
                let registry = dispatch
                    .downcast_ref::<tracing_subscriber::Registry>()
                    .unwrap();
                *expected_fields.lock().unwrap() = registry
                    .span(id)
                    .unwrap()
                    .extensions()
                    .get::<FormattedFields<DefaultFields>>()
                    .unwrap()
                    .fields
                    .clone();
            });
            tracing::info!(target: "host_record", parent: &span, "cached");
        });
        let expected_fields = expected_fields.lock().unwrap().clone();
        for (span_limit, event_limit) in [
            (expected_fields.len(), expected.len()),
            (expected_fields.len() - 1, expected.len()),
            (expected_fields.len(), expected.len() - 1),
        ] {
            let records = Records::default();
            let status = RecordStatus::default();
            let layer = ansi_layer(
                &records,
                ansi,
                FormatterLimits::new(event_limit, span_limit).unwrap(),
                status.clone(),
            );
            tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), || {
                let allocations = PayloadAllocations::new(None);
                let span = tracing::info_span!(target: "host_record", "small", v = "é");
                if span_limit == expected_fields.len() {
                    assert_eq!(cached_span(&span), (expected_fields.clone(), span_limit));
                } else {
                    assert!(cached_span(&span).0.is_empty());
                }
                tracing::info!(target: "host_record", parent: &span, "cached");
                assert_eq!(
                    allocations.attempts(),
                    if span_limit == expected_fields.len() {
                        2
                    } else {
                        1
                    }
                );
            });
            if span_limit < expected_fields.len() {
                assert!(records.lock().unwrap().is_empty());
                assert!(
                    matches!(status.failure().as_deref(), Some(RecordFailure::Size {
                    buffer: BufferKind::Span, limit }) if *limit == span_limit)
                );
            } else if event_limit < expected.len() {
                assert!(records.lock().unwrap().is_empty());
                assert!(
                    matches!(status.failure().as_deref(), Some(RecordFailure::Size {
                    buffer: BufferKind::Event, limit }) if *limit == event_limit)
                );
            } else {
                assert_eq!(
                    records.lock().unwrap().as_slice(),
                    std::slice::from_ref(&expected)
                );
                assert!(status.failure().is_none());
            }
        }
    }
}

#[test]
fn explicit_ansi_constructor_preserves_default_and_failure_independence() {
    for ansi in [false, true] {
        let public = Records::default();
        let private = Records::default();
        let calls = Arc::new(AtomicUsize::new(0));
        let seen = calls.clone();
        let attempts = public.clone();
        let (public_layer, public_status) = super::record_layer_with_failure_and_ansi(
            baseline_limits(),
            move |bytes| {
                attempts.lock().unwrap().push(bytes.to_vec());
                Err(io::Error::new(io::ErrorKind::BrokenPipe, "ANSI sink"))
            },
            move || {
                seen.fetch_add(1, Ordering::SeqCst);
            },
            ansi,
        );
        let (private_layer, private_status) =
            super::record_layer_with_failure(baseline_limits(), capture(&private), || {
                panic!("private layer must not fail")
            });
        tracing::subscriber::with_default(
            tracing_subscriber::registry()
                .with(public_layer)
                .with(private_layer),
            || {
                tracing::info!(target: "host_record", "first");
                tracing::info!(target: "host_record", "second");
            },
        );
        let public = public.lock().unwrap();
        let private = private.lock().unwrap();
        assert_eq!(public.len(), 1);
        assert_eq!(public[0].contains(&0x1b), ansi);
        assert_eq!(private.len(), 2);
        assert!(!private.concat().contains(&0x1b));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert!(
            matches!(public_status.failure().as_deref(), Some(RecordFailure::Sink(error))
            if error.kind() == io::ErrorKind::BrokenPipe)
        );
        assert!(private_status.failure().is_none());
    }
}

#[test]
fn ansi_format_error_and_panic_keep_failure_and_never_publish_partial_records() {
    struct Failure<'a>(&'a AtomicUsize, bool);
    impl fmt::Debug for Failure<'_> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fetch_add(1, Ordering::SeqCst);
            writer.write_str("prefix\x1b[31m")?;
            if self.1 {
                panic!("ANSI formatter panic");
            }
            Err(fmt::Error)
        }
    }
    for panic in [false, true] {
        for span_field in [false, true] {
            let records = Records::default();
            let status = RecordStatus::default();
            let calls = AtomicUsize::new(0);
            let layer = ansi_layer(&records, true, baseline_limits(), status.clone());
            tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), || {
                let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                    if span_field {
                        let _span = tracing::info_span!(target: "host_record", "broken", value = ?Failure(&calls, panic));
                    } else {
                        tracing::info!(target: "host_record", value = ?Failure(&calls, panic));
                    }
                }));
                if panic {
                    assert_eq!(
                        result.unwrap_err().downcast_ref::<&str>(),
                        Some(&"ANSI formatter panic")
                    );
                    assert!(matches!(
                        status.failure().as_deref(),
                        Some(RecordFailure::Unwinding)
                    ));
                } else {
                    assert!(result.is_ok());
                    assert!(matches!(
                        status.failure().as_deref(),
                        Some(RecordFailure::Formatting)
                    ));
                }
                tracing::info!(target: "host_record", value = ?Failure(&calls, panic));
            });
            assert_eq!(calls.load(Ordering::SeqCst), 1);
            assert!(records.lock().unwrap().is_empty());
        }
    }
}

#[test]
fn ansi_timestamp_fallback_matches_stock_and_cannot_hide_byte_overflow() {
    #[derive(Clone, Copy)]
    struct FailingTime;
    impl FormatTime for FailingTime {
        fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
            writer.write_str("prefix")?;
            Err(fmt::Error)
        }
    }
    let expected = Output::default();
    let writer = expected.clone();
    let stock = tracing_subscriber::fmt()
        .with_timer(FailingTime)
        .with_ansi(true)
        .with_writer(move || writer.clone())
        .finish();
    let emit = || tracing::info!(target: "host_record", "time");
    tracing::subscriber::with_default(stock, emit);
    let expected = expected.0.lock().unwrap().clone();
    for limit in [expected.len(), expected.len() - 1, 6] {
        let records = Records::default();
        let status = RecordStatus::default();
        let layer = RecordLayer {
            ansi: true,
            ..layer_with_status(
                FormatterLimits::new(limit, 8).unwrap(),
                capture(&records),
                FailingTime,
                true,
                status.clone(),
            )
        };
        tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), emit);
        if limit == expected.len() {
            assert_eq!(
                records.lock().unwrap().as_slice(),
                std::slice::from_ref(&expected)
            );
            assert!(status.failure().is_none());
        } else {
            assert!(records.lock().unwrap().is_empty());
            assert!(matches!(status.failure().as_deref(),
                Some(RecordFailure::Size { buffer: BufferKind::Event, limit: actual }) if *actual == limit));
        }
    }
}

const TEARDOWN_CASE: &str = "HERMIT_RECORD_TEARDOWN_CASE";
const TEARDOWN_OUTPUT: &str = "HERMIT_RECORD_TEARDOWN_OUTPUT";
const TEARDOWN_RECORD: &[u8] =
    b" INFO watched{owner=7}: host_record: retained value=11 answer=\"stable\"\n";

fn teardown_event(parent: &tracing::Span) {
    tracing::info!(target: "host_record", parent: parent, value = 11, answer = "stable", "retained");
}

struct ExitRecord {
    parent: tracing::Span,
    create_span: bool,
    contextual: bool,
}

impl Drop for ExitRecord {
    fn drop(&mut self) {
        if self.create_span {
            let _span = tracing::info_span!(target: "host_record", parent: &self.parent, "late", value = 11);
        } else if self.contextual {
            tracing::info!(target: "host_record", value = 11, answer = "stable", "retained");
        } else {
            teardown_event(&self.parent);
        }
    }
}

thread_local! {
    static EXIT_RECORD: std::cell::OnceCell<ExitRecord> = const { std::cell::OnceCell::new() };
}
static PROCESS_PARENT: OnceLock<tracing::Span> = OnceLock::new();

extern "C" fn process_exit_record() {
    teardown_event(PROCESS_PARENT.get().expect("retained process parent"));
}

// This is a normal libtest target: discovery does not run a producer. Each
// selected subprocess installs one global subscriber, avoiding scoped-dispatch
// TLS in the very control intended to test logging after TLS destruction.
#[test]
fn teardown_child() {
    let Ok(case) = std::env::var(TEARDOWN_CASE) else {
        return;
    };
    let limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) }, 0);
    let path = std::env::var_os(TEARDOWN_OUTPUT).expect("child output path");
    let mut file = std::fs::File::create(path).unwrap();
    if case == "stderr-pressure" {
        let pipe_capacity = unsafe { libc::fcntl(libc::STDERR_FILENO, libc::F_GETPIPE_SZ) };
        assert!(pipe_capacity > 0, "stderr should be a pipe");
        let mut stderr = std::io::stderr().lock();
        writeln!(stderr, "pressure-start capacity={pipe_capacity}").unwrap();
        stderr
            .write_all(&vec![b'x'; pipe_capacity as usize + 1])
            .unwrap();
        writeln!(stderr, "\npressure-end").unwrap();
        file.write_all(TEARDOWN_RECORD).unwrap();
        return;
    }
    let dynamic = case == "dynamic-filter";
    let filter = EnvFilter::new(if dynamic {
        "off,[watched]=info"
    } else {
        "info"
    });
    let status = if case.starts_with("stock-") {
        let writer = Arc::new(file);
        tracing::subscriber::set_global_default(
            tracing_subscriber::fmt()
                .without_time()
                .with_ansi(false)
                .with_env_filter(filter)
                .with_writer(writer)
                .finish(),
        )
        .unwrap();
        None
    } else {
        let writer = Mutex::new(file);
        let (subscriber, status) = super::subscriber_with_status(
            filter,
            baseline_limits(),
            move |record| writer.lock().unwrap().write_all(record),
            (),
            false,
            RecordStatus::default(),
        );
        tracing::subscriber::set_global_default(subscriber).unwrap();
        Some(status)
    };
    if case.ends_with("process") {
        let parent = tracing::info_span!(target: "host_record", "watched", owner = 7);
        parent.in_scope(|| teardown_event(&parent));
        assert!(PROCESS_PARENT.set(parent).is_ok());
        assert_eq!(unsafe { libc::atexit(process_exit_record) }, 0);
        // exit runs current-thread TLS destruction before the atexit callback.
        unsafe { libc::exit(0) }
    }
    std::thread::spawn(move || {
        let after_registry = case != "thread" && case != "stock-thread";
        if after_registry {
            EXIT_RECORD.with(|_| ());
        }
        let parent = tracing::info_span!(target: "host_record", "watched", owner = 7);
        let entered = parent.enter();
        EXIT_RECORD.with(|slot| {
            assert!(
                slot.set(ExitRecord {
                    parent: parent.clone(),
                    create_span: case == "new-span",
                    contextual: case == "contextual",
                })
                .is_ok()
            );
        });
        teardown_event(&parent);
        if case == "contextual" {
            // Keep an entered context until TLS destruction. This separate
            // dependency reproducer must not be called complete-log evidence.
            std::mem::forget(entered);
        }
    })
    .join()
    .unwrap();
    if let Some(status) = status {
        assert!(status.failure().is_none());
    }
}

fn teardown_subprocess(case: &str) -> (std::process::Output, Vec<u8>) {
    use std::io::Read;
    use std::process::Command;
    use std::process::Output;
    use std::process::Stdio;
    use std::time::Duration;
    use std::time::Instant;

    let directory = tempfile::tempdir().unwrap();
    let output = directory.path().join("records");
    let mut child = Command::new(std::env::current_exe().unwrap())
        .args([
            "--exact",
            "liteinst_record::tests::teardown_child",
            "--nocapture",
            "--test-threads=1",
        ])
        .env(TEARDOWN_CASE, case)
        .env(TEARDOWN_OUTPUT, &output)
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(10);
    let mut stderr = child.stderr.take().expect("piped child stderr");
    let stderr_reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        stderr.read_to_end(&mut bytes).unwrap();
        bytes
    });
    let status = loop {
        if let Some(status) = child.try_wait().unwrap() {
            break status;
        }
        if Instant::now() >= deadline {
            child.kill().unwrap();
            child.wait().unwrap();
            let stderr = stderr_reader.join().expect("stderr reader should complete");
            panic!(
                "teardown subprocess {case} exceeded 10 seconds: {}",
                String::from_utf8_lossy(&stderr)
            );
        }
        std::thread::sleep(Duration::from_millis(10));
    };
    let stderr = stderr_reader.join().expect("stderr reader should complete");
    let result = Output {
        status,
        stdout: Vec::new(),
        stderr,
    };
    let bytes = std::fs::read(output).unwrap();
    (result, bytes)
}

#[test]
fn teardown_subprocess_drains_stderr_beyond_pipe_capacity() {
    let (result, bytes) = teardown_subprocess("stderr-pressure");
    assert!(
        result.status.success(),
        "pressure child failed: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let stderr = String::from_utf8(result.stderr).unwrap();
    let (header, body) = stderr
        .split_once('\n')
        .expect("pressure child should separate its header");
    let capacity = header
        .strip_prefix("pressure-start capacity=")
        .and_then(|value| value.parse::<usize>().ok())
        .expect("pressure child should report the pipe capacity");
    let pressure = body
        .strip_suffix("\npressure-end\n")
        .expect("pressure child should retain its stderr trailer");
    assert_eq!(pressure.len(), capacity + 1);
    assert!(pressure.bytes().all(|byte| byte == b'x'));
    assert_eq!(bytes, TEARDOWN_RECORD);
}

#[test]
fn complete_records_survive_thread_and_process_formatter_tls_teardown() {
    for case in ["thread", "after-registry", "process"] {
        let (result, bytes) = teardown_subprocess(case);
        assert!(
            result.status.success(),
            "{case}: {}",
            String::from_utf8_lossy(&result.stderr)
        );
        assert_eq!(bytes, TEARDOWN_RECORD.repeat(2), "{case}");
        assert!(result.stderr.is_empty(), "{case}: {:?}", result.stderr);
    }
}

#[test]
fn teardown_control_reproduces_stock_formatter_tls_failure() {
    for case in ["stock-thread", "stock-process"] {
        let (result, bytes) = teardown_subprocess(case);
        assert!(
            !result.status.success(),
            "{case}: control did not exercise destroyed fmt TLS"
        );
        assert!(
            String::from_utf8_lossy(&result.stderr)
                .contains("cannot access a Thread Local Storage value"),
            "{case}: {:?}",
            result.stderr
        );
        assert_eq!(
            bytes, TEARDOWN_RECORD,
            "{case}: only the original warmup record survives"
        );
    }
}

// These controls characterize unresolved dependency defects, not supported
// logging cases. When the lifetime defects are fixed, require the complete
// records here too; never relax the positive 142-byte teardown comparison.
#[test]
fn known_teardown_defects_abort_on_new_span_and_dynamic_filter() {
    use std::os::unix::process::ExitStatusExt;

    for (case, diagnostic) in [
        (
            "new-span",
            // sharded-slab 0.1.7, shard.rs:295. Reassess this known defect
            // after a dependency update; complete records remain the goal.
            "Thread count overflowed the configured max count.",
        ),
        (
            "dynamic-filter",
            "cannot access a Thread Local Storage value during or after destruction: AccessError",
        ),
    ] {
        let (result, bytes) = teardown_subprocess(case);
        assert_eq!(
            result.status.signal(),
            Some(libc::SIGABRT),
            "{case}: expected the known dependency abort, not complete logging"
        );
        let stderr = String::from_utf8_lossy(&result.stderr);
        assert!(stderr.contains(diagnostic), "{case}: {stderr}");
        assert!(
            stderr.contains("thread local panicked on drop, aborting"),
            "{case}: {stderr}"
        );
        assert_eq!(
            bytes, TEARDOWN_RECORD,
            "{case}: the known defect preserves only the 71-byte warmup"
        );
    }
}

#[test]
fn known_teardown_defect_loses_context_without_reporting_a_local_failure() {
    let (result, bytes) = teardown_subprocess("contextual");
    // The child also requires RecordStatus to remain clear. Exit success and
    // a clear local status are insufficient: the entered context was lost.
    assert!(result.status.success(), "{:?}", result.stderr);
    assert!(result.stderr.is_empty(), "{:?}", result.stderr);
    let missing_context = b" INFO host_record: retained value=11 answer=\"stable\"\n";
    assert_eq!(bytes, [TEARDOWN_RECORD, missing_context].concat());
    assert_eq!(bytes.len(), 124);
    assert_ne!(bytes, TEARDOWN_RECORD.repeat(2));
}