fluxframe-cli 0.8.0

fluxframe CLI binary: list, check, run, benchmark.
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
//! Consumer-presence detection for v4l2loopback devices.
//!
//! Linux-only. On other targets this module is not compiled, and the
//! supervisor (`build_idle_runtime` in `runtime.rs`) gates its wiring
//! through the same `cfg`.
//!
//! ## Sources, in order of preference
//!
//! | `idle.presence_source` | Behaviour |
//! |---|---|
//! | `auto` (default) | Kernel `V4L2_EVENT_PRI_CLIENT_USAGE` events, degrading to the heuristic below when the subscription is unavailable. |
//! | `kernel_event` | Kernel events only. On failure the status stays `Unknown` (read as "present"), so idle never engages — for telling a working fix apart from a silent fallback. |
//! | `inotify` | Force the heuristic. |
//! | `disabled` | Pin the status to `Present`; idle never engages. |
//!
//! The live choice is published as the `consumer_source` gauge, because
//! a silent degradation is otherwise indistinguishable from a healthy
//! run.
//!
//! The two kernel-event modes take a second knob,
//! `idle.resync_interval_secs`: how often to re-read the driver instead
//! of waiting for the next event (`0` disables it). The heuristic modes
//! ignore it — see "The resync tick" below.
//!
//! ## Why the kernel event is the primary source
//!
//! Two earlier designs failed, and their failure modes are the reason
//! the current one looks the way it does.
//!
//! Stage 15 polled `/sys/class/video4linux/<videoN>/state`, assuming
//! `"capture"` meant "a reader called `STREAMON`". It does not — the
//! attribute reflects the *producer's* `ready_for_capture` flag, so it
//! read `"capture"` the moment fluxframe itself started writing. The
//! detector pinned `Present` and idle never engaged.
//!
//! The `inotify` + `/proc`-walk hybrid that replaced it assumed the
//! walk was authoritative whenever it was readable. It never is: an
//! unprivileged process gets `EACCES` on every other user's
//! `/proc/<pid>/fd`, so "nobody holds the device" and "I may not see
//! who does" are indistinguishable. `CleanAbsent` — the only outcome
//! that cleared the open balance — was therefore unreachable, and a
//! single lost `IN_CLOSE` latched `Present` for the rest of the
//! process. Filtering the candidate set does not rescue it: on a
//! typical desktop dozens of unreadable processes can genuinely open
//! the device.
//!
//! `V4L2_EVENT_PRI_CLIENT_USAGE` (see
//! [`fluxframe_gst::v4l2_events`]) sidesteps both: the driver reports
//! capture usage as an absolute value, so there is no state to
//! accumulate and drift, and the verdict never depends on `/proc`. It
//! also fires on `STREAMON`/`STREAMOFF` rather than `open`/`close`, so
//! device enumeration no longer counts as a consumer. (The resync tick
//! below does walk `/proc`, but only for the `external_openers`
//! diagnostic — never to decide presence.)
//!
//! ## The resync tick
//!
//! The subscription is edge-triggered, which makes it a single point of
//! failure: an event the driver never queues — or never delivers —
//! latches the verdict for the rest of the run. Every
//! `idle.resync_interval_secs` the detector therefore re-reads the
//! absolute value from a fresh descriptor and repairs itself. See
//! [`resync_tick`] for the ordering constraints and
//! [`ResyncSchedule`] for the cadence.
//!
//! Until the first reading arrives the status stays `Unknown`, which
//! the state machine treats as "present": idle must never engage on an
//! assumption.
//!
//! ## How the inotify + walk fallback works
//!
//! The detector watches `/dev/videoN` for `IN_OPEN`,
//! `IN_CLOSE_NOWRITE` and `IN_CLOSE_WRITE` via `inotify`. In
//! steady-state idle the cost is one nonblocking `read(2)` returning
//! `EAGAIN` every ~50 ms (the [`SHUTDOWN_POLL_GRANULARITY`] window
//! used so the worker can honour `running` / `stopped`), not a
//! per-event syscall — orders of magnitude cheaper than the prior
//! per-poll `/proc` walk, and the kernel only delivers an actual
//! event when somebody opens or closes the device.
//!
//! On every event the detector classifies the device via two signals,
//! folded together in [`ConsumerPresence`]:
//!
//! 1. A `/proc/[0-9]+/fd/` walk ([`count_external_consumers`], filtering
//!    out `my_pid`) yields a [`WalkOutcome`]: a readable external holder
//!    (`External`), a fully-readable "nobody" (`CleanAbsent`), a walk
//!    where ≥1 candidate `/proc/<pid>/fd` returned `EACCES` so the answer
//!    is suspect (`UncertainAbsent` — a sandboxed/root-owned consumer is
//!    indistinguishable from "nobody"), or an unreadable `/proc` root
//!    (`Unreadable` → `Unknown`, fail-open).
//! 2. A net **open balance**: `IN_OPEN` is `+1`, `IN_CLOSE_*` is `−1`,
//!    accumulated since the watch armed. fluxframe never re-opens the
//!    loopback after startup (its output write-fd is opened before the
//!    watch and held for the whole run), so a positive balance means an
//!    external consumer is attached — *even one the walk cannot see*.
//!
//! `ConsumerPresence::observe` combines them: a readable walk is
//! authoritative (`External → Present`, `CleanAbsent → Absent`), while an
//! `UncertainAbsent` walk defers to the balance — a held open we could
//! not attribute (EACCES) still wakes to `Present`, and returns to
//! `Absent` when it closes. This is what lets a sandboxed browser (whose
//! capture process is non-dumpable → `/proc/<pid>/fd` = EACCES) wake the
//! daemon. `ENOENT` from a process that exited mid-scan is skipped.
//!
//! ## Overflow and fallback
//!
//! On `IN_Q_OVERFLOW` (extremely rare unless the system is under
//! pathological load), the detector does one synchronous walk to
//! resync.
//!
//! When `inotify::init` or `watches().add` fails (e.g. user at
//! `/proc/sys/fs/inotify/max_user_watches`, hard sandbox, or the
//! device node doesn't exist), the dispatcher falls back to the
//! original polling path — a `/proc` walk every
//! `idle.poll_interval_ms`. The walk happens identically; only the
//! wake mechanism differs. Public behaviour and `ConsumerStatus`
//! semantics are unchanged.
//!
//! The dispatcher also falls back on `IN_IGNORED` (e.g. `modprobe
//! -r v4l2loopback` removes the watched node mid-run); polling
//! continues reporting whatever the walk decides until the device
//! comes back. Persistent `read_events` failures (rare — typically
//! `EINTR` storms) publish `Unknown` (fail-open) on the first error
//! and after [`INOTIFY_READ_ERROR_BUDGET`] consecutive errors
//! escalate to a polling fallback so the watch never silently dies.
//!
//! ## RESTAT semantics
//!
//! The polling path rearms the [`LogOnce`] gates every
//! `RESTAT_INTERVAL_POLLS` *poll iterations*; the inotify path
//! rearms every `RESTAT_INTERVAL_POLLS` *walks* (each walk fires on
//! an open/close event). On a busy device the cadence is similar;
//! on a quiet device the inotify path may never rearm — which is a
//! feature, not a bug, since the gates exist to surface
//! activity-time problems.
//!
//! ## Limitations
//!
//! * **Unattributable consumers rely on the open balance.** An
//!   unprivileged fluxframe cannot read a root-owned or sandboxed
//!   consumer's `/proc/<pid>/fd`, so the walk classifies it as
//!   `UncertainAbsent`. The net open balance still catches a *held*
//!   open (inotify fires regardless of who opened), so such a consumer
//!   does wake the daemon; the residual blind spot is a consumer that
//!   was already holding the device *before* the watch armed (its
//!   opening `IN_OPEN` predates the balance) — it reads as `Absent`
//!   until it re-opens. Running fluxframe as the same user as the
//!   consumer removes the EACCES entirely (the walk then sees it).
//! * **`/proc` must be mounted.** Hard containerization that hides
//!   `/proc` collapses the walk to `Unreadable` → `Unknown` (fail-open).
//!
//! ## Lifecycle
//!
//! [`ConsumerDetector::spawn`] returns a handle owning the worker
//! thread. The thread shuts down on either of two signals:
//!
//! * the caller-provided `running` flag flips to `false` (the
//!   supervisor's shared Ctrl-C atomic), OR
//! * the [`ConsumerDetector`] is dropped (sets an internal `stopped`
//!   flag that nobody else sees).
//!
//! `Drop` joins the worker. The poll loop uses a chunked sleep so
//! shutdown latency is bounded at ~50 ms regardless of how large
//! `poll_interval` is — see [`SHUTDOWN_POLL_GRANULARITY`].
//!
//! [`IdleConfig::poll_interval_ms`]: fluxframe_core::IdleConfig::poll_interval_ms

use std::ffi::{OsStr, OsString};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(test)]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use fluxframe_core::{Counters, IdlePresenceSource};
use fluxframe_gst::ClientUsage;
use fluxframe_gst::output::OutputSink;
use fluxframe_gst::v4l2_events::ConsumerWatch;
use tracing::{debug, info, warn};

use super::resync::{DeviceProbe, NodeProbe, ResyncSchedule, ResyncState, resync_tick};
use super::state::ConsumerStatus;

/// Maximum number of unreadable-pid identifiers sampled into
/// [`WalkOutcome::UncertainAbsent`] for the diagnostic line. The full
/// EACCES count is kept separately; only this bounded sample is carried
/// so a pathological host cannot build an unbounded `Vec`.
const EACCES_PID_SAMPLE: usize = 8;

/// Number of poll iterations between log-flag re-arms. With the
/// default 250 ms poll cadence this is one re-arm every 15 s —
/// enough to surface a fresh diagnostic if `/proc` access conditions
/// change mid-run without spamming the log.
const RESTAT_INTERVAL_POLLS: u32 = 60;

/// Granularity of the worker's between-poll sleep. The loop wakes at
/// least this often to re-check `running` / `stopped`, capping
/// shutdown latency at this value regardless of `poll_interval`.
const SHUTDOWN_POLL_GRANULARITY: Duration = Duration::from_millis(50);

/// [`SHUTDOWN_POLL_GRANULARITY`] as a `poll(2)` timeout.
///
/// The saturating fallback deliberately rounds *down*: this timeout is
/// consumed by blocking calls on the thread `ConsumerDetector::drop`
/// joins, so an unrepresentable value must degrade into a shorter wait,
/// never into `i32::MAX` milliseconds — that would turn a retuned
/// constant into a shutdown deadlock.
pub(super) fn shutdown_bounded_timeout_ms() -> i32 {
    i32::try_from(SHUTDOWN_POLL_GRANULARITY.as_millis()).unwrap_or(i32::from(u8::MAX))
}

/// Persistent `inotify::read_events` failures budget. The first
/// failure already published `Unknown` (fail-open). After this many
/// consecutive errors we surface `DetectorExit::ReadFatal` so the
/// dispatcher falls back to polling rather than burning CPU on a
/// permanently broken fd.
const INOTIFY_READ_ERROR_BUDGET: u32 = 16;

/// Stack buffer size for `inotify::read_events`. Each event is a
/// ~16-byte header plus a variable-length name; 1024 bytes holds
/// ~64 events per drain. Steady-state is 0 events; bursts come
/// during pipeline state transitions (a handful of events).
const INOTIFY_EVENT_BUFFER_BYTES: usize = 1024;

/// Metric encoding for [`Counters::set_consumer_source`]: the
/// authoritative kernel `V4L2_EVENT_PRI_CLIENT_USAGE` path.
///
/// Zero means "the good path is live"; any non-zero value on the
/// metrics line means the detector degraded to a heuristic.
const CONSUMER_SOURCE_KERNEL: u64 = 0;

/// Metric encoding for [`Counters::set_consumer_source`]: the
/// `inotify` + `/proc`-walk hybrid.
const CONSUMER_SOURCE_INOTIFY: u64 = 1;

/// Metric encoding for [`Counters::set_consumer_source`]: the
/// `/proc`-polling fallback (no inotify available).
const CONSUMER_SOURCE_POLL: u64 = 2;

/// Metric encoding for [`Counters::set_consumer_source`]: presence
/// detection switched off by config; the status is pinned to `Present`.
const CONSUMER_SOURCE_DISABLED: u64 = 3;

/// A source of absolute capture-usage readings from the loopback node.
///
/// Exists as a trait purely as a test seam: the production
/// implementation is [`fluxframe_gst::v4l2_events::ConsumerWatch`],
/// which needs a live v4l2loopback fd that no unit test has. Behind
/// this trait the decision loop can be driven from a scripted fake.
pub(crate) trait UsageSource {
    /// Block up to `timeout_ms` for a fresh reading.
    ///
    /// `Ok(None)` means the wait expired with nothing new — not "no
    /// consumer". `Err` means the subscription is dead and the caller
    /// must stop using this source.
    ///
    /// Yields the driver's [`ClientUsage`] unchanged rather than a bare
    /// count: the "is anybody streaming" rule belongs to that type
    /// ([`ClientUsage::attached`]), and re-deriving it here would fork
    /// the same domain rule across two crates.
    fn wait(&mut self, timeout_ms: i32) -> io::Result<Option<ClientUsage>>;
}

impl UsageSource for ConsumerWatch {
    fn wait(&mut self, timeout_ms: i32) -> io::Result<Option<ClientUsage>> {
        self.poll(timeout_ms)
    }
}

/// Variant returned from [`run_detector_inotify`] back to the
/// dispatcher. Each variant maps to a deliberate dispatcher log
/// level: init/add-watch failures are routine on slim hosts and log
/// at `info`; watch-removed and read-fatal are runtime surprises and
/// log at `warn`.
enum DetectorExit {
    /// The watch fired `IN_IGNORED` — the device node was deleted
    /// (e.g. `modprobe -r v4l2loopback`). Fall back to polling so
    /// the detector keeps producing a status until the device
    /// returns.
    WatchRemoved,
    /// `Inotify::init` failed (sandbox, ENOMEM).
    InitFailed(io::Error),
    /// `watches().add` failed (ENOSPC = at `max_user_watches`,
    /// ENOENT when the device node doesn't exist).
    AddFailed(io::Error),
    /// `read_events` produced [`INOTIFY_READ_ERROR_BUDGET`]
    /// consecutive non-recoverable errors. The first error already
    /// published `Unknown` (fail-open).
    ReadFatal(io::Error),
}

impl std::fmt::Display for DetectorExit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WatchRemoved => f.write_str("watch removed (IN_IGNORED)"),
            Self::InitFailed(e) => write!(f, "inotify init failed: {e}"),
            Self::AddFailed(e) => write!(f, "inotify watch add failed: {e}"),
            Self::ReadFatal(e) => write!(f, "inotify read failed repeatedly: {e}"),
        }
    }
}

/// Read-only context bundle threaded through dispatcher and path
/// functions. Reduces argument count and keeps the call sites
/// readable.
///
/// Visible to the rest of `idle` because [`super::resync`] runs on this
/// same thread and against this same context — the two modules split
/// the detector's work, not its state.
pub(super) struct DetectorContext<'a> {
    pub(super) proc_root: &'a Path,
    pub(super) my_pid: u32,
    running: &'a AtomicBool,
    status: &'a AtomicU8,
    pub(super) stopped: &'a AtomicBool,
    restat_interval_polls: u32,
    pub(super) device_basename: &'a OsStr,
    /// Process-wide counters. The detector bumps
    /// `unattributable_wakes_total` when it wakes on an open it could
    /// not attribute via `/proc`.
    pub(super) counters: &'a Counters,
    /// How long the device may stay completely quiet before a
    /// `Present` verdict that rests only on the unattributable open
    /// balance is discarded. Derived from `idle.teardown_secs` so the
    /// decay never fires faster than the grace period the operator
    /// configured for entering idle.
    stale_balance_after: Duration,
    /// The operator's idle grace period, used by the resync path as the
    /// floor for its event-silence threshold. See the field of the same
    /// name on [`DetectorParams`].
    teardown_grace: Duration,
    /// Per-detector test counter incremented in the inotify path on
    /// successful init + add_watch. See [`ConsumerDetector::inotify_activations_handle`].
    #[cfg(test)]
    inotify_activations: &'a AtomicU64,
}

/// Mutable per-run state threaded between dispatcher and path
/// functions. Pulled out of arg lists so neither path needs
/// `clippy::too_many_arguments`.
///
/// `last_status` is a plain `&mut`, which is the reason both this and
/// [`super::resync`] must stay on the detector thread — see
/// [`super::resync::resync_tick`].
pub(super) struct DetectorState<'a> {
    log_once: &'a mut LogOnce,
    pub(super) last_status: &'a mut Option<ConsumerStatus>,
    presence: &'a mut ConsumerPresence,
}

/// Resolve the `/dev/videoN` device path for a V4L2 output sink.
/// Returns `None` for non-V4L2 sinks (`Fake` / `Auto` / `Pipewire`) —
/// the supervisor uses the `Option` to gate detector spawn.
#[must_use]
pub(crate) fn device_path(sink: &OutputSink) -> Option<PathBuf> {
    let OutputSink::V4l2Loopback { device } = sink else {
        return None;
    };
    Some(device.clone())
}

/// One-shot fire gate. `fire()` returns `true` once and then `false`
/// until `rearm()` flips it back on. Encapsulates the consume-on-use
/// pattern shared by every diagnostic flag in [`LogOnce`].
struct Gate(bool);

impl Gate {
    /// Construct an armed gate (will fire on the next `fire()` call).
    const fn armed() -> Self {
        Self(true)
    }

    /// Attempt to consume the gate. Returns `true` exactly once per
    /// `armed()` / `rearm()` cycle.
    fn fire(&mut self) -> bool {
        std::mem::replace(&mut self.0, false)
    }

    /// Re-arm the gate so the next `fire()` returns `true` again.
    fn rearm(&mut self) {
        self.0 = true;
    }

    /// Test/inspection helper: is the gate currently armed?
    #[cfg(test)]
    pub(super) fn is_armed(&self) -> bool {
        self.0
    }
}

/// One-shot diagnostic gates for the detector. Each gate fires at
/// most once per re-arm window. `LogOnce::rearm()` re-arms every
/// gate in lockstep.
///
/// Gates:
/// * `scan_failed` — top-level `/proc` `read_dir` failure (the only
///   realistic detector failure).
/// * `eacces_storm` — every candidate `/proc/<pid>/fd` returned
///   `EACCES`, so we found no consumers but the answer is suspect.
struct LogOnce {
    scan_failed: Gate,
    eacces_storm: Gate,
}

impl LogOnce {
    /// All gates armed — each will log on its next matching failure.
    fn armed() -> Self {
        Self {
            scan_failed: Gate::armed(),
            eacces_storm: Gate::armed(),
        }
    }

    /// Re-arm every gate (called on `RESTAT_INTERVAL_POLLS` boundary).
    fn rearm(&mut self) {
        self.scan_failed.rearm();
        self.eacces_storm.rearm();
    }
}

/// Outcome of one `/proc` walk — pure data, no side effects. The caller
/// ([`walk_observe_publish`]) fires the one-shot diagnostics and folds
/// this into the presence latch. Keeping the walk free of `&mut LogOnce`
/// makes it trivially unit-testable and puts every log line at one
/// consistent layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum WalkOutcome {
    /// A readable external process holds the device fd; `pid` is the
    /// first such holder (the walk short-circuits on the first match).
    External { pid: u32 },
    /// No external holder, and every candidate `/proc/<pid>/fd` was
    /// readable — authoritatively nobody.
    CleanAbsent,
    /// No external holder found, but ≥1 candidate `/proc/<pid>/fd`
    /// returned `EACCES`, so the answer is suspect: a sandboxed or
    /// root-owned consumer looks identical to "nobody". `eacces_count`
    /// is the full count; `pids` a bounded sample for diagnostics.
    UncertainAbsent { eacces_count: u32, pids: Vec<u32> },
    /// `/proc` root itself was unreadable — detection disabled.
    Unreadable(io::ErrorKind),
}

/// Why the detector published a given [`ConsumerStatus`]. `Copy` so it
/// threads into the diagnostic line and the wake counter without
/// allocating on the common unchanged-walk path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PresenceReason {
    /// A readable external holder was found.
    External,
    /// A fully-readable `/proc` walk found nobody — authoritative absence.
    CleanAbsent,
    /// An unattributable (EACCES) walk with a zero open balance — assumed
    /// absent, but not authoritative. Distinguished from `CleanAbsent` so
    /// an operator reading the diagnostic can tell a proven absence from a
    /// fail-open guess.
    UncertainAbsent,
    /// An open we could not attribute (EACCES) with a positive open
    /// balance — the fail-open wake.
    UnattributableWake,
    /// `/proc` root unreadable — fail-open `Unknown`.
    FailOpen,
}

/// Consumer-presence latch. Pure state machine mirroring
/// [`super::state::IdleStateMachine`]'s style — the producer end of the
/// detector's status channel, kept separate from the worker-side
/// consumer FSM (they sit on opposite ends of the `AtomicU8`).
///
/// `open_balance` tracks live external opens of the loopback: inotify
/// `IN_OPEN` is `+1`, `IN_CLOSE_*` is `−1`, accumulated since the watch
/// armed. inotify counts open *file descriptions*, so `dup`/`fork` do
/// not inflate it and a crashed consumer still emits its close. Because
/// fluxframe never re-opens the loopback after startup (the output
/// write-fd is opened before the watch and held for the whole run), a
/// positive balance means an external consumer is attached — even one
/// whose `/proc/<pid>/fd` is unreadable (a sandboxed browser → EACCES).
/// The readable walk (`External`/`CleanAbsent`) re-anchors the balance
/// authoritatively, so drift is self-correcting.
#[derive(Default)]
struct ConsumerPresence {
    open_balance: i32,
}

impl ConsumerPresence {
    /// Fold one walk outcome plus the inotify open/close delta into the
    /// latch and return the published status and the reason for it.
    fn observe(
        &mut self,
        walk: &WalkOutcome,
        net_opens: i32,
        overflow: bool,
    ) -> (ConsumerStatus, PresenceReason) {
        // `overflow` means we lost events: reset the balance and let the
        // walk re-anchor. Otherwise fold the batch's net delta, clamped
        // at zero so an unmatched close (a pre-watch fd closing after
        // the watch armed) cannot drive the balance negative.
        if overflow {
            self.open_balance = 0;
        } else {
            self.open_balance = (self.open_balance + net_opens).max(0);
        }
        match walk {
            WalkOutcome::Unreadable(_) => (ConsumerStatus::Unknown, PresenceReason::FailOpen),
            WalkOutcome::External { .. } => {
                // Re-anchor to exactly 1, not `max(1)`. A readable walk
                // is authoritative in *both* directions: it says "one
                // holder, right now". Keeping a larger accumulated
                // balance here was the bug that let drift survive every
                // authoritative observation and latch `Present` for the
                // rest of the process — the balance could then only ever
                // be paid down by an exactly-matching number of closes.
                self.open_balance = 1;
                (ConsumerStatus::Present, PresenceReason::External)
            }
            WalkOutcome::CleanAbsent => {
                self.open_balance = 0;
                (ConsumerStatus::Absent, PresenceReason::CleanAbsent)
            }
            WalkOutcome::UncertainAbsent { .. } => {
                if self.open_balance > 0 {
                    (ConsumerStatus::Present, PresenceReason::UnattributableWake)
                } else {
                    (ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
                }
            }
        }
    }

    /// Should a `Present` verdict that rests only on the open balance be
    /// discarded because nothing has happened for `threshold`?
    ///
    /// A balance-backed `Present` is a guess: we saw an open we could
    /// not attribute and assume the holder is still there. If the device
    /// then goes completely silent — no opens, no closes — for longer
    /// than the idle grace period, the guess has outlived its evidence.
    /// Without this the balance can only ever be paid down by an
    /// exactly-matching close, so a single lost close pins the camera on
    /// for the rest of the process.
    ///
    /// Pure so it can be tested without threads or sleeps.
    fn is_stale(open_balance: i32, since_last_event: Duration, threshold: Duration) -> bool {
        open_balance > 0 && since_last_event >= threshold
    }

    /// Apply [`ConsumerPresence::is_stale`], zeroing the balance when it
    /// has gone stale. Returns `true` if the balance was discarded, so
    /// the caller can re-walk and log.
    fn decay_if_stale(&mut self, since_last_event: Duration, threshold: Duration) -> bool {
        if Self::is_stale(self.open_balance, since_last_event, threshold) {
            self.open_balance = 0;
            true
        } else {
            false
        }
    }

    /// Reset the balance to zero. Called when the inotify path falls
    /// back to polling (no more edge counting), so a stale positive
    /// balance cannot latch `Present` until the next authoritative walk.
    fn reset(&mut self) {
        self.open_balance = 0;
    }
}

/// Detector handle returned from [`ConsumerDetector::spawn`]. Owns
/// the worker thread and exposes the shared status atomic.
///
/// Drop joins the worker — see the module docstring. There is no
/// public `join` method; the supervisor relies on `Drop`.
pub(crate) struct ConsumerDetector {
    handle: Option<JoinHandle<()>>,
    status: Arc<AtomicU8>,
    /// Drop-only kill signal. Flipped to `true` in `Drop::drop` so
    /// the worker can exit even when the caller's `running` flag
    /// is still `true` (test cleanup; supervisor teardown ordering).
    stopped: Arc<AtomicBool>,
    /// Per-detector test-only counter, incremented each time
    /// `run_detector_inotify` successfully reaches its main loop
    /// (init + add_watch both succeeded). Tests snapshot the
    /// per-detector Arc to assert the inotify path was actually
    /// taken (vs. silently falling back to polling) without racing
    /// against sibling tests via a global.
    #[cfg(test)]
    inotify_activations: Arc<AtomicU64>,
}

/// Everything the detector thread needs to know about *what* to watch
/// and *how* to decide, as opposed to the shared handles it reports
/// through.
///
/// Bundled because the argument list crossed the point where positional
/// parameters stop being readable — five of the six were `Duration`,
/// `u32` or `PathBuf`, so a transposed pair would have compiled.
pub(crate) struct DetectorParams {
    /// `/dev/videoN` whose basename is matched against fd targets in
    /// the `/proc` fallback, and which the inotify watch is armed on.
    pub(crate) device_path: PathBuf,
    /// The supervisor's own pid; fds held by it are excluded from the
    /// external-consumer count.
    pub(crate) my_pid: u32,
    /// Cadence of the `/proc`-polling fallback. Unused by the other
    /// two sources, which are edge-driven.
    pub(crate) poll_interval: Duration,
    /// Which presence mechanism to use.
    pub(crate) mode: IdlePresenceSource,
    /// Quiet period after which a `Present` verdict resting only on an
    /// unattributable open balance is discarded.
    pub(crate) stale_balance_after: Duration,
    /// The operator's idle grace period (`idle.teardown_secs`).
    ///
    /// Its own field rather than a second reading of
    /// `stale_balance_after`: that one is a heuristic-path knob that may
    /// be retuned for `inotify` reasons, and the resync path's silence
    /// threshold must not move silently when it is.
    pub(crate) teardown_grace: Duration,
    /// How often to re-read the driver's absolute capture-usage value
    /// instead of trusting the event stream. `None` disables it.
    ///
    /// Honoured only by the kernel-event source. The heuristic paths
    /// cannot use it: the probe's `open`/`close` would land in their own
    /// `IN_OPEN`/`IN_CLOSE` balance and read as a consumer attaching.
    pub(crate) resync_interval: Option<Duration>,
}

/// The shared handles the detector thread reports *through*, as opposed
/// to the [`DetectorParams`] that say what to watch.
///
/// Bundled for the same reason as `DetectorParams`: `running` and
/// `stopped` are both `Arc<AtomicBool>` and a transposed pair would
/// compile silently while inverting the shutdown logic.
struct DetectorHandles {
    /// The supervisor's shared Ctrl-C flag. Clearing it stops the thread.
    running: Arc<AtomicBool>,
    /// Where the detector publishes its [`ConsumerStatus`].
    status: Arc<AtomicU8>,
    /// Drop-only kill signal owned by [`ConsumerDetector`].
    stopped: Arc<AtomicBool>,
    /// Process-wide metrics.
    counters: Arc<Counters>,
}

/// Injection points that production code fixes to constants and only
/// tests vary. Kept off [`DetectorParams`] so test-only knobs never leak
/// into the type the supervisor constructs.
pub(crate) struct DetectorTestKnobs {
    /// `/proc` in production; a tempdir in the walk tests.
    proc_root: PathBuf,
    /// [`RESTAT_INTERVAL_POLLS`] in production.
    restat_interval_polls: u32,
    /// Per-detector activation counter for the inotify path.
    #[cfg(test)]
    inotify_activations: Arc<AtomicU64>,
}

impl ConsumerDetector {
    /// Spawn the detector thread. The thread watches the device via
    /// inotify; the `poll_interval` is used only by the
    /// `/proc/*/fd/` polling fallback that fires when inotify init
    /// or watch-add fails. The thread shuts down when either
    /// `running` flips to `false` or the returned handle is dropped.
    ///
    /// `device_path` is the `/dev/videoN` path whose basename we
    /// match against fd targets. `my_pid` is the supervisor's own
    /// pid (typically `std::process::id()`); fds held by this pid
    /// are excluded from the external-consumer count.
    ///
    /// The `Unknown` initial status is reset to the first observed
    /// value on the first poll — the supervisor's state machine
    /// treats `Unknown` as `Present`, so the first tick is a no-op
    /// (Active stays Active) regardless of what the walk finds.
    pub(crate) fn spawn(
        params: DetectorParams,
        running: Arc<AtomicBool>,
        counters: Arc<Counters>,
        watch: Option<ConsumerWatch>,
    ) -> Self {
        Self::spawn_with_knobs(
            params,
            DetectorTestKnobs {
                proc_root: PathBuf::from("/proc"),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                #[cfg(test)]
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            running,
            counters,
            watch,
        )
    }

    /// Test-oriented constructor that lets tests inject a tempdir as
    /// `/proc`, tune the re-arm cadence, and observe how often the
    /// inotify path activated. Production code uses [`Self::spawn`]
    /// which fixes the defaults.
    pub(crate) fn spawn_with_knobs(
        params: DetectorParams,
        knobs: DetectorTestKnobs,
        running: Arc<AtomicBool>,
        counters: Arc<Counters>,
        watch: Option<ConsumerWatch>,
    ) -> Self {
        let status = Arc::new(AtomicU8::new(ConsumerStatus::Unknown.as_u8()));
        let stopped = Arc::new(AtomicBool::new(false));
        #[cfg(test)]
        let inotify_activations = Arc::clone(&knobs.inotify_activations);
        let handles = DetectorHandles {
            running,
            status: Arc::clone(&status),
            stopped: Arc::clone(&stopped),
            counters,
        };
        let handle = thread::Builder::new()
            .name("fluxframe-detector".into())
            .spawn(move || {
                run_detector(params, handles, knobs, watch);
            })
            .expect("spawn detector thread");
        Self {
            handle: Some(handle),
            status,
            stopped,
            #[cfg(test)]
            inotify_activations,
        }
    }

    /// Cheap clone of the shared status atomic. The worker reads this
    /// every loop iteration; only the detector writes to it. Ordering
    /// is `Acquire` on the worker side, `Release` on the detector
    /// side — see the comment in [`run_detector`] for the rationale.
    pub(crate) fn status_handle(&self) -> Arc<AtomicU8> {
        Arc::clone(&self.status)
    }

    /// Test-only handle on the per-detector inotify activation
    /// counter. Tests assert `> 0` after spawn to verify the inotify
    /// path was actually taken.
    #[cfg(test)]
    pub(super) fn inotify_activations_handle(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.inotify_activations)
    }
}

impl Drop for ConsumerDetector {
    fn drop(&mut self) {
        // Signal the worker to exit at its next poll-granularity
        // wakeup (≤ SHUTDOWN_POLL_GRANULARITY away).
        self.stopped.store(true, Ordering::Release);
        if let Some(handle) = self.handle.take() {
            if let Err(panic) = handle.join() {
                warn!(
                    target: "fluxframe::idle",
                    panic = ?panic,
                    "consumer detector thread panicked during shutdown"
                );
            }
        }
    }
}

/// Publish `new_status` to the shared atomic and log the transition,
/// but only when it differs from the previously-published value.
///
/// `Release` store pairs with the worker's `Acquire` load in
/// `IdleStateMachine::tick` — guarantees the timer restart on the
/// worker side is ordered after the observed transition.
fn publish_if_changed(
    new_status: ConsumerStatus,
    status: &AtomicU8,
    last_status: &mut Option<ConsumerStatus>,
    counters: &Counters,
) {
    if Some(new_status) == *last_status {
        return;
    }
    status.store(new_status.as_u8(), Ordering::Release);
    // Mirror onto the metrics line. The transition counter doubles as
    // the detector's liveness signal: a run whose status never moves is
    // indistinguishable in the log from a genuinely busy camera, which
    // is exactly how a permanently latched `Present` went unnoticed.
    counters.set_consumer_status(new_status.as_u8());
    if matches!(new_status, ConsumerStatus::Present | ConsumerStatus::Absent) {
        // Promoted to `info` (rare event, no spam risk) so the
        // operator can see attach/detach transitions with
        // `RUST_LOG=info` without enabling debug-level globally.
        info!(
            target: "fluxframe::idle",
            from = ?last_status,
            to = ?new_status,
            "consumer status changed"
        );
    } else {
        // Keep an explicit debug! for Unknown so operators running at
        // debug-level still see the transition.
        debug!(
            target: "fluxframe::idle",
            from = ?last_status,
            to = ?new_status,
            "consumer status changed"
        );
    }
    *last_status = Some(new_status);
}

/// Detector thread entry point. Owns everything it was handed (the
/// bundles are moved across the thread boundary) and destructures them
/// exactly once, here, so no call site ever has to keep a dozen
/// same-typed positional arguments in the right order.
fn run_detector(
    params: DetectorParams,
    handles: DetectorHandles,
    knobs: DetectorTestKnobs,
    watch: Option<ConsumerWatch>,
) {
    let DetectorParams {
        device_path,
        my_pid,
        poll_interval,
        mode,
        stale_balance_after,
        teardown_grace,
        resync_interval,
    } = params;
    let DetectorHandles {
        running,
        status,
        stopped,
        counters,
    } = handles;
    let DetectorTestKnobs {
        proc_root,
        restat_interval_polls,
        #[cfg(test)]
        inotify_activations,
    } = knobs;

    // Resolved once outside the loop — `file_name()` allocates `OsStr`
    // borrows from the underlying PathBuf and we want to avoid the
    // walk-time path manipulation.
    let Some(basename) = device_path.file_name() else {
        warn!(
            target: "fluxframe::idle",
            path = %device_path.display(),
            "device path has no basename — consumer detector disabled"
        );
        status.store(ConsumerStatus::Unknown.as_u8(), Ordering::Release);
        return;
    };
    let device_basename: OsString = basename.to_os_string();

    info!(
        target: "fluxframe::idle",
        device = %device_path.display(),
        my_pid,
        poll_ms = poll_interval.as_millis() as u64,
        ?mode,
        subscription = watch.is_some(),
        "consumer detector started"
    );

    let mut log_once = LogOnce::armed();
    let mut last_status: Option<ConsumerStatus> = None;
    let mut presence = ConsumerPresence::default();
    let ctx = DetectorContext {
        proc_root: &proc_root,
        my_pid,
        running: &running,
        status: &status,
        stopped: &stopped,
        restat_interval_polls,
        device_basename: &device_basename,
        counters: &counters,
        stale_balance_after,
        teardown_grace,
        #[cfg(test)]
        inotify_activations: &inotify_activations,
    };
    let mut state = DetectorState {
        log_once: &mut log_once,
        last_status: &mut last_status,
        presence: &mut presence,
    };

    // The probe re-opens the same node the watch was taken on; it is
    // built here so the kernel-event path gets it without knowing how a
    // device path becomes a probe.
    let probe = DeviceProbe::new(device_path.clone());
    let schedule = resync_interval.map_or(ResyncSchedule::Off, ResyncSchedule::every);

    // Try the inotify event-driven path first. On failure (watch
    // limit, sandbox restriction, device-node deleted mid-run, …)
    // fall back to the polling path. Both share
    // `count_external_consumers` for the actual presence test, so
    // the public contract is identical — only the wake mechanism
    // differs.
    if run_presence_source(mode, watch, &probe, schedule, &ctx, &mut state) {
        run_heuristic_detector(poll_interval, &device_path, &ctx, &mut state);
    }

    info!(target: "fluxframe::idle", "consumer detector exiting");
}

/// Dispatch to the configured presence source.
///
/// Returns `true` when the caller should run the `inotify`/`/proc`
/// heuristic — either because it was asked for, or because the
/// authoritative source was unavailable and the mode permits degrading.
fn run_presence_source<P: NodeProbe>(
    mode: IdlePresenceSource,
    watch: Option<ConsumerWatch>,
    probe: &P,
    schedule: ResyncSchedule,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) -> bool {
    match mode {
        IdlePresenceSource::Disabled => {
            run_detector_disabled(ctx, state);
            false
        }
        IdlePresenceSource::Inotify => {
            // Drop the subscription we may have been handed: the
            // operator asked for the heuristic explicitly, and holding a
            // dup of the device fd would keep the loopback's open file
            // description alive for no reason.
            debug!(
                target: "fluxframe::idle",
                subscription = watch.is_some(),
                "presence_source = inotify — using the heuristic path"
            );
            drop(watch);
            true
        }
        IdlePresenceSource::Auto | IdlePresenceSource::KernelEvent => {
            let strict = mode == IdlePresenceSource::KernelEvent;
            let Some(mut watch) = watch else {
                if strict {
                    // Deliberately do NOT degrade: the operator asked to
                    // know whether the kernel path works. `Unknown` reads
                    // as "present", so the camera stays on and nothing
                    // silently papers over the missing subscription.
                    warn!(
                        target: "fluxframe::idle",
                        "presence_source = kernel_event but the sink exposes no \
                         subscription — presence is UNKNOWN and idle will not engage"
                    );
                    park_until_stopped(ctx);
                    return false;
                }
                info!(
                    target: "fluxframe::idle",
                    "no kernel client-usage subscription available — using the \
                     inotify + /proc heuristic"
                );
                return true;
            };
            match run_detector_client_usage(&mut watch, probe, schedule, ctx, state) {
                Ok(()) => false,
                Err(e) if strict => {
                    warn!(
                        target: "fluxframe::idle",
                        error = %e,
                        "kernel client-usage subscription died and \
                         presence_source = kernel_event forbids falling back"
                    );
                    publish_if_changed(
                        ConsumerStatus::Unknown,
                        ctx.status,
                        state.last_status,
                        ctx.counters,
                    );
                    park_until_stopped(ctx);
                    false
                }
                Err(e) => {
                    warn!(
                        target: "fluxframe::idle",
                        error = %e,
                        "kernel client-usage subscription died — falling back to \
                         the inotify + /proc heuristic"
                    );
                    // Fail open while the heuristic re-establishes a verdict.
                    publish_if_changed(
                        ConsumerStatus::Unknown,
                        ctx.status,
                        state.last_status,
                        ctx.counters,
                    );
                    true
                }
            }
        }
    }
}

/// The pre-0.5 heuristic: `inotify` first, `/proc` polling as its own
/// fallback. Both share `count_external_consumers` for the actual
/// presence test — only the wake mechanism differs.
fn run_heuristic_detector(
    poll_interval: Duration,
    device_path: &Path,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) {
    if let Err(exit) = run_detector_inotify(device_path, ctx, state) {
        match &exit {
            DetectorExit::WatchRemoved => warn!(
                target: "fluxframe::idle",
                "inotify watch removed — falling back to /proc polling"
            ),
            DetectorExit::ReadFatal(e) => warn!(
                target: "fluxframe::idle",
                error = %e,
                "inotify read repeatedly failed — falling back to /proc polling"
            ),
            DetectorExit::InitFailed(_) | DetectorExit::AddFailed(_) => info!(
                target: "fluxframe::idle",
                reason = %exit,
                "inotify path unavailable — falling back to /proc polling"
            ),
        }
        ctx.counters.set_consumer_source(CONSUMER_SOURCE_POLL);
        run_detector_polling(poll_interval, ctx, state);
    }
}

/// Sleep in shutdown-responsive slices until the thread is told to stop.
/// Used by the paths that publish a fixed verdict and have nothing left
/// to observe.
fn park_until_stopped(ctx: &DetectorContext<'_>) {
    while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
        thread::sleep(SHUTDOWN_POLL_GRANULARITY);
    }
}

/// Drive the detector from absolute kernel capture-usage readings.
///
/// The loop does not interpret the signal: it takes each reading the
/// driver hands it, asks the reading itself whether a capture client is
/// streaming ([`ClientUsage::attached`]), and publishes that. There is
/// no balance to accumulate, so the verdict cannot drift by degrees —
/// but it *can* be lost outright, because the signal is edge-triggered:
/// an event the driver never queues, or never delivers, leaves the last
/// verdict standing for the rest of the run. Twice in production that
/// verdict was `Absent`, and the camera stayed down until the daemon
/// was restarted.
///
/// [`resync_tick`] is the answer to that: on the cadence given by
/// `schedule` it re-reads the absolute value from the driver and
/// corrects the verdict when the two disagree.
///
/// Blocks in `wait` for at most [`SHUTDOWN_POLL_GRANULARITY`] so the
/// thread stays responsive to `running` / `stopped` — the handle's
/// `Drop` joins this thread, so an unbounded block here would deadlock
/// teardown.
///
/// Until the first reading arrives the status stays `Unknown`, which the
/// state machine treats as "consumer present". That is deliberate: idle
/// must never engage on an assumption. In practice the window is
/// negligible because the subscription asks for the initial value.
///
/// Returns `Err` when the subscription dies (device removed, module
/// unloaded); the caller decides whether to fall back.
fn run_detector_client_usage<S: UsageSource, P: NodeProbe>(
    source: &mut S,
    probe: &P,
    schedule: ResyncSchedule,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) -> io::Result<()> {
    let timeout_ms = shutdown_bounded_timeout_ms();
    ctx.counters.set_consumer_source(CONSUMER_SOURCE_KERNEL);
    info!(
        target: "fluxframe::idle",
        "consumer detection using kernel client-usage events"
    );
    let mut resync = ResyncState::new(schedule, ctx.teardown_grace);
    resync.announce();

    while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
        resync.note_iteration();
        if let Some(usage) = source.wait(timeout_ms)? {
            debug!(
                target: "fluxframe::idle",
                count = usage.count,
                "client-usage event"
            );
            resync.note_external_event();
            apply_usage(usage, ctx, state);
        }
        // Re-check the shutdown flags before the tick: `wait` may have
        // just consumed the whole timeout, and the tick opens the device.
        if !ctx.running.load(Ordering::Acquire) || ctx.stopped.load(Ordering::Acquire) {
            break;
        }
        if resync.due() {
            resync_tick(source, probe, ctx, state, &mut resync);
        }
    }
    Ok(())
}

/// Publish one absolute reading: both the verdict and the client count.
///
/// Single entry point on purpose. The event path and the resync path
/// used to be free to update one and not the other, and a metrics line
/// that says `consumer_status=1 consumer_clients=0` is exactly the kind
/// of self-contradiction that costs an hour when reading logs after an
/// incident.
///
/// The two are still separate atomics, so a snapshot taken between them
/// can catch the pair mid-update. This narrows that window to a couple
/// of instructions rather than closing it — closing it would mean
/// packing verdict and count into one atomic, which is not worth the
/// encoding for a diagnostic gauge.
pub(super) fn apply_usage(
    usage: ClientUsage,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) {
    ctx.counters.set_consumer_clients(u64::from(usage.count));
    let status = if usage.attached() {
        ConsumerStatus::Present
    } else {
        ConsumerStatus::Absent
    };
    publish_if_changed(status, ctx.status, state.last_status, ctx.counters);
}

/// Pin the status to `Present` and park until shutdown.
///
/// Used for `presence_source = "disabled"`: idle never engages, the
/// camera is held for the whole run, but the placeholder machinery and
/// the loopback's CAPTURE-caps heartbeat are untouched. This is the
/// operator's "stop guessing, just keep the camera on" switch.
fn run_detector_disabled(ctx: &DetectorContext<'_>, state: &mut DetectorState<'_>) {
    ctx.counters.set_consumer_source(CONSUMER_SOURCE_DISABLED);
    info!(
        target: "fluxframe::idle",
        "consumer detection disabled by config — idle will never engage"
    );
    publish_if_changed(
        ConsumerStatus::Present,
        ctx.status,
        state.last_status,
        ctx.counters,
    );
    park_until_stopped(ctx);
}

/// Running summary of a batch of `inotify` events. Built up
/// incrementally by [`EventSummary::observe`] as the reader drains
/// the kernel queue.
#[derive(Default, Clone, Copy)]
struct EventSummary {
    needs_rescan: bool,
    /// Net open/close delta over the batch: `IN_OPEN` is `+1`,
    /// `IN_CLOSE_*` is `−1`. Feeds [`ConsumerPresence`]'s open balance.
    net_opens: i32,
    overflow: bool,
    watch_removed: bool,
}

impl EventSummary {
    /// Fold a single event's mask into the running summary.
    fn observe(&mut self, mask: inotify::EventMask) {
        if mask.contains(inotify::EventMask::Q_OVERFLOW) {
            self.overflow = true;
        }
        // OPEN and CLOSE arrive as distinct events, but fold each
        // independently so a hypothetical combined mask is still counted
        // correctly. `needs_rescan` stays the walk trigger; `net_opens`
        // is only the balance input.
        if mask.contains(inotify::EventMask::OPEN) {
            self.needs_rescan = true;
            self.net_opens += 1;
        }
        if mask.intersects(inotify::EventMask::CLOSE_WRITE | inotify::EventMask::CLOSE_NOWRITE) {
            self.needs_rescan = true;
            self.net_opens -= 1;
        }
        if mask.contains(inotify::EventMask::IGNORED) {
            self.watch_removed = true;
        }
    }
}

/// Event-driven detector path. Watches the device for
/// `IN_OPEN` / `IN_CLOSE_NOWRITE` / `IN_CLOSE_WRITE` and, on every
/// event, walks `/proc` via `count_external_consumers` to decide
/// Present vs Absent. In steady-state idle the cost is one
/// nonblocking `read(2)` returning `EAGAIN` every ~50 ms (the
/// [`SHUTDOWN_POLL_GRANULARITY`] window), not a per-event syscall —
/// orders of magnitude cheaper than the prior per-poll `/proc`
/// walk, and the kernel only delivers an actual event when the
/// device is opened or closed.
///
/// # Errors
///
/// Returns:
///
/// * [`DetectorExit::InitFailed`] — `Inotify::init` failed (sandbox,
///   ENOMEM).
/// * [`DetectorExit::AddFailed`] — `watches().add` failed (ENOSPC at
///   `max_user_watches`, ENOENT for a missing device node).
/// * [`DetectorExit::WatchRemoved`] — the watch fired `IN_IGNORED`
///   mid-run (e.g. `modprobe -r v4l2loopback`).
/// * [`DetectorExit::ReadFatal`] — `read_events` returned
///   non-recoverable errors for [`INOTIFY_READ_ERROR_BUDGET`]
///   consecutive iterations; the first failure already published
///   `Unknown` (fail-open).
fn run_detector_inotify(
    device_path: &Path,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) -> Result<(), DetectorExit> {
    let mut inotify = inotify::Inotify::init().map_err(DetectorExit::InitFailed)?;
    inotify
        .watches()
        .add(
            device_path,
            inotify::WatchMask::OPEN
                | inotify::WatchMask::CLOSE_NOWRITE
                | inotify::WatchMask::CLOSE_WRITE,
        )
        .map_err(DetectorExit::AddFailed)?;

    #[cfg(test)]
    ctx.inotify_activations.fetch_add(1, Ordering::Release);

    // Publish the live detection path only once the watch is actually
    // armed: a silent degradation to a weaker path is otherwise
    // indistinguishable in the metrics from a healthy run.
    ctx.counters.set_consumer_source(CONSUMER_SOURCE_INOTIFY);

    // Baseline walk — the kernel only delivers events that happen
    // AFTER `add()`, so we need one synchronous walk to publish the
    // initial state. Without this the worker would observe
    // `Unknown` until the first open/close, which on a quiet system
    // may be never. No inotify delta yet (`net_opens = 0`).
    walk_observe_publish(ctx, state, 0, false);

    let mut buffer = [0u8; INOTIFY_EVENT_BUFFER_BYTES];
    let mut walks_since_restat: u32 = 0;
    // Consecutive `read_events` errors (non-WouldBlock). Reset on
    // every successful read. The first error already published
    // Unknown (fail-open); the budget below caps how long we keep
    // retrying before escalating to a polling fallback.
    let mut consecutive_read_errors: u32 = 0;
    // When the device last saw any open/close. Feeds the staleness
    // decay below; a device nobody touches for a long time cannot still
    // be justifying a balance-backed `Present`.
    let mut last_event_at = Instant::now();

    while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
        let summary = read_event_batch(
            &mut inotify,
            &mut buffer,
            ctx,
            state,
            &mut consecutive_read_errors,
        )?;
        if summary.needs_rescan || summary.net_opens != 0 || summary.overflow {
            last_event_at = Instant::now();
        }
        apply_summary(summary, ctx, state, &mut walks_since_restat)?;

        if state
            .presence
            .decay_if_stale(last_event_at.elapsed(), ctx.stale_balance_after)
        {
            warn!(
                target: "fluxframe::idle",
                quiet_secs = last_event_at.elapsed().as_secs(),
                "discarding a stale unattributable open balance and re-checking; \
                 a close event was most likely missed"
            );
            last_event_at = Instant::now();
            walk_observe_publish(ctx, state, 0, false);
        }
    }

    Ok(())
}

/// Drain queued `inotify` events into an [`EventSummary`]. Handles
/// the WouldBlock sleep, the error budget, and the first-error
/// `Unknown` publish. Returns the accumulated summary on success;
/// returns [`DetectorExit::ReadFatal`] when the consecutive-error
/// budget is exhausted.
fn read_event_batch(
    inotify: &mut inotify::Inotify,
    buffer: &mut [u8],
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
    consecutive_read_errors: &mut u32,
) -> Result<EventSummary, DetectorExit> {
    let mut summary = EventSummary::default();
    match inotify.read_events(buffer) {
        Ok(events) => {
            *consecutive_read_errors = 0;
            for ev in events {
                summary.observe(ev.mask);
            }
        }
        Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
            *consecutive_read_errors = 0;
            // No events queued. Sleep at the shutdown granularity
            // so we honour `running` / `stopped` within ~50 ms.
            thread::sleep(SHUTDOWN_POLL_GRANULARITY);
        }
        Err(e) => {
            if *consecutive_read_errors == 0 {
                // Fail-open on the first surprise so the
                // supervisor's idle FSM treats the gap as Present
                // (Unknown is mapped to Present upstream). Better
                // to leave the input pipeline running through a
                // transient inotify hiccup than silently freeze on
                // stale Present.
                publish_if_changed(
                    ConsumerStatus::Unknown,
                    ctx.status,
                    state.last_status,
                    ctx.counters,
                );
            }
            *consecutive_read_errors = consecutive_read_errors.saturating_add(1);
            // Noise reduction: warn only on the very first error
            // (operator-visible) and right before we escalate to a
            // polling fallback. Intermediate retries land at debug
            // so a transient EINTR storm doesn't flood the log.
            let consecutive = *consecutive_read_errors;
            if consecutive == 1 || consecutive >= INOTIFY_READ_ERROR_BUDGET - 1 {
                warn!(
                    target: "fluxframe::idle",
                    error = %e,
                    consecutive,
                    "inotify read failed; retrying after shutdown poll window"
                );
            } else {
                debug!(
                    target: "fluxframe::idle",
                    error = %e,
                    consecutive,
                    "inotify read failed; retrying after shutdown poll window"
                );
            }
            if consecutive >= INOTIFY_READ_ERROR_BUDGET {
                return Err(DetectorExit::ReadFatal(e));
            }
            thread::sleep(SHUTDOWN_POLL_GRANULARITY);
        }
    }
    Ok(summary)
}

/// React to a drained [`EventSummary`]: log overflow, escalate
/// `IGNORED` to a `WatchRemoved` exit (publishing `Unknown` first so
/// the polling fallback's startup window doesn't leave a stale
/// status), and run the `/proc` walk + restat tick when an
/// open/close or overflow needs a rescan.
fn apply_summary(
    summary: EventSummary,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
    walks_since_restat: &mut u32,
) -> Result<(), DetectorExit> {
    if summary.watch_removed {
        // Publish Unknown BEFORE escalating so the polling fallback's
        // startup window (until its first walk completes) doesn't
        // leave a stale Present/Absent behind for the supervisor's
        // state machine to act on.
        publish_if_changed(
            ConsumerStatus::Unknown,
            ctx.status,
            state.last_status,
            ctx.counters,
        );
        // Device node disappeared. Surface to the dispatcher so
        // the polling fallback can keep producing a status
        // until the device returns.
        return Err(DetectorExit::WatchRemoved);
    }

    if summary.overflow {
        info!(
            target: "fluxframe::idle",
            "inotify queue overflow — resyncing via /proc walk"
        );
    }

    if summary.needs_rescan || summary.overflow {
        walk_observe_publish(ctx, state, summary.net_opens, summary.overflow);
        // Rearm gate cadence shifts from wall-clock (polling path)
        // to walk-count here. The gates exist to surface
        // activity-time problems; rearm-on-activity is arguably
        // better behaviour.
        tick_restat(
            walks_since_restat,
            ctx.restat_interval_polls,
            state.log_once,
        );
    }
    Ok(())
}

/// Bump a restat counter; when it crosses `interval`, rearm the
/// log-once gates and reset the counter. Shared by both the inotify
/// path (counts walks) and the polling path (counts polls).
fn tick_restat(counter: &mut u32, interval: u32, log_once: &mut LogOnce) {
    *counter = counter.wrapping_add(1);
    if *counter >= interval {
        log_once.rearm();
        *counter = 0;
    }
}

fn run_detector_polling(
    poll_interval: Duration,
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
) {
    let mut polls_since_restat: u32 = 0;
    // The polling path has no open/close edges to count, so drop any
    // balance the inotify path accumulated before falling back — a
    // stale positive balance must not latch `Present` here.
    state.presence.reset();

    while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
        // No inotify delta on the polling path (`net_opens = 0`); the
        // walk alone drives the status.
        walk_observe_publish(ctx, state, 0, false);

        // Clear the one-shot log flag every restat_interval_polls
        // so a transient diagnostic (e.g. `/proc` briefly remount)
        // re-surfaces after the re-arm window.
        tick_restat(
            &mut polls_since_restat,
            ctx.restat_interval_polls,
            state.log_once,
        );

        // Bounded shutdown latency: chunk the sleep so we re-check
        // `running` / `stopped` at least every
        // `SHUTDOWN_POLL_GRANULARITY`. Without this cap, a multi-
        // second `poll_interval` would delay Ctrl-C / Drop for the
        // full interval.
        let mut remaining = poll_interval;
        while remaining > Duration::ZERO
            && ctx.running.load(Ordering::Acquire)
            && !ctx.stopped.load(Ordering::Acquire)
        {
            let chunk = remaining.min(SHUTDOWN_POLL_GRANULARITY);
            thread::sleep(chunk);
            remaining = remaining.saturating_sub(chunk);
        }
    }
}

/// Walk `/proc`, fold the outcome into the presence latch, publish any
/// status change, and fire the one-shot diagnostics. This is the single
/// place the walk → observe → publish → log → metrics sequence lives;
/// the baseline walk, the inotify event path, and the polling fallback
/// all call it. `net_opens` is the inotify open/close delta for this
/// batch (`0` for the baseline and polling paths, which have no edges).
fn walk_observe_publish(
    ctx: &DetectorContext<'_>,
    state: &mut DetectorState<'_>,
    net_opens: i32,
    overflow: bool,
) {
    let walk = count_external_consumers(ctx.proc_root, ctx.device_basename, ctx.my_pid);
    let prev = *state.last_status;
    let (status, reason) = state.presence.observe(&walk, net_opens, overflow);

    // Diagnostics — both one-shot gates fire from this single site. The
    // walk is pure data; the presence-layer fields (`open_balance`,
    // `net_opens`, the decision) are only known here, so the enriched
    // EACCES line cannot live inside the walk.
    match &walk {
        WalkOutcome::Unreadable(kind) => {
            if state.log_once.scan_failed.fire() {
                warn!(
                    target: "fluxframe::idle",
                    proc_root = %ctx.proc_root.display(),
                    error = ?kind,
                    "/proc scan failed — consumer detection disabled"
                );
            }
        }
        WalkOutcome::UncertainAbsent { eacces_count, pids } => {
            if state.log_once.eacces_storm.fire() {
                // `comm` is world-readable even for a process whose
                // `fd/` dir gave EACCES (non-dumpable/sandboxed), so it
                // names the likely holder ("chrome"). Read only now —
                // the gate fires ≤ once per rearm window, off the hot
                // path.
                let comms = read_comms(ctx.proc_root, pids);
                info!(
                    target: "fluxframe::idle",
                    eacces_count = *eacces_count,
                    net_opens,
                    open_balance = state.presence.open_balance,
                    decision = ?status,
                    reason = ?reason,
                    comms = ?comms,
                    "scanned /proc; candidate fd dirs returned EACCES — a sandboxed/privileged consumer may be present"
                );
            }
        }
        WalkOutcome::External { .. } | WalkOutcome::CleanAbsent => {}
    }

    // An open we could not attribute but chose to treat as a consumer
    // (fail-open) that just flipped us to Present.
    if reason == PresenceReason::UnattributableWake && prev != Some(ConsumerStatus::Present) {
        ctx.counters.inc_unattributable_wakes();
    }

    publish_if_changed(status, ctx.status, state.last_status, ctx.counters);
}

/// Best-effort read of `/proc/<pid>/comm`.
///
/// `None` for a process that exited between the walk and the read, or
/// whose `comm` we may not read. The value is attacker-controlled
/// (`PR_SET_NAME`): escape it before it reaches a log line.
pub(super) fn read_comm(proc_root: &Path, pid: u32) -> Option<String> {
    std::fs::read_to_string(proc_root.join(pid.to_string()).join("comm"))
        .ok()
        .map(|s| s.trim_end().to_string())
}

/// Best-effort read of `/proc/<pid>/comm` for a sample of pids, for the
/// EACCES-storm diagnostic. Failures (ENOENT for a process that exited)
/// are skipped. Called only when the gate fires.
fn read_comms(proc_root: &Path, pids: &[u32]) -> Vec<String> {
    pids.iter()
        .filter_map(|&pid| read_comm(proc_root, pid))
        .collect()
}

/// Walk `proc_root` (typically `/proc`) and classify whether any
/// external process holds an fd whose symlink target's basename equals
/// `device_basename`. Pure — returns a [`WalkOutcome`]; the caller fires
/// diagnostics. The walk short-circuits on the first match.
///
/// * Top-level `read_dir(proc_root)` failure → [`WalkOutcome::Unreadable`].
/// * A readable pid holding the fd → [`WalkOutcome::External`].
/// * No holder, all candidates readable → [`WalkOutcome::CleanAbsent`].
/// * No holder but ≥1 `/proc/<pid>/fd` returned `EACCES` →
///   [`WalkOutcome::UncertainAbsent`] (the multi-user / sandboxed blind
///   spot where an unprivileged fluxframe cannot see the consumer).
/// * Per-pid `ENOENT`/other I/O and `read_link` failures skip silently.
pub(super) fn count_external_consumers(
    proc_root: &Path,
    device_basename: &OsStr,
    my_pid: u32,
) -> WalkOutcome {
    let entries = match std::fs::read_dir(proc_root) {
        Ok(it) => it,
        Err(e) => return WalkOutcome::Unreadable(e.kind()),
    };

    let mut eacces_count: u32 = 0;
    let mut eacces_pids: Vec<u32> = Vec::new();

    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name_str) = name.to_str() else {
            continue;
        };
        let Ok(pid) = name_str.parse::<u32>() else {
            // Non-numeric `/proc` entries (`self`, `cpuinfo`, …).
            continue;
        };
        if pid == my_pid {
            continue;
        }

        let fd_dir = entry.path().join("fd");
        // EACCES (root or other-user pid) is counted so we can surface
        // the "candidate unreadable" blind spot. ENOENT (process exited
        // mid-scan) and any other I/O error skip silently — steady-state
        // expected on a multi-user system.
        let fd_entries = match std::fs::read_dir(&fd_dir) {
            Ok(it) => it,
            Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
                eacces_count = eacces_count.saturating_add(1);
                if eacces_pids.len() < EACCES_PID_SAMPLE {
                    eacces_pids.push(pid);
                }
                continue;
            }
            Err(_) => continue,
        };

        for fd in fd_entries.flatten() {
            let Ok(link) = std::fs::read_link(fd.path()) else {
                continue;
            };
            if link.file_name() == Some(device_basename) {
                // One matching fd settles it — no need to scan further.
                return WalkOutcome::External { pid };
            }
        }
    }

    if eacces_count > 0 {
        WalkOutcome::UncertainAbsent {
            eacces_count,
            pids: eacces_pids,
        }
    } else {
        WalkOutcome::CleanAbsent
    }
}

// `pub(super)` so [`super::resync`]'s tests can reuse the `/proc`
// fixture and the context builder rather than growing a second copy of
// each.
#[cfg(test)]
pub(super) mod tests {
    use super::*;
    use std::fs;
    use std::os::unix::fs::{PermissionsExt, symlink};
    use std::time::Instant;

    use super::super::resync::fixtures::{FakeProbe, probe_ok};

    /// Scripted [`UsageSource`] standing in for a real v4l2loopback
    /// subscription, which needs a live device fd no unit test has.
    ///
    /// Yields each scripted reading once. When the script runs out it
    /// flips the detector's `stopped` flag and reports "nothing new", so
    /// the loop exits deterministically after consuming exactly the
    /// script — no sleeps, no timer to race — and the test can assert on
    /// the last published status and the resulting counters.
    struct FakeUsage<'a> {
        script: std::collections::VecDeque<io::Result<Option<ClientUsage>>>,
        stopped: &'a AtomicBool,
    }

    impl<'a> FakeUsage<'a> {
        fn new(script: Vec<io::Result<Option<ClientUsage>>>, stopped: &'a AtomicBool) -> Self {
            Self {
                script: script.into(),
                stopped,
            }
        }
    }

    impl UsageSource for FakeUsage<'_> {
        fn wait(&mut self, _timeout_ms: i32) -> io::Result<Option<ClientUsage>> {
            let Some(reading) = self.script.pop_front() else {
                self.stopped.store(true, Ordering::Release);
                return Ok(None);
            };
            reading
        }
    }

    /// Build a scripted reading with the given client count.
    #[expect(
        clippy::unnecessary_wraps,
        reason = "the Result/Option wrapper is the point: scripts mix readings with \
                  Ok(None) timeouts and Err subscription deaths"
    )]
    fn usage(count: u32) -> io::Result<Option<ClientUsage>> {
        Ok(Some(ClientUsage { count }))
    }

    /// What one scripted client-usage run produced: the last published
    /// status, the loop's own result, and the metrics snapshot. The
    /// counters matter as much as the status — `set_consumer_status` is
    /// documented as "call only on an actual change", so
    /// `consumer_transitions_total` is what pins de-duplication.
    struct ClientUsageRun {
        last_status: Option<ConsumerStatus>,
        result: io::Result<()>,
        counters: fluxframe_core::CounterValues,
    }

    /// Run the client-usage loop against a scripted source, with the
    /// resync path disabled.
    fn drive_client_usage(script: Vec<io::Result<Option<ClientUsage>>>) -> ClientUsageRun {
        drive_client_usage_with(
            script,
            &FakeProbe::silent(),
            ResyncSchedule::Off,
            Path::new("/proc"),
        )
    }

    /// Run the client-usage loop with the resync path enabled on every
    /// iteration, against a `/proc` that contains nothing.
    fn drive_with_resync(
        script: Vec<io::Result<Option<ClientUsage>>>,
        probe: &FakeProbe,
    ) -> ClientUsageRun {
        let empty_proc = tempfile::tempdir().expect("tempdir");
        drive_client_usage_with(
            script,
            probe,
            ResyncSchedule::EveryIterations(1),
            empty_proc.path(),
        )
    }

    /// Run the client-usage loop against a scripted source until the
    /// script is exhausted, then stop it.
    fn drive_client_usage_with(
        script: Vec<io::Result<Option<ClientUsage>>>,
        probe: &FakeProbe,
        schedule: ResyncSchedule,
        proc_root: &Path,
    ) -> ClientUsageRun {
        let running = AtomicBool::new(true);
        let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
        // `FakeUsage` sets this once the script is drained, so the loop
        // exits deterministically after consuming exactly the script.
        let stopped = AtomicBool::new(false);
        let counters = Counters::new();
        let device_basename = OsString::from("video10");
        #[cfg(test)]
        let activations = AtomicU64::new(0);
        let ctx = DetectorContext {
            proc_root,
            stale_balance_after: Duration::from_secs(3600),
            teardown_grace: Duration::from_secs(5),
            my_pid: 9999,
            running: &running,
            status: &status,
            stopped: &stopped,
            restat_interval_polls: RESTAT_INTERVAL_POLLS,
            device_basename: &device_basename,
            counters: &counters,
            #[cfg(test)]
            inotify_activations: &activations,
        };
        let mut log_once = LogOnce::armed();
        let mut last_status: Option<ConsumerStatus> = None;
        let mut presence = ConsumerPresence::default();
        let mut state = DetectorState {
            log_once: &mut log_once,
            last_status: &mut last_status,
            presence: &mut presence,
        };

        let mut source = FakeUsage::new(script, &stopped);
        let result = run_detector_client_usage(&mut source, probe, schedule, &ctx, &mut state);
        ClientUsageRun {
            last_status,
            result,
            counters: counters.snapshot(),
        }
    }

    #[test]
    fn client_usage_zero_means_absent() {
        let run = drive_client_usage(vec![usage(0)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Absent));
        assert_eq!(run.counters.consumer_clients, 0);
    }

    #[test]
    fn client_usage_nonzero_means_present() {
        let run = drive_client_usage(vec![usage(1)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_clients, 1);
    }

    #[test]
    fn client_usage_counts_above_one_still_mean_present() {
        // v4l2loopback 0.15 reports 0/1, but the field is a `count` and
        // a future driver may report a real client count.
        let run = drive_client_usage(vec![usage(3)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(
            run.counters.consumer_clients, 3,
            "the gauge carries the raw count, not the boolean"
        );
    }

    #[test]
    fn client_usage_tracks_transitions_in_order() {
        // Unknown → Present → (repeat, no-op) → Absent → Present.
        // The transition counter is what distinguishes "processed every
        // reading in order" from "only looked at the last one": the end
        // status alone is identical for `[1]` and `[1, 1, 0, 1]`.
        let run = drive_client_usage(vec![usage(1), usage(1), usage(0), usage(1)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(
            run.counters.consumer_transitions_total, 3,
            "three actual changes; the repeated `1` must not be published twice"
        );
        assert_eq!(run.counters.consumer_clients, 1);
    }

    #[test]
    fn client_usage_deduplicates_repeated_readings() {
        // Same terminal status as the script above, but only one change:
        // `set_consumer_status` is documented as "call only on an actual
        // change", so a repeat must not bump the transition counter.
        let run = drive_client_usage(vec![usage(1), usage(1)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_transitions_total, 1);
    }

    #[test]
    fn client_usage_timeout_does_not_change_the_verdict() {
        // `Ok(None)` is "nothing new", NOT "no consumer" — conflating
        // the two would tear the camera down on a quiet device.
        let run = drive_client_usage(vec![usage(1), Ok(None), Ok(None)]);
        assert!(run.result.is_ok());
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(
            run.counters.consumer_transitions_total, 1,
            "a timeout is not a transition"
        );
    }

    #[test]
    fn client_usage_stays_unknown_until_the_first_reading() {
        // Before any event the status must remain `Unknown`, which the
        // state machine treats as "present" — idle must never engage on
        // an assumption.
        let run = drive_client_usage(vec![Ok(None)]);
        assert!(run.result.is_ok());
        assert_eq!(
            run.last_status, None,
            "no verdict may be published without evidence"
        );
        assert_eq!(run.counters.consumer_transitions_total, 0);
    }

    #[test]
    fn client_usage_surfaces_a_dead_subscription() {
        // The caller decides whether to fall back; the loop must not
        // swallow the error and spin.
        // ENODEV (19) — what the driver returns once the module is
        // unloaded or the node disappears. Spelled numerically because
        // this crate does not depend on `libc`.
        const ENODEV: i32 = 19;
        let run = drive_client_usage(vec![Err(io::Error::from_raw_os_error(ENODEV))]);
        let err = run.result.expect_err("a dead subscription must surface");
        assert_eq!(err.raw_os_error(), Some(ENODEV));
    }

    #[test]
    fn resync_confirming_the_verdict_is_not_a_correction() {
        // The common case: the event stream is healthy and the re-read
        // agrees. It must leave the verdict alone and, above all, not
        // inflate the correction counter — that counter is the evidence
        // that events are being lost.
        let probe = FakeProbe::new(vec![probe_ok(1)]);
        let run = drive_with_resync(vec![usage(1)], &probe);
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_resync_corrections_total, 0);
        assert!(run.counters.consumer_resync_total > 0);
        assert_eq!(run.counters.consumer_resync_failures_total, 0);
    }

    #[test]
    fn resync_wakes_the_camera_as_soon_as_the_kernel_says_present() {
        // The 13.08/27.08 failure: the verdict is latched at Absent
        // while a client is streaming. One disagreeing read is enough to
        // repair it — an idle camera woken by mistake costs one
        // interval, a sleeping camera under a live client costs the call.
        let probe = FakeProbe::new(vec![probe_ok(1)]);
        let run = drive_with_resync(vec![usage(0)], &probe);
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_resync_corrections_total, 1);
        assert_eq!(run.counters.consumer_clients, 1);
    }

    #[test]
    fn resync_needs_two_agreeing_reads_before_letting_the_camera_go() {
        // The expensive direction: `teardown_secs` after this verdict
        // the camera is released under whoever is using it.
        let probe = FakeProbe::new(vec![probe_ok(0)]);
        let one_tick = drive_with_resync(vec![usage(1), Ok(None)], &probe);
        assert_eq!(
            one_tick.last_status,
            Some(ConsumerStatus::Present),
            "a single disagreeing read must not release the camera"
        );
        assert_eq!(one_tick.counters.consumer_resync_corrections_total, 0);

        // Same script, but the probe keeps saying "nobody" — the second
        // agreeing read is what applies the downgrade.
        let probe = FakeProbe::new(vec![probe_ok(0), probe_ok(0)]);
        let two_ticks = drive_with_resync(vec![usage(1), Ok(None), Ok(None)], &probe);
        assert_eq!(two_ticks.last_status, Some(ConsumerStatus::Absent));
        assert_eq!(two_ticks.counters.consumer_resync_corrections_total, 1);
    }

    #[test]
    fn resync_publishes_the_first_reading_without_calling_it_a_correction() {
        // Nothing published yet: the re-read establishes the verdict.
        // Counting that as a drift correction would put a floor of one
        // on every run and destroy the counter's meaning.
        let probe = FakeProbe::new(vec![probe_ok(1)]);
        let run = drive_with_resync(vec![Ok(None)], &probe);
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_resync_corrections_total, 0);
    }

    #[test]
    fn a_failed_resync_never_latches_the_verdict() {
        // "The kernel did not answer" must not be read as "nobody is
        // streaming" — that would be the original failure, caused by the
        // thing meant to prevent it.
        let probe = FakeProbe::new(vec![Err(io::Error::from(io::ErrorKind::TimedOut))]);
        let run = drive_with_resync(vec![usage(1)], &probe);
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert!(run.counters.consumer_resync_failures_total >= 1);
        assert_eq!(run.counters.consumer_resync_corrections_total, 0);
    }

    #[test]
    fn a_permanent_probe_failure_stops_the_resync_for_the_run() {
        // ENOTTY: the node does not implement the event at all. Retrying
        // every interval would turn the failure counter into a clock.
        const ENOTTY: i32 = 25;
        let probe = FakeProbe::new(vec![
            Err(io::Error::from_raw_os_error(ENOTTY)),
            probe_ok(1),
            probe_ok(1),
        ]);
        let run = drive_with_resync(vec![usage(0), Ok(None), Ok(None), Ok(None)], &probe);
        assert_eq!(probe.calls.get(), 1, "the probe must not be called again");
        assert_eq!(run.counters.consumer_resync_failures_total, 1);
        assert_eq!(run.last_status, Some(ConsumerStatus::Absent));
    }

    #[test]
    fn a_changed_reading_during_the_probe_wins_over_the_drift_check() {
        // The echo drain sees a value that differs from what the probe
        // read: the truth moved between the two, so the newer reading
        // applies and no drift is reported for this tick.
        let probe = FakeProbe::new(vec![probe_ok(0)]);
        let run = drive_with_resync(vec![usage(0), usage(1)], &probe);
        assert_eq!(run.last_status, Some(ConsumerStatus::Present));
        assert_eq!(run.counters.consumer_resync_corrections_total, 0);
    }

    /// Build a detector context over a caller-supplied `/proc` and run
    /// `f` against it. For the tick helpers that are worth testing
    /// without driving the whole loop.
    pub(in crate::idle) fn with_ctx<R>(
        proc_root: &Path,
        counters: &Counters,
        f: impl FnOnce(&DetectorContext<'_>) -> R,
    ) -> R {
        let running = AtomicBool::new(true);
        let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
        let stopped = AtomicBool::new(false);
        let device_basename = OsString::from("video10");
        #[cfg(test)]
        let activations = AtomicU64::new(0);
        let ctx = DetectorContext {
            proc_root,
            stale_balance_after: Duration::from_secs(3600),
            teardown_grace: Duration::from_secs(5),
            my_pid: 9999,
            running: &running,
            status: &status,
            stopped: &stopped,
            restat_interval_polls: RESTAT_INTERVAL_POLLS,
            device_basename: &device_basename,
            counters,
            #[cfg(test)]
            inotify_activations: &activations,
        };
        f(&ctx)
    }

    #[test]
    fn stale_balance_decays_only_after_the_quiet_period() {
        let threshold = Duration::from_secs(5);
        // Balance-backed present, but events are still flowing.
        assert!(!ConsumerPresence::is_stale(
            1,
            Duration::from_secs(4),
            threshold
        ));
        // Quiet for longer than the grace period — the guess has
        // outlived its evidence.
        assert!(ConsumerPresence::is_stale(
            1,
            Duration::from_secs(5),
            threshold
        ));
        // Nothing to decay.
        assert!(!ConsumerPresence::is_stale(
            0,
            Duration::from_secs(600),
            threshold
        ));
    }

    #[test]
    fn decay_zeroes_the_balance_once() {
        let mut presence = ConsumerPresence { open_balance: 4 };
        assert!(presence.decay_if_stale(Duration::from_secs(10), Duration::from_secs(5)));
        assert_eq!(presence.open_balance, 0);
        // Idempotent: nothing left to discard.
        assert!(!presence.decay_if_stale(Duration::from_secs(10), Duration::from_secs(5)));
    }

    #[test]
    fn readable_walk_reanchors_the_balance_downwards() {
        // Regression guard for the latch that kept the camera on: an
        // authoritative walk must reset the balance to exactly 1, not
        // `max(1)`, so accumulated drift cannot survive it.
        let mut presence = ConsumerPresence { open_balance: 9 };
        let (status, reason) = presence.observe(&WalkOutcome::External { pid: 42 }, 0, false);
        assert_eq!(status, ConsumerStatus::Present);
        assert_eq!(reason, PresenceReason::External);
        assert_eq!(presence.open_balance, 1);

        // One close now genuinely clears it.
        let (status, _) = presence.observe(
            &WalkOutcome::UncertainAbsent {
                eacces_count: 400,
                pids: vec![],
            },
            -1,
            false,
        );
        assert_eq!(status, ConsumerStatus::Absent);
    }

    /// Helper: wait for the detector to publish the expected status
    /// or time out. Spin-poll cadence is short enough that the test
    /// stays under a few hundred ms even on slow CI.
    fn wait_for_status(
        status: &Arc<AtomicU8>,
        expected: ConsumerStatus,
        timeout: Duration,
    ) -> bool {
        let deadline = Instant::now() + timeout;
        while Instant::now() < deadline {
            let observed = ConsumerStatus::from_u8(status.load(Ordering::Acquire));
            if observed == expected {
                return true;
            }
            thread::sleep(Duration::from_millis(5));
        }
        false
    }

    /// Synthesise a `/proc/<pid>/fd/<fd>` symlink pointing at
    /// `target`. `target` does not need to exist.
    pub(in crate::idle) fn make_proc_entry(proc_root: &Path, pid: u32, fd: u32, target: &Path) {
        let fd_dir = proc_root.join(pid.to_string()).join("fd");
        fs::create_dir_all(&fd_dir).unwrap();
        symlink(target, fd_dir.join(fd.to_string())).unwrap();
    }

    #[test]
    fn device_path_for_v4l2_loopback() {
        let sink = OutputSink::V4l2Loopback {
            device: PathBuf::from("/dev/video10"),
        };
        let path = device_path(&sink).expect("v4l2 sink yields a device path");
        assert_eq!(path, PathBuf::from("/dev/video10"));
    }

    #[test]
    fn device_path_none_for_non_v4l2_sinks() {
        assert!(device_path(&OutputSink::Fake).is_none());
        assert!(device_path(&OutputSink::Auto).is_none());
        assert!(
            device_path(&OutputSink::Pipewire {
                node_name: Some("fluxframe".into())
            })
            .is_none()
        );
    }

    #[test]
    fn one_external_pid_with_matching_fd_is_external() {
        let dir = tempfile::tempdir().expect("tempdir");
        make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::External { pid: 1234 });
    }

    #[test]
    fn multiple_fds_same_pid_is_external() {
        // Several fds from one pid all pointing at /dev/video10 still
        // classify as a single External holder (the walk short-circuits
        // on the first match).
        let dir = tempfile::tempdir().expect("tempdir");
        make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));
        make_proc_entry(dir.path(), 1234, 4, Path::new("/dev/video10"));
        make_proc_entry(dir.path(), 1234, 5, Path::new("/dev/video10"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::External { pid: 1234 });
    }

    #[test]
    fn self_pid_only_is_clean_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        // fluxframe's own fd should not count as a consumer.
        make_proc_entry(dir.path(), 9999, 3, Path::new("/dev/video10"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::CleanAbsent);
    }

    #[test]
    fn no_matching_fds_is_clean_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        // External pid but holding unrelated fds.
        make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/null"));
        make_proc_entry(dir.path(), 1234, 4, Path::new("/dev/video11"));
        make_proc_entry(dir.path(), 5678, 3, Path::new("/dev/zero"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::CleanAbsent);
    }

    /// A pid with a chmod-0o000 fd dir is unreadable (EACCES) but a
    /// readable pid holding a matching fd still settles the walk as
    /// `External` — one found consumer trumps any EACCES noise.
    #[test]
    fn permission_denied_pid_skipped_when_consumer_found() {
        let dir = tempfile::tempdir().expect("tempdir");
        // Unreadable pid (simulated root-owned process).
        let unreadable_fd_dir = dir.path().join("1234").join("fd");
        fs::create_dir_all(&unreadable_fd_dir).unwrap();
        // Restore permissions before the tempdir drops — some
        // platforms refuse to remove a 0o000 directory.
        let _restore = ScopeGuard::new({
            let p = unreadable_fd_dir.clone();
            move || {
                let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
            }
        });
        fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();

        // External pid that IS readable and matches.
        make_proc_entry(dir.path(), 5678, 3, Path::new("/dev/video10"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::External { pid: 5678 });
    }

    /// Every candidate `/proc/<pid>/fd` unreadable and no match →
    /// `UncertainAbsent` carrying the full EACCES count (the sampled
    /// pids are a bounded sample; assert only the count to stay robust
    /// against `read_dir` ordering).
    #[test]
    fn all_eacces_no_match_is_uncertain_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let unreadable_fd_dir = dir.path().join("1234").join("fd");
        fs::create_dir_all(&unreadable_fd_dir).unwrap();
        let _restore = ScopeGuard::new({
            let p = unreadable_fd_dir.clone();
            move || {
                let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
            }
        });
        fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert!(
            matches!(
                walk,
                WalkOutcome::UncertainAbsent {
                    eacces_count: 1,
                    ..
                }
            ),
            "expected UncertainAbsent with one EACCES, got {walk:?}"
        );
    }

    #[test]
    fn unreadable_proc_root_is_unreadable() {
        let walk =
            count_external_consumers(Path::new("/no/such/proc/path"), OsStr::new("video10"), 9999);
        assert!(matches!(walk, WalkOutcome::Unreadable(_)), "got {walk:?}");
    }

    #[test]
    fn mixed_self_plus_external_is_external() {
        let dir = tempfile::tempdir().expect("tempdir");
        make_proc_entry(dir.path(), 9999, 3, Path::new("/dev/video10"));
        make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));

        let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
        assert_eq!(walk, WalkOutcome::External { pid: 1234 });
    }

    // --- ConsumerPresence::observe pure matrix -------------------------

    fn uncertain(n: u32) -> WalkOutcome {
        WalkOutcome::UncertainAbsent {
            eacces_count: n,
            pids: Vec::new(),
        }
    }

    #[test]
    fn observe_external_is_present_and_floors_balance() {
        let mut p = ConsumerPresence::default();
        // Even with a stale negative delta, External floors to >=1.
        let (s, r) = p.observe(&WalkOutcome::External { pid: 1 }, -5, false);
        assert_eq!((s, r), (ConsumerStatus::Present, PresenceReason::External));
        assert!(p.open_balance >= 1);
    }

    #[test]
    fn observe_clean_absent_zeroes_balance() {
        let mut p = ConsumerPresence { open_balance: 4 };
        let (s, r) = p.observe(&WalkOutcome::CleanAbsent, 0, false);
        assert_eq!(
            (s, r),
            (ConsumerStatus::Absent, PresenceReason::CleanAbsent)
        );
        assert_eq!(p.open_balance, 0);
    }

    #[test]
    fn observe_unreadable_is_failopen_and_keeps_counting() {
        let mut p = ConsumerPresence { open_balance: 1 };
        let (s, r) = p.observe(&WalkOutcome::Unreadable(io::ErrorKind::NotFound), 1, false);
        assert_eq!((s, r), (ConsumerStatus::Unknown, PresenceReason::FailOpen));
        // Balance still folds the delta (valid regardless of /proc).
        assert_eq!(p.open_balance, 2);
    }

    #[test]
    fn observe_uncertain_wakes_on_positive_balance() {
        let mut p = ConsumerPresence::default();
        // Open arrives (net +1) but the walk can't attribute it → wake.
        let (s, r) = p.observe(&uncertain(1), 1, false);
        assert_eq!(
            (s, r),
            (ConsumerStatus::Present, PresenceReason::UnattributableWake)
        );
    }

    #[test]
    fn observe_uncertain_probe_open_then_close_stays_absent() {
        let mut p = ConsumerPresence::default();
        // A brief probe: OPEN then CLOSE in one batch → net 0 → Absent.
        let (s, r) = p.observe(&uncertain(1), 0, false);
        assert_eq!(
            (s, r),
            (ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
        );
    }

    #[test]
    fn observe_uncertain_aux_fd_close_keeps_present() {
        let mut p = ConsumerPresence { open_balance: 2 };
        // One of several held fds closes (net -1); balance 1 > 0 → still Present.
        let (s, r) = p.observe(&uncertain(1), -1, false);
        assert_eq!(
            (s, r),
            (ConsumerStatus::Present, PresenceReason::UnattributableWake)
        );
        assert_eq!(p.open_balance, 1);
    }

    #[test]
    fn observe_uncertain_steady_no_open_is_absent() {
        let mut p = ConsumerPresence::default();
        // Steady EACCES noise with no open events → stays Absent.
        let (s, r) = p.observe(&uncertain(3), 0, false);
        assert_eq!(
            (s, r),
            (ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
        );
    }

    #[test]
    fn observe_overflow_resets_balance_before_deciding() {
        let mut p = ConsumerPresence { open_balance: 5 };
        // Overflow drops the balance to 0 before the walk decides; an
        // uncertain walk with the balance reset → Absent.
        let (s, _) = p.observe(&uncertain(1), 3, true);
        assert_eq!(s, ConsumerStatus::Absent);
        assert_eq!(p.open_balance, 0);
    }

    #[test]
    fn observe_balance_clamps_at_zero() {
        let mut p = ConsumerPresence::default();
        // Unmatched close (pre-watch fd) must not drive balance negative.
        let (_s, _r) = p.observe(&uncertain(1), -3, false);
        assert_eq!(p.open_balance, 0);
    }

    // --- read_comms + gate wiring --------------------------------------

    #[test]
    fn read_comms_reads_present_and_skips_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let pid_dir = dir.path().join("1234");
        fs::create_dir_all(&pid_dir).unwrap();
        fs::write(pid_dir.join("comm"), "chrome\n").unwrap();
        // 1234 has a comm (trailing newline trimmed); 5678 has none → skipped.
        assert_eq!(
            read_comms(dir.path(), &[1234, 5678]),
            vec!["chrome".to_string()]
        );
    }

    /// Run one `walk_observe_publish` against `proc_root` and report which
    /// [`LogOnce`] gates remain armed afterwards — the seam that maps a
    /// [`WalkOutcome`] to its diagnostic gate now that the walk itself is
    /// gate-free.
    fn gates_after_one_walk(proc_root: &Path) -> (bool, bool) {
        let running = AtomicBool::new(true);
        let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
        let stopped = AtomicBool::new(false);
        let counters = Counters::new();
        let device_basename = OsString::from("video10");
        let activations = AtomicU64::new(0);
        let ctx = DetectorContext {
            proc_root,
            stale_balance_after: Duration::from_secs(3600),
            teardown_grace: Duration::from_secs(5),
            my_pid: 9999,
            running: &running,
            status: &status,
            stopped: &stopped,
            restat_interval_polls: RESTAT_INTERVAL_POLLS,
            device_basename: &device_basename,
            counters: &counters,
            inotify_activations: &activations,
        };
        let mut log_once = LogOnce::armed();
        let mut last_status = None;
        let mut presence = ConsumerPresence::default();
        let mut state = DetectorState {
            log_once: &mut log_once,
            last_status: &mut last_status,
            presence: &mut presence,
        };
        walk_observe_publish(&ctx, &mut state, 0, false);
        (
            log_once.scan_failed.is_armed(),
            log_once.eacces_storm.is_armed(),
        )
    }

    #[test]
    fn walk_observe_publish_fires_scan_failed_on_unreadable() {
        // Unreadable /proc root → Unreadable → scan_failed consumed,
        // eacces_storm untouched.
        let (scan_armed, eacces_armed) = gates_after_one_walk(Path::new("/no/such/proc/path"));
        assert!(!scan_armed, "Unreadable walk must consume scan_failed");
        assert!(eacces_armed, "Unreadable walk must not touch eacces_storm");
    }

    #[test]
    fn walk_observe_publish_fires_eacces_storm_on_uncertain() {
        let dir = tempfile::tempdir().expect("tempdir");
        let unreadable_fd_dir = dir.path().join("1234").join("fd");
        fs::create_dir_all(&unreadable_fd_dir).unwrap();
        let _restore = ScopeGuard::new({
            let p = unreadable_fd_dir.clone();
            move || {
                let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
            }
        });
        fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();
        // All-EACCES → UncertainAbsent → eacces_storm consumed, scan_failed untouched.
        let (scan_armed, eacces_armed) = gates_after_one_walk(dir.path());
        assert!(
            scan_armed,
            "UncertainAbsent walk must not touch scan_failed"
        );
        assert!(
            !eacces_armed,
            "UncertainAbsent walk must consume eacces_storm"
        );
    }

    #[test]
    fn walk_observe_publish_fires_no_gate_on_clean_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/null"));
        // Fully-readable, no match → CleanAbsent → neither gate fires.
        let (scan_armed, eacces_armed) = gates_after_one_walk(dir.path());
        assert!(
            scan_armed && eacces_armed,
            "CleanAbsent must not fire any gate"
        );
    }

    /// Walk the full transition cycle expected at runtime: absent →
    /// add an external consumer → drop it → make the proc root
    /// disappear → put it back. Verifies the **polling fallback**
    /// path picks up each transition within the poll window — the
    /// device path points at a non-existent node so the inotify
    /// path fails at `add_watch` and the dispatcher falls back to
    /// polling. The inotify path itself is exercised by
    /// `inotify_path_fires_on_external_open` below.
    #[test]
    fn detector_cycles_through_states_via_fake_proc_polling_fallback() {
        let dir = tempfile::tempdir().expect("tempdir");
        let proc_root = dir.path().to_path_buf();
        // Synthesise an inert non-numeric entry so the directory is
        // non-empty from the start (read_dir on an empty tempdir is
        // still legal but the test cycles below mutate it).
        fs::write(proc_root.join("self"), "").unwrap();

        let running = Arc::new(AtomicBool::new(true));
        // Non-existent device path forces inotify::watches().add to
        // fail with ENOENT → dispatcher falls back to polling. The
        // per-detector activations counter is checked at end-of-test
        // to confirm the inotify path never activated.
        let activations = Arc::new(AtomicU64::new(0));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: PathBuf::from("/dev/this-device-does-not-exist"),
                my_pid: 9999,
                poll_interval: Duration::from_millis(20),
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: proc_root.clone(),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                inotify_activations: Arc::clone(&activations),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );
        let status = detector.status_handle();

        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "empty proc must surface as Absent"
        );

        // Attach an external consumer. Basename must match the
        // device_path basename used at detector spawn.
        make_proc_entry(
            &proc_root,
            1234,
            3,
            Path::new("/dev/this-device-does-not-exist"),
        );
        assert!(
            wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
            "external pid attaching must surface as Present"
        );

        // Detach.
        fs::remove_dir_all(proc_root.join("1234")).unwrap();
        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "external pid detaching must surface as Absent"
        );

        assert_eq!(
            activations.load(Ordering::Acquire),
            0,
            "inotify path must not activate when add_watch fails"
        );

        running.store(false, Ordering::Release);
        drop(detector);
    }

    /// Shutdown latency is bounded by `SHUTDOWN_POLL_GRANULARITY`
    /// (~50 ms), NOT by `poll_interval`. The 500 ms tolerance leaves
    /// CI plenty of slack to avoid flakiness.
    #[test]
    fn shutdown_completes_quickly_even_with_long_poll_interval() {
        let dir = tempfile::tempdir().expect("tempdir");
        let running = Arc::new(AtomicBool::new(true));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: PathBuf::from("/dev/video10"),
                my_pid: 9999,
                poll_interval: Duration::from_secs(2), // long poll
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: dir.path().to_path_buf(),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );

        // Wait briefly to ensure the detector entered its sleep loop.
        thread::sleep(Duration::from_millis(100));

        let start = Instant::now();
        running.store(false, Ordering::Release);
        drop(detector); // Drop joins under the new pattern.
        let elapsed = start.elapsed();

        assert!(
            elapsed < Duration::from_millis(500),
            "shutdown took {elapsed:?} — expected < 500 ms"
        );
    }

    /// One-shot gate mechanics used by both diagnostic gates: `fire()`
    /// returns `true` exactly once per `armed()`/`rearm()` cycle, then
    /// `false`, and `rearm()` restores it. The diagnostics that consume
    /// these gates now live in [`walk_observe_publish`] rather than the
    /// walk; the gate contract itself is what these tests pin.
    #[test]
    fn log_once_gates_fire_once_and_rearm_in_lockstep() {
        let mut log = LogOnce::armed();
        assert!(log.scan_failed.is_armed());
        assert!(log.eacces_storm.is_armed());

        assert!(log.scan_failed.fire(), "first fire returns true");
        assert!(!log.scan_failed.is_armed(), "gate consumed after fire");
        assert!(!log.scan_failed.fire(), "second fire returns false");

        // eacces_storm is independent until rearm.
        assert!(log.eacces_storm.is_armed());
        assert!(log.eacces_storm.fire());
        assert!(!log.eacces_storm.is_armed());

        // rearm restores every gate in lockstep.
        log.rearm();
        assert!(log.scan_failed.is_armed(), "rearm restores scan_failed");
        assert!(log.eacces_storm.is_armed(), "rearm restores eacces_storm");
        assert!(log.scan_failed.fire(), "re-armed gate is consumable again");
    }

    /// Pragmatic survival test for the `run_detector` rearm boundary:
    /// drive the worker at the most aggressive cadence
    /// (`restat_interval_polls = 1`, so EVERY poll rearms) against a
    /// non-existent proc_root that keeps producing the `scan_failed`
    /// diagnostic, and verify the thread doesn't deadlock, panic, or
    /// burn CPU into oblivion.
    ///
    /// Note: this test validates that the rearm code path is
    /// exercised at the per-poll boundary AT MINIMUM. A finer
    /// assertion (e.g. counting rearm invocations) would require
    /// wiring a test-only Arc<AtomicU32> into `LogOnce`, which is
    /// disproportionate plumbing for one assertion.
    #[test]
    fn run_detector_rearms_log_flag_at_restat_boundary() {
        let running = Arc::new(AtomicBool::new(true));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: PathBuf::from("/dev/video10"),
                my_pid: 9999,
                poll_interval: Duration::from_millis(20),
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: PathBuf::from("/no/such/proc/path"),
                restat_interval_polls: 1, // rearm on EVERY poll
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );
        let status = detector.status_handle();

        // Worker keeps producing Unknown because the proc_root is
        // unreadable; we just need the thread to survive the
        // aggressive cadence without crashing.
        assert!(
            wait_for_status(&status, ConsumerStatus::Unknown, Duration::from_millis(300)),
            "missing proc root must surface as Unknown"
        );

        // Let the loop iterate several times so the rearm path runs
        // many times in a row. If rearm panicked or deadlocked, the
        // shutdown below would hang.
        thread::sleep(Duration::from_millis(200));
        assert_eq!(
            ConsumerStatus::from_u8(status.load(Ordering::Acquire)),
            ConsumerStatus::Unknown,
            "worker must keep publishing Unknown across rearm cycles"
        );

        running.store(false, Ordering::Release);
        drop(detector);
    }

    /// Exercise the inotify event-driven path against a real file:
    /// open the watched node from the test thread; the detector's
    /// inotify watch fires `IN_OPEN`, the loop walks the fake `/proc`,
    /// finds the synthesised external entry, and publishes `Present`.
    ///
    /// Uses `NamedTempFile` as the device path because (a) it exists
    /// on disk so `inotify::watches().add` succeeds; (b) the test
    /// thread controls open/close cadence; (c) the basename is
    /// unique per run, avoiding cross-test interference.
    ///
    /// The fake `/proc/<pid>/fd/<fd>` symlink targets the same
    /// `NamedTempFile::path()`, so `count_external_consumers`
    /// compares matching basenames and the synthesised "consumer"
    /// counts.
    #[test]
    fn inotify_path_fires_on_external_open() {
        let proc_dir = tempfile::tempdir().expect("proc tempdir");
        let proc_root = proc_dir.path().to_path_buf();
        // Inert non-numeric entry so the dir scan starts non-empty.
        fs::write(proc_root.join("self"), "").unwrap();

        // The device path is a real file we control. NamedTempFile
        // creates it on disk; inotify::watches().add accepts any
        // regular file as a watch target.
        let device = tempfile::NamedTempFile::new().expect("device tempfile");
        let device_path = device.path().to_path_buf();

        // Pre-arm the synthesised consumer so the post-event walk
        // finds it. The detector won't walk before the first open
        // event arrives (baseline is the only walk before that, and
        // baseline = no /proc/1234 entry yet).
        make_proc_entry(&proc_root, 1234, 3, &device_path);

        let running = Arc::new(AtomicBool::new(true));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: device_path.clone(),
                my_pid: 9999,
                poll_interval: Duration::from_millis(20),
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: proc_root.clone(),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );
        let status = detector.status_handle();
        // Per-detector activation counter — no global, no cross-test race.
        let activations = detector.inotify_activations_handle();

        // Baseline walk runs immediately after `add_watch` succeeds.
        // Since the /proc entry already points at our device_path,
        // baseline must surface as Present.
        assert!(
            wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
            "baseline walk must surface synthesised consumer as Present"
        );
        assert!(
            activations.load(Ordering::Acquire) > 0,
            "inotify path must have activated (init + add_watch succeeded)"
        );

        // Detach the synthesised consumer — but the detector is
        // event-driven now, so it only re-walks on the NEXT open
        // event. Touch the file to trigger one.
        fs::remove_dir_all(proc_root.join("1234")).unwrap();
        {
            // Open + immediate close → fires IN_OPEN + IN_CLOSE_*.
            let _f = std::fs::File::open(&device_path).expect("open device");
        }
        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "event-driven walk must observe the consumer disappearing"
        );

        // Re-attach and re-trigger.
        make_proc_entry(&proc_root, 5678, 3, &device_path);
        {
            let _f = std::fs::File::open(&device_path).expect("open device again");
        }
        assert!(
            wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
            "event-driven walk must observe the consumer re-attaching"
        );

        running.store(false, Ordering::Release);
        drop(detector);
    }

    /// The core net-count wake: a consumer whose `/proc/<pid>/fd` is
    /// unreadable (EACCES — sandboxed browser) is invisible to the walk
    /// (`UncertainAbsent`), but a *held* `IN_OPEN` drives the open
    /// balance positive and must wake the detector to `Present`;
    /// closing it must return to `Absent`. Reproduces the incident's
    /// root cause without a real camera or Chrome by chmod-0'ing the
    /// fake `/proc/<pid>/fd` dir and holding the watched file open
    /// across an inotify drain.
    #[test]
    fn unattributable_held_open_wakes_via_net_count() {
        let proc_dir = tempfile::tempdir().expect("proc tempdir");
        let proc_root = proc_dir.path().to_path_buf();
        // One unreadable pid dir → every walk returns UncertainAbsent.
        let unreadable_fd_dir = proc_root.join("1234").join("fd");
        fs::create_dir_all(&unreadable_fd_dir).unwrap();
        let _restore = ScopeGuard::new({
            let p = unreadable_fd_dir.clone();
            move || {
                let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
            }
        });
        fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();

        let device = tempfile::NamedTempFile::new().expect("device tempfile");
        let device_path = device.path().to_path_buf();

        let running = Arc::new(AtomicBool::new(true));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: device_path.clone(),
                my_pid: 9999,
                poll_interval: Duration::from_millis(20),
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: proc_root.clone(),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );
        let status = detector.status_handle();

        // Baseline: UncertainAbsent with a zero open balance → Absent.
        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "uncertain-absent with zero balance must read Absent"
        );

        // Hold the device open across a drain: IN_OPEN (+1), no matching
        // close yet → balance 1 → Present despite the EACCES walk.
        let held = std::fs::File::open(&device_path).expect("open device");
        assert!(
            wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
            "held open on an unattributable consumer must wake to Present"
        );

        // Close → IN_CLOSE_NOWRITE (−1) → balance 0 → Absent.
        drop(held);
        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "closing the held fd must return to Absent"
        );

        running.store(false, Ordering::Release);
        drop(detector);
    }

    /// `EventMask::IGNORED` is the kernel's signal that the watched
    /// file went away (deleted, fs unmounted). The detector surfaces
    /// it as an `io::Error` from `run_detector_inotify`, and the
    /// dispatcher falls back to polling. This test verifies the
    /// fallback by deleting the watched file mid-run and confirming
    /// the detector keeps producing a status (polling fallback
    /// against the deleted-then-recreated /proc/<pid>/fd entry).
    ///
    /// Realistic operational scenario: `modprobe -r v4l2loopback`
    /// while fluxframe is running.
    #[test]
    fn inotify_watch_removed_falls_back_to_polling() {
        let proc_dir = tempfile::tempdir().expect("proc tempdir");
        let proc_root = proc_dir.path().to_path_buf();
        fs::write(proc_root.join("self"), "").unwrap();

        let device = tempfile::NamedTempFile::new().expect("device tempfile");
        let device_path = device.path().to_path_buf();

        make_proc_entry(&proc_root, 1234, 3, &device_path);

        let running = Arc::new(AtomicBool::new(true));
        let detector = ConsumerDetector::spawn_with_knobs(
            DetectorParams {
                device_path: device_path.clone(),
                my_pid: 9999,
                poll_interval: Duration::from_millis(20),
                mode: IdlePresenceSource::Inotify,
                stale_balance_after: Duration::from_secs(3600),
                teardown_grace: Duration::from_secs(5),
                // The heuristic paths never resync — see the field docs.
                resync_interval: None,
            },
            DetectorTestKnobs {
                proc_root: proc_root.clone(),
                restat_interval_polls: RESTAT_INTERVAL_POLLS,
                inotify_activations: Arc::new(AtomicU64::new(0)),
            },
            Arc::clone(&running),
            Arc::new(Counters::new()),
            None,
        );
        let status = detector.status_handle();

        // Baseline must reach Present via inotify path.
        assert!(
            wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
            "baseline walk must surface synthesised consumer as Present"
        );

        // Delete the device file. The kernel fires IN_IGNORED on
        // the watch; run_detector_inotify returns Err; dispatcher
        // falls back to polling. After fallback, status should
        // still track /proc mutations.
        drop(device); // tempfile is unlink-on-drop
        // Give the inotify path a window to observe IN_IGNORED and
        // the dispatcher to enter the polling fallback.
        thread::sleep(Duration::from_millis(100));

        // Detach the consumer in /proc. Polling should observe.
        fs::remove_dir_all(proc_root.join("1234")).unwrap();
        assert!(
            wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
            "polling fallback must observe consumer detach after IN_IGNORED"
        );

        running.store(false, Ordering::Release);
        drop(detector);
    }

    /// Tiny RAII guard so the EACCES tests can restore a 0o000 dir's
    /// permissions before the tempdir drops (some platforms refuse to
    /// remove a 0o000 directory). Pulled in here rather than as a dep —
    /// `defer-rs` / `scopeguard` would be overkill for one call site.
    struct ScopeGuard<F: FnMut()> {
        f: Option<F>,
    }

    impl<F: FnMut()> ScopeGuard<F> {
        fn new(f: F) -> Self {
            Self { f: Some(f) }
        }
    }

    impl<F: FnMut()> Drop for ScopeGuard<F> {
        fn drop(&mut self) {
            if let Some(mut f) = self.f.take() {
                f();
            }
        }
    }
}