trusty-common 0.70.5

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Real-process tests for `trusty_common::linux_lifecycle` (#11084).
//!
//! Why: the defects this module replaces — a fixed health wait, trusting a
//! signal's return code, signalling an unidentified pid — all pass against
//! mocks. These tests run the module against real processes on a real socket.
//!
//! What: this test binary is also its own fixture. Run with the
//! `tc-lc-role=daemon` argument, `child_entry` becomes a small daemon that
//! binds the Unix socket named by `TC_LC_SOCKET` (its instance key, #11098)
//! and reacts to SIGTERM per its `mode=`; with
//! `tc-lc-role=runner` it becomes a separate process that calls `start`.
//! Each test hard-links this binary into a temp install dir under the names
//! `lc-daemon` and `lc-other`, so `/proc/<pid>/exe` names the install-dir
//! path. A process that survives SIGKILL cannot be made unprivileged, so the
//! survivor tests run a real SIGTERM-ignoring process and drop SIGKILL through
//! the module's `SignalDelivery` seam.
//!
//! No fixture outlives its test (#11084): every daemon role exits on its own
//! once its socket's directory is gone or `FIXTURE_LIFETIME` passes, and a
//! test arms its cleanup from the pids the fixtures write to their marker,
//! never from the result of the call under test.
//!
//! Test: this file. Linux only, and the module needs the `uds` feature.
#![cfg(all(target_os = "linux", feature = "uds"))]

use std::ffi::CString;
use std::fs::{self, File, OpenOptions};
use std::io::Write as _;
use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::fs::PermissionsExt as _;
use std::os::unix::net::{UnixListener, UnixStream};
use std::os::unix::process::ExitStatusExt as _;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use trusty_common::linux_lifecycle::{
    DaemonDescriptor, KernelDelivery, LifecycleError, PinnedProcess, ProcessTable, Signal,
    SignalDelivery, StopOutcome, StoppedSignal, restart, restart_pid, restart_pid_with,
    restart_with, restart_with_table, start, start_with_table, stop, stop_pid, stop_pid_with,
    stop_with, stop_with_table,
};

const ROLE_DAEMON: &str = "tc-lc-role=daemon";
const ROLE_RUNNER: &str = "tc-lc-role=runner";
/// #11098: a stdio bridge stand-in — the same executable as the daemon, run
/// as `daemon_main` but without the daemon's `ROLE_DAEMON` argument.
const ROLE_BRIDGE: &str = "tc-lc-role=bridge";
/// #11098: the fixture's instance key. A fixture daemon reads its socket from
/// this variable when its argv names none, as a real daemon derives its socket
/// from its data-dir variable, so two instances can run with identical argv.
const SOCKET_ENV: &str = "TC_LC_SOCKET";
/// #11098: the fixture flag that sets the process name to [`BAD_NAME`].
const BAD_NAME_FLAG: &str = "bad-name";
/// A `comm` that is not UTF-8; `/proc/<pid>/status` prints it unescaped.
const BAD_NAME: &[u8] = b"lc-\xff\xfe-bad";
const DAEMON: &str = "lc-daemon";
const OTHER: &str = "lc-other";
/// Longer than `tm restart`'s 3 s health wait, which AC1 rules out.
const LINGER_MS: u64 = 3_500;
const SERVE_BOUND: Duration = Duration::from_secs(20);
/// Hard limit on any fixture's life, whatever its test does (#11084).
const FIXTURE_LIFETIME: Duration = Duration::from_secs(120);
const WATCH_TICK: Duration = Duration::from_millis(100);
/// How long a wrong implementation's spawned child gets to show up.
const SPAWN_SETTLE: Duration = Duration::from_millis(500);

// ─── Fixture roles ──────────────────────────────────────────────────────────

/// The fixture entry point; a no-op when run as an ordinary test.
#[test]
fn child_entry() {
    let args: Vec<String> = std::env::args().collect();
    if args.iter().any(|a| a == ROLE_DAEMON || a == ROLE_BRIDGE) {
        daemon_main(&args);
    }
    if args.iter().any(|a| a == ROLE_RUNNER) {
        runner_main(&args);
    }
}

fn arg<'a>(args: &'a [String], key: &str) -> Option<&'a str> {
    args.iter()
        .find_map(|a| a.strip_prefix(key)?.strip_prefix('='))
}

static TERM: AtomicBool = AtomicBool::new(false);

extern "C" fn on_term(_: libc::c_int) {
    TERM.store(true, Ordering::SeqCst);
}

fn append(path: &str, line: &str) {
    let mut f = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .expect("open marker");
    writeln!(f, "{line}").expect("write marker");
}

/// Exit this process once `dir` is gone or `FIXTURE_LIFETIME` has passed.
///
/// Why: a test that panics before its cleanup must not leave a fixture
/// running (#11084); the temp dir is removed as the panic unwinds.
fn arm_watchdog(dir: PathBuf) {
    std::thread::spawn(move || {
        let deadline = Instant::now() + FIXTURE_LIFETIME;
        while Instant::now() < deadline && fs::symlink_metadata(&dir).is_ok() {
            std::thread::sleep(WATCH_TICK);
        }
        std::process::exit(3);
    });
}

/// The watchdog's rule for a forked child, which has no watchdog thread: only
/// async-signal-safe calls (`access`, `nanosleep`, `_exit`).
fn forked_watch(dir: &CString) -> ! {
    let ticks = FIXTURE_LIFETIME.as_millis() / WATCH_TICK.as_millis();
    let tick = libc::timespec {
        tv_sec: 0,
        tv_nsec: WATCH_TICK.as_nanos() as libc::c_long,
    };
    for _ in 0..ticks {
        // SAFETY: a valid C string, and a valid timespec with a null remainder.
        unsafe {
            if libc::access(dir.as_ptr(), libc::F_OK) != 0 {
                break;
            }
            libc::nanosleep(&tick, std::ptr::null_mut());
        }
    }
    // SAFETY: `_exit` is async-signal-safe and never returns.
    unsafe { libc::_exit(3) }
}

/// A daemon stand-in. Modes: `serve` (exit on SIGTERM), `linger` (close the
/// socket on SIGTERM, exit `LINGER_MS` later), `ignore-term`, `never-bind`,
/// `exit-now`, `fork-lock-holder` (on SIGTERM, fork a child that keeps the
/// inherited lock, then exit), and (#11098) `unlink-socket` / `close-socket`
/// (after the bind, unlink the socket file or close the listener, write
/// `unserved` to the marker, and keep running). The `undumpable` flag makes
/// `/proc/<pid>/exe` unreadable to other processes.
fn daemon_main(args: &[String]) -> ! {
    let mode = arg(args, "mode").unwrap_or("serve");
    let socket = arg(args, "socket")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os(SOCKET_ENV).map(PathBuf::from))
        .expect("socket arg or env");
    let watch_dir = socket.parent().expect("socket dir").to_path_buf();
    arm_watchdog(watch_dir.clone());
    if args.iter().any(|a| a == "undumpable") {
        // SAFETY: PR_SET_DUMPABLE takes one integer argument.
        let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) };
        assert_eq!(rc, 0, "prctl(PR_SET_DUMPABLE)");
    }
    if args.iter().any(|a| a == BAD_NAME_FLAG) {
        // `prctl(PR_SET_NAME)` here would name only this test thread; status
        // prints the main thread's `comm`, which this write sets.
        fs::write("/proc/self/comm", BAD_NAME).expect("set comm");
    }
    let marker = arg(args, "marker");
    if let Some(m) = marker {
        append(m, &std::process::id().to_string());
    }
    let _lock = arg(args, "lock").map(|p| {
        let f = File::create(p).expect("create lock");
        f.lock().expect("take lock");
        f
    });
    if mode == "exit-now" {
        std::process::exit(7);
    }
    // SAFETY: installing a handler that only stores to an atomic, or SIG_IGN.
    unsafe {
        if mode == "ignore-term" {
            libc::signal(libc::SIGTERM, libc::SIG_IGN);
        } else {
            libc::signal(libc::SIGTERM, on_term as *const () as libc::sighandler_t);
        }
    }
    if mode == "never-bind" {
        loop {
            if TERM.load(Ordering::SeqCst) {
                std::process::exit(0);
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
    let watch_c = CString::new(watch_dir.as_os_str().as_bytes()).expect("watch dir C string");
    // bind_singleton's shape: `<socket>.lock` is held only while binding, so
    // a module that read it as liveness would see every fixture as stopped.
    let bind_lock = File::create(format!("{}.lock", socket.display())).expect("bind lock");
    bind_lock.lock().expect("take bind lock");
    let _ = fs::remove_file(&socket);
    let listener = UnixListener::bind(&socket).expect("bind fixture socket");
    drop(bind_lock);
    listener.set_nonblocking(true).expect("nonblocking");
    let mut listener = Some(listener);
    if mode == "unlink-socket" || mode == "close-socket" {
        if mode == "unlink-socket" {
            fs::remove_file(&socket).expect("unlink fixture socket");
        } else {
            drop(listener.take());
        }
        if let Some(m) = marker {
            append(m, "unserved");
        }
    }
    loop {
        if TERM.load(Ordering::SeqCst) {
            match mode {
                "linger" => {
                    drop(listener.take());
                    if let Some(m) = marker {
                        append(m, "closed");
                    }
                    std::thread::sleep(Duration::from_millis(LINGER_MS));
                    std::process::exit(0);
                }
                "fork-lock-holder" => {
                    drop(listener.take());
                    let _ = fs::remove_file(&socket);
                    // SAFETY: the forked child runs only `forked_watch`,
                    // which is async-signal-safe.
                    let holder = unsafe { libc::fork() };
                    if holder == 0 {
                        forked_watch(&watch_c);
                    }
                    if let Some(m) = marker {
                        append(m, &format!("holder={holder}"));
                    }
                    std::process::exit(0);
                }
                _ => {
                    let _ = fs::remove_file(&socket);
                    std::process::exit(0);
                }
            }
        }
        if let Some(l) = &listener {
            while let Ok((conn, _)) = l.accept() {
                drop(conn);
            }
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// Make every later `pidfd_open` in this process (and its children) fail with
/// `ENOSYS`, as on a kernel older than 5.3.
///
/// What: a seccomp filter that compares the native syscall number only; the
/// fixture issues native syscalls, so no arch check is needed. Unprivileged,
/// because `PR_SET_NO_NEW_PRIVS` is set first.
fn deny_pidfd_open() {
    let stmt = |code: u32, k: u32| libc::sock_filter {
        code: code as u16,
        jt: 0,
        jf: 0,
        k,
    };
    let filter = [
        // A = seccomp_data.nr (offset 0).
        stmt(libc::BPF_LD | libc::BPF_W | libc::BPF_ABS, 0),
        // nr == pidfd_open ? next : skip one.
        libc::sock_filter {
            code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
            jt: 0,
            jf: 1,
            k: libc::SYS_pidfd_open as u32,
        },
        stmt(
            libc::BPF_RET | libc::BPF_K,
            libc::SECCOMP_RET_ERRNO | libc::ENOSYS as u32,
        ),
        stmt(libc::BPF_RET | libc::BPF_K, libc::SECCOMP_RET_ALLOW),
    ];
    let prog = libc::sock_fprog {
        len: filter.len() as u16,
        filter: filter.as_ptr().cast_mut(),
    };
    // SAFETY: documented prctl forms; `prog` and `filter` outlive the call,
    // and the kernel copies the program.
    unsafe {
        assert_eq!(libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0);
        assert_eq!(
            libc::prctl(
                libc::PR_SET_SECCOMP,
                libc::SECCOMP_MODE_FILTER as libc::c_ulong,
                &raw const prog,
            ),
            0,
            "seccomp filter"
        );
    }
}

/// Pids whose parent is this process, zombies included.
fn children_of_self() -> Vec<u32> {
    let me = std::process::id();
    let Ok(dir) = fs::read_dir("/proc") else {
        return Vec::new();
    };
    dir.flatten()
        .filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok())
        .filter(|&pid| {
            fs::read_to_string(format!("/proc/{pid}/stat"))
                .ok()
                .and_then(|s| {
                    let rest = s.rsplit_once(')')?.1;
                    rest.split_whitespace().nth(1)?.parse::<u32>().ok()
                })
                == Some(me)
        })
        .collect()
}

/// A process other than the test that calls `start`, writes the outcome to
/// `out=`, and exits. With `no-pidfd`, `pidfd_open` fails in this process and
/// an error report also lists this process's children left after `start`.
/// With `emfile` (#11098) it calls `stop` instead, with one fd free, and
/// writes the result's `Debug` form.
fn runner_main(args: &[String]) -> ! {
    if args.iter().any(|a| a == "no-pidfd") {
        deny_pidfd_open();
    }
    let socket = PathBuf::from(arg(args, "socket").expect("socket"));
    let marker = PathBuf::from(arg(args, "marker").expect("marker"));
    let out = arg(args, "out").expect("out");
    let mut desc = DaemonDescriptor::with_install_dir(
        DAEMON,
        arg(args, "install").expect("install"),
        &socket,
        StoppedSignal::SocketRefuses,
    )
    .expect("descriptor");
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    set_instance(&mut desc, &socket);
    // #11098: `allow=NAME` puts one name on the environment allowlist.
    desc.env_passthrough = arg(args, "allow").map(str::to_string).into_iter().collect();
    desc.ready_timeout = SERVE_BOUND;
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("runtime");
    if args.iter().any(|a| a == "emfile") {
        // #11098: one free fd — the dial's, then `read_dir("/proc")`'s — so
        // the scan's first `/proc/<pid>/status` open fails with EMFILE.
        let fillers = exhaust_fds();
        let stopped = rt.block_on(stop(&desc));
        drop(fillers);
        fs::write(out, format!("{stopped:?}")).expect("write out");
        std::process::exit(0);
    }
    match rt.block_on(start(&desc)) {
        Ok(outcome) => {
            fs::write(out, outcome.pid.to_string()).expect("write out");
            std::process::exit(0);
        }
        Err(e) => {
            let children: Vec<String> = children_of_self().iter().map(u32::to_string).collect();
            fs::write(out, format!("error: {e}\nchildren={}", children.join(",")))
                .expect("write out");
            std::process::exit(1);
        }
    }
}

/// Lower the soft fd limit, open files until `EMFILE`, then free exactly one.
fn exhaust_fds() -> Vec<File> {
    let mut lim = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: get/setrlimit with a valid rlimit pointer.
    unsafe {
        assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut lim), 0);
        lim.rlim_cur = lim.rlim_cur.min(128);
        assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &raw const lim), 0);
    }
    let mut files = Vec::new();
    loop {
        match File::open("/dev/null") {
            Ok(f) => files.push(f),
            Err(e) if e.raw_os_error() == Some(libc::EMFILE) => break,
            Err(e) => panic!("filling the fd table: {e}"),
        }
    }
    files.pop().expect("at least one filler");
    files
}

fn daemon_args(mode: &str, extra: &[String]) -> Vec<String> {
    role_args(ROLE_DAEMON, mode, extra)
}

/// Point `desc` at the instance on `socket` (#11098). The liveness argument is
/// the real daemons' shape — the role alone, as `serve --foreground` is — so
/// every test's fixture daemon matches it, and only `instance_env` tells this
/// test's instance from the others.
fn set_instance(desc: &mut DaemonDescriptor, socket: &Path) {
    desc.socket = socket.to_path_buf();
    desc.liveness_args = vec![ROLE_DAEMON.to_string()];
    desc.instance_env.retain(|(name, _)| name != SOCKET_ENV);
    desc.instance_env
        .push((SOCKET_ENV.to_string(), Some(socket.as_os_str().to_owned())));
}

fn role_args(role: &str, mode: &str, extra: &[String]) -> Vec<String> {
    let mut args = vec![
        "--exact".to_string(),
        "child_entry".to_string(),
        "-q".to_string(),
        role.to_string(),
        format!("mode={mode}"),
    ];
    args.extend_from_slice(extra);
    args
}

// ─── Test harness ───────────────────────────────────────────────────────────

struct Fixture {
    _install_dir: tempfile::TempDir,
    _work_dir: tempfile::TempDir,
    install: PathBuf,
    work: PathBuf,
    socket: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        let exe = std::env::current_exe().expect("current_exe");
        let exe_dir = exe.parent().expect("exe dir");
        // Same filesystem as the test binary, so a hard link always works and
        // no copy (with its open write fd) races a concurrent fork.
        let install_dir = tempfile::Builder::new()
            .prefix("lc-install")
            .tempdir_in(exe_dir)
            .expect("install dir");
        for name in [DAEMON, OTHER] {
            fs::hard_link(&exe, install_dir.path().join(name)).expect("hard link fixture");
        }
        let work_dir = tempfile::tempdir().expect("work dir");
        let install = fs::canonicalize(install_dir.path()).expect("canonical install");
        let work = work_dir.path().to_path_buf();
        let socket = work.join("d.sock");
        Self {
            _install_dir: install_dir,
            _work_dir: work_dir,
            install,
            work,
            socket,
        }
    }

    fn descriptor(&self, signal: StoppedSignal) -> DaemonDescriptor {
        self.descriptor_at(signal, &self.socket)
    }

    /// [`Fixture::descriptor`] for the instance on another socket path.
    fn descriptor_at(&self, signal: StoppedSignal, socket: &Path) -> DaemonDescriptor {
        let mut desc = DaemonDescriptor::with_install_dir(DAEMON, &self.install, socket, signal)
            .expect("descriptor");
        desc.stop_grace = Duration::from_secs(30);
        desc.kill_wait = Duration::from_secs(5);
        desc.ready_timeout = SERVE_BOUND;
        set_instance(&mut desc, socket);
        desc
    }

    /// The socket of another instance, in its own directory under the work
    /// dir, so that instance's watchdog ends with the test.
    fn instance_socket(&self, name: &str) -> PathBuf {
        let dir = self.path(name);
        fs::create_dir(&dir).expect("instance dir");
        dir.join("d.sock")
    }

    fn path(&self, name: &str) -> PathBuf {
        self.work.join(name)
    }

    /// Spawn a fixture daemon directly (not through the module) and wait for it
    /// to serve.
    fn spawn(&self, binary: &str, mode: &str, extra: &[String]) -> Running {
        self.spawn_at(binary, mode, &self.socket, extra)
    }

    /// [`Fixture::spawn`] on another socket path.
    fn spawn_at(&self, binary: &str, mode: &str, socket: &Path, extra: &[String]) -> Running {
        let running = self.launch(binary, mode, socket, extra);
        assert!(wait_serving(socket), "fixture never served");
        running
    }

    /// Spawn a fixture daemon without waiting for it to serve.
    fn launch(&self, binary: &str, mode: &str, socket: &Path, extra: &[String]) -> Running {
        self.launch_as(ROLE_DAEMON, binary, mode, socket, extra)
    }

    /// [`Fixture::launch`] with another role argument (#11098: a bridge).
    fn launch_as(
        &self,
        role: &str,
        binary: &str,
        mode: &str,
        socket: &Path,
        extra: &[String],
    ) -> Running {
        let child = Command::new(self.install.join(binary))
            .args(role_args(role, mode, extra))
            .env(SOCKET_ENV, socket)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn fixture");
        Running { child }
    }

    /// A [`Reap`] for every pid the fixtures wrote to `marker`.
    fn reap_reported(&self, marker: &Path) -> Vec<Reap> {
        lines(marker)
            .iter()
            .filter_map(|l| l.parse().ok())
            .map(|pid| Reap::arm(pid, &self.install))
            .collect()
    }
}

/// A fixture child that is SIGKILLed and reaped on drop.
struct Running {
    child: Child,
}

impl Running {
    fn pid(&self) -> u32 {
        self.child.id()
    }
}

impl Drop for Running {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn wait_serving(socket: &Path) -> bool {
    wait_for(|| UnixStream::connect(socket).is_ok())
}

/// Poll `cond` until it holds or `SERVE_BOUND` passes.
fn wait_for(mut cond: impl FnMut() -> bool) -> bool {
    let deadline = Instant::now() + SERVE_BOUND;
    while Instant::now() < deadline {
        if cond() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    false
}

/// Whether another open file description holds `lock`'s `flock`.
fn lock_held(lock: &Path) -> bool {
    File::open(lock).is_ok_and(|f| matches!(f.try_lock(), Err(fs::TryLockError::WouldBlock)))
}

/// Alive = `/proc/<pid>` exists and is not a zombie.
fn is_alive(pid: u32) -> bool {
    // #11098: bytes, as `comm` in `stat` may be non-UTF-8.
    let Ok(stat) = fs::read(format!("/proc/{pid}/stat")) else {
        return false;
    };
    let close = stat.iter().rposition(|b| *b == b')');
    let state = close.and_then(|i| stat[i + 1..].iter().find(|b| !b.is_ascii_whitespace()));
    !matches!(state, None | Some(b'Z' | b'X'))
}

fn kill_pid(pid: u32) {
    // SAFETY: plain kill(2) on a pid this test owns.
    unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
}

/// SIGKILLs a fixture pid on drop unless disarmed.
///
/// Why: the module now reaps a child it failed to start, so its pid can be
/// reused; a bare `kill(pid)` on drop could reach an unrelated process (#11084).
/// What: `arm` pins the pid with a pidfd and keeps it only when
/// `/proc/<pid>/exe` lies in the test's install dir; drop signals through the
/// pidfd, which never reaches a newcomer.
struct Reap(Option<OwnedFd>);

impl Reap {
    fn arm(pid: u32, install: &Path) -> Self {
        // SAFETY: pidfd_open takes a pid and flags and returns a new fd or -1.
        let rc = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0) };
        if rc < 0 {
            return Self(None);
        }
        // SAFETY: a fresh fd owned by no one else.
        let fd = unsafe { OwnedFd::from_raw_fd(rc as i32) };
        let ours =
            fs::read_link(format!("/proc/{pid}/exe")).is_ok_and(|exe| exe.starts_with(install));
        Self(ours.then_some(fd))
    }

    fn disarm(&mut self) {
        self.0 = None;
    }
}

impl Drop for Reap {
    fn drop(&mut self) {
        if let Some(fd) = &self.0 {
            // SAFETY: an open pidfd, SIGKILL, null siginfo, zero flags.
            unsafe {
                libc::syscall(
                    libc::SYS_pidfd_send_signal,
                    fd.as_raw_fd(),
                    libc::SIGKILL,
                    std::ptr::null::<libc::siginfo_t>(),
                    0,
                );
            }
        }
    }
}

/// Restores a directory's mode on drop, so the temp dir can be removed.
struct ModeGuard(PathBuf);

impl ModeGuard {
    fn lock(dir: &Path) -> Self {
        fs::set_permissions(dir, fs::Permissions::from_mode(0o000)).expect("chmod 000");
        Self(dir.to_path_buf())
    }
}

impl Drop for ModeGuard {
    fn drop(&mut self) {
        let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o755));
    }
}

fn lines(path: &Path) -> Vec<String> {
    fs::read_to_string(path)
        .unwrap_or_default()
        .lines()
        .map(str::to_string)
        .collect()
}

/// Records every signal; forwards SIGTERM, and SIGKILL only when `kill_takes`.
struct Recording {
    kill_takes: bool,
    sent: Mutex<Vec<Signal>>,
}

impl Recording {
    fn new(kill_takes: bool) -> Self {
        Self {
            kill_takes,
            sent: Mutex::new(Vec::new()),
        }
    }

    fn sent(&self) -> Vec<Signal> {
        self.sent.lock().expect("sent lock").clone()
    }
}

impl SignalDelivery for Recording {
    fn deliver(&self, target: &PinnedProcess, signal: Signal) -> std::io::Result<()> {
        self.sent.lock().expect("sent lock").push(signal);
        if signal == Signal::Kill && !self.kill_takes {
            return Ok(());
        }
        target.send_signal(signal)
    }
}

// ─── stop ───────────────────────────────────────────────────────────────────

// AC5.
#[tokio::test]
async fn stop_returns_not_running_when_socket_is_absent() {
    let fx = Fixture::new();
    let rec = Recording::new(true);
    let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
    assert_eq!(out.expect("stop"), StopOutcome::NotRunning);
    assert!(rec.sent().is_empty(), "no signal may be sent");
}

// AC5.
#[tokio::test]
async fn stop_returns_not_running_when_socket_refuses_connections() {
    let fx = Fixture::new();
    drop(UnixListener::bind(&fx.socket).expect("bind"));
    assert!(fx.socket.exists(), "stale socket file must remain");
    // #11098: another test's fork holds a copy of the listener until its exec,
    // so the socket can accept for that window; wait until it refuses.
    assert!(
        wait_for(|| UnixStream::connect(&fx.socket)
            .is_err_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused)),
        "fixture precondition: the stale socket refuses"
    );
    let rec = Recording::new(true);
    let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
    assert_eq!(out.expect("stop"), StopOutcome::NotRunning);
    assert!(rec.sent().is_empty(), "no signal may be sent");
}

// Clean stop; a fixed sleep as long as the grace would fail the time bound.
#[tokio::test]
async fn stop_returns_stopped_promptly_after_a_clean_exit() {
    let fx = Fixture::new();
    let mut d = fx.spawn(DAEMON, "serve", &[]);
    let rec = Recording::new(true);
    let t0 = Instant::now();
    let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
    let elapsed = t0.elapsed();
    let pid = d.pid();
    assert_eq!(
        out.expect("stop"),
        StopOutcome::Stopped { pid, forced: false }
    );
    assert!(
        d.child.try_wait().expect("try_wait").is_some(),
        "pid must have exited"
    );
    assert!(elapsed < Duration::from_secs(10), "stop took {elapsed:?}");
    assert_eq!(rec.sent(), vec![Signal::Term]);
}

// AC1: the socket closes at SIGTERM, the pid lives LINGER_MS longer.
#[tokio::test]
async fn stop_waits_for_pid_exit_not_socket_close() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let mut d = fx.spawn(DAEMON, "linger", &[format!("marker={}", marker.display())]);
    let t0 = Instant::now();
    let out = stop(&fx.descriptor(StoppedSignal::SocketRefuses)).await;
    let elapsed = t0.elapsed();
    let pid = d.pid();
    assert_eq!(
        out.expect("stop"),
        StopOutcome::Stopped { pid, forced: false }
    );
    assert!(
        d.child.try_wait().expect("try_wait").is_some(),
        "pid must have exited"
    );
    assert!(
        elapsed >= Duration::from_millis(LINGER_MS),
        "returned after {elapsed:?}, before the pid exited"
    );
    assert!(
        lines(&marker).iter().any(|l| l == "closed"),
        "socket closed first"
    );
}

// AC2.
#[tokio::test]
async fn stop_sends_sigkill_to_a_process_that_ignores_sigterm() {
    let fx = Fixture::new();
    let mut d = fx.spawn(DAEMON, "ignore-term", &[]);
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.stop_grace = Duration::from_millis(300);
    let rec = Recording::new(true);
    let out = stop_with(&desc, &rec).await;
    let pid = d.pid();
    assert_eq!(
        out.expect("stop"),
        StopOutcome::Stopped { pid, forced: true }
    );
    let status = d
        .child
        .try_wait()
        .expect("try_wait")
        .expect("pid must have exited");
    assert_eq!(status.signal(), Some(libc::SIGKILL));
    assert_eq!(rec.sent(), vec![Signal::Term, Signal::Kill]);
}

// AC3.
#[tokio::test]
async fn stop_reports_a_survivor_when_sigkill_does_not_take() {
    let fx = Fixture::new();
    let d = fx.spawn(DAEMON, "ignore-term", &[]);
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.stop_grace = Duration::from_millis(200);
    desc.kill_wait = Duration::from_millis(300);
    let rec = Recording::new(false);
    match stop_with(&desc, &rec).await {
        Err(LifecycleError::Survivor { pid }) => assert_eq!(pid, d.pid()),
        other => panic!("expected Survivor, got {other:?}"),
    }
    assert!(is_alive(d.pid()), "the survivor is still running");
    assert_eq!(rec.sent(), vec![Signal::Term, Signal::Kill]);
}

// AC4.
#[tokio::test]
async fn stop_refuses_to_signal_a_process_with_another_name() {
    let fx = Fixture::new();
    let d = fx.spawn(OTHER, "serve", &[]);
    let rec = Recording::new(true);
    match stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await {
        Err(LifecycleError::IdentityMismatch {
            pid,
            expected,
            found,
        }) => {
            assert_eq!(
                (pid, expected.as_str(), found.as_str()),
                (d.pid(), DAEMON, OTHER)
            );
        }
        other => panic!("expected IdentityMismatch, got {other:?}"),
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(d.pid()), "the other process is untouched");
}

// AC8: the pid exits, but a forked child keeps the flock.
#[tokio::test]
async fn stop_with_lock_signal_is_not_stopped_while_another_process_holds_the_lock() {
    let fx = Fixture::new();
    let lock = fx.path("daemon.lock");
    let marker = fx.path("marker");
    let mut d = fx.spawn(
        DAEMON,
        "fork-lock-holder",
        &[
            format!("lock={}", lock.display()),
            format!("marker={}", marker.display()),
        ],
    );
    let mut desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
    desc.kill_wait = Duration::from_secs(1);
    let out = stop(&desc).await;
    let holder: u32 = lines(&marker)
        .iter()
        .find_map(|l| l.strip_prefix("holder=")?.parse().ok())
        .expect("holder pid");
    let holder_alive = is_alive(holder);
    kill_pid(holder);
    match out {
        Err(LifecycleError::StoppedSignalNotReached { pid, .. }) => assert_eq!(pid, d.pid()),
        other => panic!("expected StoppedSignalNotReached, got {other:?}"),
    }
    assert!(
        d.child.try_wait().expect("try_wait").is_some(),
        "the daemon pid exited"
    );
    assert!(holder_alive, "the lock holder was alive during stop");

    let deadline = Instant::now() + SERVE_BOUND;
    while is_alive(holder) && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(10));
    }
    assert_eq!(stop(&desc).await.expect("stop"), StopOutcome::NotRunning);
}

// AC8, positive half.
#[tokio::test]
async fn stop_with_lock_signal_returns_stopped_once_the_lock_is_released() {
    let fx = Fixture::new();
    let lock = fx.path("daemon.lock");
    let d = fx.spawn(DAEMON, "serve", &[format!("lock={}", lock.display())]);
    let desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
    let pid = d.pid();
    assert_eq!(
        stop(&desc).await.expect("stop"),
        StopOutcome::Stopped { pid, forced: false }
    );
    let probe = File::open(&lock).expect("lock file");
    assert!(probe.try_lock().is_ok(), "the flock is free after Stopped");
}

// ─── start ──────────────────────────────────────────────────────────────────

// AC6 and AC9: a separate process with a decoy first on PATH calls `start`
// and exits; the daemon runs the install-dir binary and keeps serving.
#[tokio::test]
async fn start_from_another_process_spawns_the_install_dir_binary_and_it_outlives_the_caller() {
    let fx = Fixture::new();
    let decoy_dir = fx.path("decoy");
    fs::create_dir(&decoy_dir).expect("decoy dir");
    let decoy_ran = fx.path("decoy-ran");
    let decoy = decoy_dir.join(DAEMON);
    fs::write(
        &decoy,
        format!("#!/bin/sh\ntouch '{}'\n", decoy_ran.display()),
    )
    .expect("decoy");
    fs::set_permissions(&decoy, fs::Permissions::from_mode(0o755)).expect("chmod decoy");
    let path = format!(
        "{}:{}",
        decoy_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = fx.path("out");
    let marker = fx.path("marker");
    let status = Command::new(std::env::current_exe().expect("current_exe"))
        .args(["--exact", "child_entry", "-q", ROLE_RUNNER])
        .arg(format!("install={}", fx.install.display()))
        .arg(format!("socket={}", fx.socket.display()))
        .arg(format!("marker={}", marker.display()))
        .arg(format!("out={}", out.display()))
        .env("PATH", path)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run runner");
    let mut reaps = fx.reap_reported(&marker);
    let report = fs::read_to_string(&out).unwrap_or_default();
    assert!(status.success(), "runner failed: {report}");
    let pid: u32 = report.trim().parse().expect("runner pid");
    assert_eq!(
        lines(&marker),
        vec![pid.to_string()],
        "one daemon, reported"
    );

    assert!(is_alive(pid), "the daemon outlived the runner");
    assert!(UnixStream::connect(&fx.socket).is_ok(), "and still serves");
    let exe = fs::read_link(format!("/proc/{pid}/exe")).expect("exe link");
    assert_eq!(exe, fx.install.join(DAEMON));
    assert!(!decoy_ran.exists(), "the PATH decoy must never run");

    let desc = fx.descriptor(StoppedSignal::SocketRefuses);
    assert_eq!(
        stop(&desc).await.expect("cleanup stop"),
        StopOutcome::Stopped { pid, forced: false }
    );
    reaps.iter_mut().for_each(Reap::disarm);
}

// AC7, and #11084: the unready child is killed and reaped, not left running
// where no `stop` can find it.
#[tokio::test]
async fn start_errors_when_the_socket_never_serves() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("never-bind", &[format!("marker={}", marker.display())]);
    desc.ready_timeout = Duration::from_secs(1);
    let out = start(&desc).await;
    let _reaps = fx.reap_reported(&marker);
    let (pid, err) = match out {
        Err(e @ LifecycleError::NotReady { pid, .. }) => (pid, e),
        other => panic!("expected NotReady, got {other:?}"),
    };
    assert_eq!(lines(&marker), vec![pid.to_string()], "the child ran");
    assert!(!is_alive(pid), "the unready child must be gone: {err}");
    assert!(
        !Path::new(&format!("/proc/{pid}")).exists(),
        "and reaped, not a zombie"
    );
    assert!(err.to_string().contains("killed and reaped"), "{err}");
}

// #11084: with no pidfd for the child (ENOSYS through seccomp, as on a kernel
// before 5.3), `start` still kills and reaps it. A separate runner process
// takes the filter, so the test process keeps its pidfds.
#[test]
fn start_kills_the_child_when_its_pidfd_cannot_be_opened() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let out = fx.path("out");
    let status = Command::new(std::env::current_exe().expect("current_exe"))
        .args(["--exact", "child_entry", "-q", ROLE_RUNNER, "no-pidfd"])
        .arg(format!("install={}", fx.install.display()))
        .arg(format!("socket={}", fx.socket.display()))
        .arg(format!("marker={}", marker.display()))
        .arg(format!("out={}", out.display()))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run runner");
    let report = fs::read_to_string(&out).unwrap_or_default();
    let children: Vec<u32> = report
        .lines()
        .find_map(|l| l.strip_prefix("children="))
        .unwrap_or_default()
        .split(',')
        .filter_map(|p| p.parse().ok())
        .collect();
    let _reaps: Vec<Reap> = children
        .iter()
        .map(|&pid| Reap::arm(pid, &fx.install))
        .chain(fx.reap_reported(&marker))
        .collect();
    assert!(
        !status.success(),
        "start must fail without a pidfd: {report}"
    );
    assert!(report.contains("pidfd"), "the pidfd arm was hit: {report}");
    assert!(
        children.is_empty(),
        "start left children {children:?} behind: {report}"
    );
    for pid in lines(&marker).iter().filter_map(|l| l.parse::<u32>().ok()) {
        assert!(!is_alive(pid), "spawned pid {pid} still runs: {report}");
    }
}

#[tokio::test]
async fn start_errors_when_the_child_exits_at_boot() {
    let fx = Fixture::new();
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("exit-now", &[]);
    desc.ready_timeout = Duration::from_secs(30);
    let t0 = Instant::now();
    let out = start(&desc).await;
    assert!(
        matches!(out, Err(LifecycleError::ChildExited { .. })),
        "expected ChildExited, got {out:?}"
    );
    assert!(
        t0.elapsed() < Duration::from_secs(10),
        "reported as a death, not a timeout"
    );
}

// ─── restart ────────────────────────────────────────────────────────────────

// AC5 + P-b.
#[tokio::test]
async fn restart_starts_a_daemon_that_is_not_running() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let out = restart(&desc).await;
    let mut reaps = fx.reap_reported(&marker);
    let out = out.expect("restart");
    assert_eq!(out.stop, StopOutcome::NotRunning);
    let pid = out.start.pid;
    assert_eq!(
        lines(&marker),
        vec![pid.to_string()],
        "one daemon, reported"
    );
    assert!(
        UnixStream::connect(&fx.socket).is_ok(),
        "the new daemon serves"
    );
    let exe = fs::read_link(format!("/proc/{pid}/exe")).expect("exe link");
    assert_eq!(exe, fx.install.join(DAEMON));
    assert_eq!(
        stop(&desc).await.expect("cleanup stop"),
        StopOutcome::Stopped { pid, forced: false }
    );
    reaps.iter_mut().for_each(Reap::disarm);
}

// AC3: a survivor aborts the restart before any spawn.
#[tokio::test]
async fn restart_does_not_start_when_stop_reports_a_survivor() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let marker_arg = format!("marker={}", marker.display());
    let d = fx.spawn(DAEMON, "ignore-term", std::slice::from_ref(&marker_arg));
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[marker_arg]);
    desc.stop_grace = Duration::from_millis(200);
    desc.kill_wait = Duration::from_millis(300);
    match restart_with(&desc, &Recording::new(false)).await {
        Err(LifecycleError::Survivor { pid }) => assert_eq!(pid, d.pid()),
        other => panic!("expected Survivor, got {other:?}"),
    }
    // A spawned daemon writes its pid to the marker first thing; give a wrong
    // implementation's child a bounded moment to show up.
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);
    assert_eq!(
        lines(&marker),
        vec![d.pid().to_string()],
        "no second process"
    );
    assert!(is_alive(d.pid()));
}

// ─── fail-open arms (#11084) ────────────────────────────────────────────────

// The lock is held but nothing serves the socket: the holder cannot be
// identified, so neither `stop` nor `restart` may treat it as not running.
#[tokio::test]
async fn stop_and_restart_refuse_when_the_lock_is_held_without_a_socket() {
    let fx = Fixture::new();
    let lock = fx.path("daemon.lock");
    let marker = fx.path("marker");
    let marker_arg = format!("marker={}", marker.display());
    let holder = fx.launch(
        DAEMON,
        "never-bind",
        &fx.socket,
        &[format!("lock={}", lock.display()), marker_arg.clone()],
    );
    assert!(
        wait_for(|| lock_held(&lock)),
        "the holder never took the lock"
    );
    let mut desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
    desc.spawn_args = daemon_args("serve", &[marker_arg]);
    let rec = Recording::new(true);
    let stopped = stop_with(&desc, &rec).await;
    let restarted = restart_with(&desc, &rec).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);

    assert!(
        matches!(&stopped, Err(LifecycleError::Unidentified { lock: l, .. }) if *l == lock),
        "stop: expected Unidentified, got {stopped:?}"
    );
    assert!(
        matches!(restarted, Err(LifecycleError::Unidentified { .. })),
        "restart: expected Unidentified, got {restarted:?}"
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert_eq!(
        lines(&marker),
        vec![holder.pid().to_string()],
        "restart spawned nothing"
    );
    assert!(is_alive(holder.pid()), "the holder is untouched");
}

// `start` against a served socket must not spawn: the fixture unlinks and
// rebinds the socket, so a second daemon would serve too — the marker counts.
#[tokio::test]
async fn start_refuses_a_socket_that_already_serves_and_spawns_no_second_daemon() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let marker_arg = format!("marker={}", marker.display());
    let d = fx.spawn(DAEMON, "serve", std::slice::from_ref(&marker_arg));
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[marker_arg]);
    let out = start(&desc).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);

    assert_eq!(
        lines(&marker),
        vec![d.pid().to_string()],
        "exactly one daemon process (start returned {out:?})"
    );
    match out {
        Err(LifecycleError::AlreadyRunning { pid, .. }) => assert_eq!(pid, Some(d.pid())),
        other => panic!("expected AlreadyRunning, got {other:?}"),
    }
    assert!(is_alive(d.pid()), "the running daemon is untouched");
}

// An undumpable listener's `/proc/<pid>/exe` cannot be read: no identity, so
// no signal.
#[tokio::test]
async fn stop_refuses_to_signal_a_process_whose_executable_cannot_be_read() {
    let fx = Fixture::new();
    // #11098: the bridge role keeps this process out of every concurrent
    // test's scan, where its unreadable environment would fail closed.
    let d = fx.launch_as(
        ROLE_BRIDGE,
        DAEMON,
        "serve",
        &fx.socket,
        &["undumpable".to_string()],
    );
    assert!(wait_serving(&fx.socket), "fixture never served");
    assert!(
        fs::read_link(format!("/proc/{}/exe", d.pid())).is_err(),
        "fixture precondition: the exe link is unreadable (not running as root)"
    );
    let rec = Recording::new(true);
    match stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await {
        Err(LifecycleError::IdentityUnreadable { pid, .. }) => assert_eq!(pid, d.pid()),
        other => panic!("expected IdentityUnreadable, got {other:?}"),
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(d.pid()), "the process stays alive");
}

// A connect that fails with EACCES (socket in a mode-000 directory) proves
// nothing: `stop` is inconclusive and `restart` does not start.
#[tokio::test]
async fn stop_and_restart_stop_short_when_the_socket_cannot_be_probed() {
    let fx = Fixture::new();
    let dir = fx.path("locked");
    fs::create_dir(&dir).expect("socket dir");
    let socket = dir.join("d.sock");
    let marker = fx.path("marker");
    let marker_arg = format!("marker={}", marker.display());
    let d = fx.spawn_at(DAEMON, "serve", &socket, std::slice::from_ref(&marker_arg));
    let mut desc = fx.descriptor_at(StoppedSignal::SocketRefuses, &socket);
    desc.spawn_args = daemon_args("serve", &[marker_arg]);
    let guard = ModeGuard::lock(&dir);
    let probe = UnixStream::connect(&socket).map(drop);
    assert!(
        matches!(&probe, Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
        "fixture precondition: connect is refused with EACCES, got {probe:?}"
    );
    let rec = Recording::new(true);
    let stopped = stop_with(&desc, &rec).await;
    let restarted = restart_with(&desc, &rec).await;
    std::thread::sleep(SPAWN_SETTLE);
    drop(guard);
    let _reaps = fx.reap_reported(&marker);

    for (call, out) in [
        ("stop", stopped.map(|o| format!("{o:?}"))),
        ("restart", restarted.map(|o| format!("{o:?}"))),
    ] {
        assert!(
            matches!(&out, Err(LifecycleError::ProbeInconclusive { socket: s }) if *s == socket),
            "{call}: expected ProbeInconclusive, got {out:?}"
        );
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert_eq!(
        lines(&marker),
        vec![d.pid().to_string()],
        "restart spawned nothing"
    );
    assert!(is_alive(d.pid()), "the daemon is untouched");
}

// ─── #11098: liveness without a socket, and the spawn's cwd/env ─────────────

/// The pid lines of a marker; other lines (`unserved`, `closed`) are skipped.
fn pid_lines(marker: &Path) -> Vec<String> {
    lines(marker)
        .into_iter()
        .filter(|l| l.parse::<u32>().is_ok())
        .collect()
}

// #11098: a daemon that unlinked its socket file, or closed its listener,
// still runs. The shortcut "socket absent ⇒ not running" reports `NotRunning`
// and lets `restart` spawn a second daemon; here every call refuses, names
// the pid, and signals and spawns nothing.
#[tokio::test]
async fn stop_start_and_restart_refuse_while_a_daemon_runs_without_its_socket() {
    for mode in ["unlink-socket", "close-socket"] {
        let fx = Fixture::new();
        let marker = fx.path("marker");
        let marker_arg = format!("marker={}", marker.display());
        let d = fx.launch(DAEMON, mode, &fx.socket, std::slice::from_ref(&marker_arg));
        assert!(
            wait_for(|| lines(&marker).iter().any(|l| l == "unserved")),
            "{mode}: the fixture never dropped its socket"
        );
        assert!(
            UnixStream::connect(&fx.socket).is_err(),
            "{mode}: fixture precondition: the socket does not serve"
        );
        let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
        desc.spawn_args = daemon_args("serve", &[marker_arg]);
        let rec = Recording::new(true);
        let stopped = stop_with(&desc, &rec).await;
        let restarted = restart_with(&desc, &rec).await;
        let started = start(&desc).await;
        std::thread::sleep(SPAWN_SETTLE);
        let _reaps = fx.reap_reported(&marker);

        assert_eq!(
            pid_lines(&marker),
            vec![d.pid().to_string()],
            "{mode}: a second daemon was spawned (stop: {stopped:?}, restart: {restarted:?})"
        );
        for (call, out) in [
            ("stop", stopped.map(|o| format!("{o:?}"))),
            ("restart", restarted.map(|o| format!("{o:?}"))),
            ("start", started.map(|o| format!("{o:?}"))),
        ] {
            assert!(
                matches!(&out, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
                "{mode}: {call}: expected RunningUnserved naming pid {}, got {out:?}",
                d.pid()
            );
        }
        assert!(rec.sent().is_empty(), "{mode}: no signal may be sent");
        assert!(is_alive(d.pid()), "{mode}: the daemon is untouched");
    }
}

// #11098: the scan reads every process's status, and a `comm` that is not
// UTF-8 once failed `read_to_string`, so one such process anywhere on the
// host made `stop` and `start` error for every daemon.
#[tokio::test]
async fn stop_ignores_an_unrelated_process_whose_name_is_not_utf8() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let other = fx.launch(
        OTHER,
        "never-bind",
        &fx.instance_socket("other"),
        &[format!("marker={}", marker.display()), BAD_NAME_FLAG.into()],
    );
    assert!(
        wait_for(|| !pid_lines(&marker).is_empty()),
        "the fixture never started"
    );
    let status = fs::read(format!("/proc/{}/status", other.pid())).expect("read status");
    assert!(
        std::str::from_utf8(&status).is_err(),
        "the fixture's status must hold its non-UTF-8 name"
    );
    let rec = Recording::new(true);
    let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
    assert_eq!(
        out.expect("a non-UTF-8 name on an unrelated process must not fail the scan"),
        StopOutcome::NotRunning
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(other.pid()), "the unrelated process is untouched");
}

// #11098: a stdio bridge runs the daemon's executable but not its arguments.
// The shortcut "match on the executable alone" reads it as the daemon.
#[tokio::test]
async fn stop_returns_not_running_while_only_a_bridge_of_the_same_binary_runs() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let bridge = fx.launch_as(
        ROLE_BRIDGE,
        DAEMON,
        "never-bind",
        &fx.socket,
        &[format!("marker={}", marker.display())],
    );
    assert!(
        wait_for(|| !pid_lines(&marker).is_empty()),
        "the bridge never started"
    );
    let rec = Recording::new(true);
    let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
    assert_eq!(
        out.expect("a bridge alone is not the daemon"),
        StopOutcome::NotRunning
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(bridge.pid()), "the bridge is untouched");
}

// #11098: `start` called from a checkout with a `.env.local`, and with a
// sentinel exported, must not run the daemon in that checkout or hand it the
// sentinel. A separate runner calls `start`, so this process keeps its cwd.
#[test]
fn start_runs_the_daemon_in_its_working_dir_with_only_the_allowed_environment() {
    let fx = Fixture::new();
    let checkout = fx.path("checkout");
    fs::create_dir(&checkout).expect("checkout dir");
    fs::write(checkout.join(".env.local"), "TC_LC_FROM_DOTENV=1\n").expect(".env.local");
    let checkout = fs::canonicalize(&checkout).expect("canonical checkout");
    let out = fx.path("out");
    let marker = fx.path("marker");
    let status = Command::new(std::env::current_exe().expect("current_exe"))
        .args([
            "--exact",
            "child_entry",
            "-q",
            ROLE_RUNNER,
            "allow=TC_LC_ALLOWED",
        ])
        .arg(format!("install={}", fx.install.display()))
        .arg(format!("socket={}", fx.socket.display()))
        .arg(format!("marker={}", marker.display()))
        .arg(format!("out={}", out.display()))
        .current_dir(&checkout)
        .env("TC_LC_SENTINEL", "leaked")
        .env("TC_LC_ALLOWED", "kept")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run runner");
    let _reaps = fx.reap_reported(&marker);
    let report = fs::read_to_string(&out).unwrap_or_default();
    assert!(status.success(), "runner failed: {report}");
    let pid: u32 = report.trim().parse().expect("runner pid");
    let cwd = fs::read_link(format!("/proc/{pid}/cwd")).expect("daemon cwd");
    let environ = fs::read(format!("/proc/{pid}/environ")).expect("daemon environ");
    let vars: Vec<String> = environ
        .split(|b| *b == 0)
        .map(|v| String::from_utf8_lossy(v).into_owned())
        .collect();
    // Names only in a failure message: a value can be a credential.
    let names: Vec<&str> = vars.iter().filter_map(|v| v.split('=').next()).collect();

    assert_ne!(cwd, checkout, "the daemon runs in the caller's cwd");
    assert_eq!(cwd, Path::new("/"), "the default working_dir is /");
    assert!(
        !names.contains(&"TC_LC_SENTINEL"),
        "the caller's sentinel reached the daemon; its names: {names:?}"
    );
    assert!(
        vars.iter().any(|v| v == "TC_LC_ALLOWED=kept"),
        "the allowlisted variable is missing; names: {names:?}"
    );
    if let Some(home) = std::env::var_os("HOME") {
        let want = format!("HOME={}", home.to_string_lossy());
        assert!(
            vars.contains(&want),
            "the base HOME is missing; names: {names:?}"
        );
    }
}

// ─── #11098: sibling instances of the same binary and argv ──────────────────

fn cmdline(pid: u32) -> Vec<u8> {
    fs::read(format!("/proc/{pid}/cmdline")).expect("cmdline")
}

/// Two instances, A and B, of one binary with identical argv; only their
/// `SOCKET_ENV` values (the stand-in for a data-dir variable) differ.
struct Siblings {
    fx: Fixture,
    marker: PathBuf,
    extra: Vec<String>,
    sock_a: PathBuf,
    sock_b: PathBuf,
}

impl Siblings {
    fn new() -> Self {
        let fx = Fixture::new();
        let marker = fx.path("marker");
        let extra = vec![format!("marker={}", marker.display())];
        let (sock_a, sock_b) = (fx.instance_socket("a"), fx.instance_socket("b"));
        Self {
            fx,
            marker,
            extra,
            sock_a,
            sock_b,
        }
    }

    fn run(&self, socket: &Path) -> Running {
        self.fx.spawn_at(DAEMON, "serve", socket, &self.extra)
    }

    /// The descriptor for instance A, spawning A with B's argv.
    fn desc_a(&self) -> DaemonDescriptor {
        let mut desc = self
            .fx
            .descriptor_at(StoppedSignal::SocketRefuses, &self.sock_a);
        desc.spawn_args = daemon_args("serve", &self.extra);
        desc
    }

    fn assert_b_untouched(&self, b: &Running) {
        assert!(is_alive(b.pid()), "sibling B was stopped");
        assert!(UnixStream::connect(&self.sock_b).is_ok(), "B still serves");
    }
}

// #11098: a sandbox daemon runs the production argv; only its data-dir
// variable differs. The shortcut "binary + argv is this daemon" stops A, then
// reads B as A still running, so `start` refuses and A stays down.
#[tokio::test]
async fn restart_of_one_instance_leaves_a_sibling_with_the_same_argv_serving() {
    let s = Siblings::new();
    let a = s.run(&s.sock_a);
    let b = s.run(&s.sock_b);
    assert_eq!(
        cmdline(a.pid()),
        cmdline(b.pid()),
        "precondition: same argv"
    );
    let desc = s.desc_a();
    let out = restart(&desc).await;
    let _reaps = s.fx.reap_reported(&s.marker);
    let out = out.expect("restart of A beside sibling B");
    assert_eq!(
        out.stop,
        StopOutcome::Stopped {
            pid: a.pid(),
            forced: false
        }
    );
    let new = out.start.pid;
    assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
    assert_eq!(cmdline(new), cmdline(b.pid()), "the new A has B's argv");
    s.assert_b_untouched(&b);
    assert_eq!(
        stop(&desc).await.expect("cleanup stop"),
        StopOutcome::Stopped {
            pid: new,
            forced: false
        }
    );
    s.assert_b_untouched(&b);
}

// #11098: owner ruling — a daemon that is not running is started, even while
// a sibling instance of it runs.
#[tokio::test]
async fn start_and_restart_start_a_stopped_instance_while_a_sibling_runs() {
    let s = Siblings::new();
    let b = s.run(&s.sock_b);
    let desc = s.desc_a();
    let started = start(&desc).await;
    let mut reaps = s.fx.reap_reported(&s.marker);
    let pid = started.expect("start of A beside sibling B").pid;
    assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves");
    assert_eq!(cmdline(pid), cmdline(b.pid()), "A has B's argv");
    assert_eq!(
        stop(&desc).await.expect("stop A"),
        StopOutcome::Stopped { pid, forced: false }
    );
    s.assert_b_untouched(&b);

    let restarted = restart(&desc).await;
    reaps.extend(s.fx.reap_reported(&s.marker));
    let restarted = restarted.expect("restart of a stopped A beside B");
    assert_eq!(restarted.stop, StopOutcome::NotRunning);
    assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
    assert_eq!(
        stop(&desc).await.expect("cleanup stop"),
        StopOutcome::Stopped {
            pid: restarted.start.pid,
            forced: false
        }
    );
    s.assert_b_untouched(&b);
}

// #11098: a process that matches the binary and argv but hides its
// environment (undumpable) cannot be told from this instance, so it fails
// closed. It runs as `OTHER`, which no other test's descriptor names.
#[tokio::test]
async fn stop_and_start_fail_closed_when_a_matching_process_hides_its_environment() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let marker_arg = format!("marker={}", marker.display());
    let hidden = fx.launch(
        OTHER,
        "never-bind",
        &fx.socket,
        &[marker_arg.clone(), "undumpable".to_string()],
    );
    assert!(
        wait_for(|| !pid_lines(&marker).is_empty()),
        "the fixture never started"
    );
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.binary = OTHER.to_string();
    desc.spawn_args = daemon_args("serve", &[marker_arg]);
    let rec = Recording::new(true);
    let stopped = stop_with(&desc, &rec).await;
    let started = start(&desc).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);

    for (call, out) in [
        ("stop", stopped.map(|o| format!("{o:?}"))),
        ("start", started.map(|o| format!("{o:?}"))),
    ] {
        assert!(
            matches!(&out, Err(LifecycleError::InstanceUnreadable { pid, .. }) if *pid == hidden.pid()),
            "{call}: expected InstanceUnreadable naming pid {}, got {out:?}",
            hidden.pid()
        );
    }
    assert_eq!(
        pid_lines(&marker),
        vec![hidden.pid().to_string()],
        "start spawned a second process"
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(hidden.pid()), "the process is untouched");
}

// ─── injected process table (#11085) ────────────────────────────────────────

/// A pid above any `pid_max`, so a fake entry never names a real process.
const FAKE_PID: u32 = 4_194_401;

fn euid() -> u32 {
    // SAFETY: geteuid has no preconditions and cannot fail.
    unsafe { libc::geteuid() }
}

/// Write a fake `<root>/<pid>` entry: a live process of `uid` that runs
/// `desc`'s binary with its `liveness_args` and every `instance_env` value,
/// so only the uid can rule it out. `environ` is mode 000 unless `readable`.
fn fake_proc_entry(root: &Path, pid: u32, uid: u32, desc: &DaemonDescriptor, readable: bool) {
    let dir = root.join(pid.to_string());
    fs::create_dir_all(&dir).expect("fake entry dir");
    let status = format!("Name:\tlc\nState:\tS (sleeping)\nUid:\t{uid}\t{uid}\t{uid}\t{uid}\n");
    fs::write(dir.join("status"), status).expect("fake status");
    let mut cmdline = desc.program().as_os_str().as_bytes().to_vec();
    for arg in &desc.liveness_args {
        cmdline.push(0);
        cmdline.extend_from_slice(arg.as_bytes());
    }
    cmdline.push(0);
    fs::write(dir.join("cmdline"), cmdline).expect("fake cmdline");
    std::os::unix::fs::symlink(desc.program(), dir.join("exe")).expect("fake exe link");
    let mut environ = Vec::new();
    for (name, value) in &desc.instance_env {
        if let Some(value) = value {
            environ.extend_from_slice(format!("{name}=").as_bytes());
            environ.extend_from_slice(value.as_bytes());
            environ.push(0);
        }
    }
    let path = dir.join("environ");
    fs::write(&path, environ).expect("fake environ");
    if !readable {
        fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).expect("chmod 000");
    }
}

// #11085: a matching process of another uid, readable or hiding its
// environment as a foreign daemon does, is skipped by every scan: stop, start
// and restart act as if it were absent. The same entry under this uid is this
// instance, so the uid alone rules it out.
#[tokio::test]
async fn a_foreign_uid_entry_in_the_process_table_is_skipped_by_stop_start_and_restart() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let mine = fx.path("mine-proc");
    fake_proc_entry(&mine, FAKE_PID, euid(), &desc, true);
    let foreign = fx.path("foreign-proc");
    let other_uid = euid().wrapping_add(1);
    fake_proc_entry(&foreign, FAKE_PID, other_uid, &desc, true);
    fake_proc_entry(&foreign, FAKE_PID + 1, other_uid, &desc, false);
    let table = ProcessTable::at(&foreign);
    let rec = Recording::new(true);

    let control = stop_with_table(&desc, &rec, &ProcessTable::at(&mine)).await;
    let stopped = stop_with_table(&desc, &rec, &table).await;
    let started = start_with_table(&desc, &table).await;
    let restarted = restart_with_table(&desc, &KernelDelivery, &table).await;
    let mut reaps = fx.reap_reported(&marker);

    assert!(
        matches!(&control, Err(LifecycleError::RunningUnserved { pids, .. }) if pids == &[FAKE_PID]),
        "the same entry under this uid is this instance: {control:?}"
    );
    assert_eq!(stopped.expect("stop"), StopOutcome::NotRunning);
    let first = started.expect("start").pid;
    let restarted = restarted.expect("restart");
    assert_eq!(
        restarted.stop,
        StopOutcome::Stopped {
            pid: first,
            forced: false
        }
    );
    let second = restarted.start.pid;
    assert_eq!(
        stop_with_table(&desc, &KernelDelivery, &table)
            .await
            .expect("cleanup stop"),
        StopOutcome::Stopped {
            pid: second,
            forced: false
        }
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    reaps.iter_mut().for_each(Reap::disarm);
}

// #11085: a matching process of this uid whose environment cannot be read
// still fails every scan closed through an injected table, as through `/proc`
// (#11098); so does a table that cannot be listed.
#[tokio::test]
async fn a_same_uid_entry_with_an_unreadable_environment_in_the_process_table_fails_closed() {
    let fx = Fixture::new();
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let proc = fx.path("proc");
    fake_proc_entry(&proc, FAKE_PID, euid(), &desc, false);
    let table = ProcessTable::at(&proc);
    let rec = Recording::new(true);

    let stopped = stop_with_table(&desc, &rec, &table).await;
    let started = start_with_table(&desc, &table).await;
    let restarted = restart_with_table(&desc, &rec, &table).await;
    let unlisted = stop_with_table(&desc, &rec, &ProcessTable::at(fx.path("absent"))).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);

    for (call, out) in [
        ("stop", stopped.map(|o| format!("{o:?}"))),
        ("start", started.map(|o| format!("{o:?}"))),
        ("restart", restarted.map(|o| format!("{o:?}"))),
    ] {
        assert!(
            matches!(&out, Err(LifecycleError::InstanceUnreadable { pid, source, .. })
                if *pid == FAKE_PID && source.kind() == std::io::ErrorKind::PermissionDenied),
            "{call}: expected InstanceUnreadable naming pid {FAKE_PID}, got {out:?}"
        );
    }
    assert!(
        matches!(&unlisted, Err(LifecycleError::Io { .. })),
        "an unlistable table must fail closed: {unlisted:?}"
    );
    assert!(lines(&marker).is_empty(), "a daemon was spawned");
    assert!(rec.sent().is_empty(), "no signal may be sent");
}

// #11098: a `/proc` read that fails for a reason other than a vanished
// process (here EMFILE) once read every process as absent, so `stop` said
// `NotRunning` and `restart` started a second daemon.
#[test]
fn stop_fails_closed_when_the_scan_cannot_open_proc_files() {
    let fx = Fixture::new();
    let out = fx.path("out");
    let status = Command::new(std::env::current_exe().expect("current_exe"))
        .args(["--exact", "child_entry", "-q", ROLE_RUNNER, "emfile"])
        .arg(format!("install={}", fx.install.display()))
        .arg(format!("socket={}", fx.socket.display()))
        .arg(format!("marker={}", fx.path("marker").display()))
        .arg(format!("out={}", out.display()))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run runner");
    let report = fs::read_to_string(&out).unwrap_or_default();
    assert!(status.success(), "runner failed: {report}");
    assert!(
        report.starts_with("Err(Io") && report.contains("/status"),
        "expected an Io error on a status read, got {report}"
    );
}

// ─── #11085: the path flag, the restart pre-check, and stop/restart by pid ──

/// The fixture's stand-in for `--data-dir`; libtest reads it as a filter.
const DIR_FLAG: &str = "lc-dir";

/// The AC6 residual's shape: instance A serves `sock_a` in `dir_a`; the
/// sibling carries A's instance key (`SOCKET_ENV`) in its environment, as a
/// `--data-dir X` daemon with the data-dir variable unset does, but names
/// `dir_b` with [`DIR_FLAG`] and serves `sock_b`.
struct PathSiblings {
    fx: Fixture,
    marker: PathBuf,
    extra: Vec<String>,
    sock_a: PathBuf,
    sock_b: PathBuf,
}

impl PathSiblings {
    fn new() -> Self {
        let fx = Fixture::new();
        let marker = fx.path("marker");
        let extra = vec![format!("marker={}", marker.display())];
        let (sock_a, sock_b) = (fx.instance_socket("a"), fx.instance_socket("b"));
        Self {
            fx,
            marker,
            extra,
            sock_a,
            sock_b,
        }
    }

    fn dir(socket: &Path) -> PathBuf {
        socket.parent().expect("instance dir").to_path_buf()
    }

    /// Run the sibling and wait until it serves `sock_b`.
    fn sibling(&self) -> Running {
        let mut extra = self.extra.clone();
        extra.extend([
            format!("socket={}", self.sock_b.display()),
            DIR_FLAG.to_string(),
            Self::dir(&self.sock_b).display().to_string(),
        ]);
        let running = self.fx.launch(DAEMON, "serve", &self.sock_a, &extra);
        assert!(wait_serving(&self.sock_b), "the sibling never served");
        running
    }

    /// A's descriptor; `opt_in` declares [`DIR_FLAG`] with A's directory.
    fn desc_a(&self, opt_in: bool) -> DaemonDescriptor {
        let mut desc = self
            .fx
            .descriptor_at(StoppedSignal::SocketRefuses, &self.sock_a);
        desc.spawn_args = daemon_args("serve", &self.extra);
        if opt_in {
            desc.instance_path_args = vec![(DIR_FLAG.to_string(), Self::dir(&self.sock_a))];
        }
        desc
    }

    fn assert_sibling_untouched(&self, sibling: &Running) {
        assert!(is_alive(sibling.pid()), "the sibling was stopped");
        assert!(
            UnixStream::connect(&self.sock_b).is_ok(),
            "the sibling still serves"
        );
    }
}

/// Launch an unserved daemon (its socket bind "failed") on `socket`'s
/// instance and wait until it has started.
fn launch_unserved(fx: &Fixture, socket: &Path, name: &str, extra: &[String]) -> Running {
    let marker = fx.path(name);
    let mut args = vec![format!("marker={}", marker.display())];
    args.extend_from_slice(extra);
    let running = fx.launch(DAEMON, "never-bind", socket, &args);
    assert!(
        wait_for(|| !pid_lines(&marker).is_empty()),
        "{name}: the fixture never started"
    );
    running
}

// #11085 AC6: a sibling started as `--data-dir X` without the data-dir variable
// read as the default instance, so `stop` refused with `RunningUnserved`. The
// opt-in tells it apart; a process naming A's own dir is still A.
#[tokio::test]
async fn stop_tells_a_sibling_from_this_instance_by_its_path_flag() {
    let s = PathSiblings::new();
    let sibling = s.sibling();
    let rec = Recording::new(true);
    let residual = stop_with(&s.desc_a(false), &rec).await;
    let told_apart = stop_with(&s.desc_a(true), &rec).await;
    let own_dir = format!("{DIR_FLAG}={}", PathSiblings::dir(&s.sock_a).display());
    let own = launch_unserved(&s.fx, &s.sock_a, "own-marker", &[own_dir]);
    let refused = stop_with(&s.desc_a(true), &rec).await;

    assert!(
        matches!(&residual, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [sibling.pid()]),
        "precondition: without the opt-in the sibling reads as A, got {residual:?}"
    );
    assert_eq!(told_apart.expect("stop A"), StopOutcome::NotRunning);
    assert!(
        matches!(&refused, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [own.pid()]),
        "a process naming A's own dir is A, got {refused:?}"
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    s.assert_sibling_untouched(&sibling);
}

// #11085: with a sibling the scan reads as A, `restart` of a HEALTHY A stopped
// it, then `start` refused, and A stayed down. The refusal now comes first.
#[tokio::test]
async fn restart_refuses_before_any_signal_when_another_process_is_this_instance() {
    let s = PathSiblings::new();
    let a = s.fx.spawn_at(DAEMON, "serve", &s.sock_a, &s.extra);
    let sibling = s.sibling();
    let rec = Recording::new(true);
    let blocked = restart_with(&s.desc_a(false), &rec).await;
    std::thread::sleep(SPAWN_SETTLE);
    match &blocked {
        Err(LifecycleError::RestartBlocked {
            serving, others, ..
        }) => {
            assert_eq!(*serving, [a.pid()]);
            assert_eq!(*others, [sibling.pid()]);
        }
        other => panic!("expected RestartBlocked, got {other:?}"),
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(a.pid()), "A was stopped");
    assert!(UnixStream::connect(&s.sock_a).is_ok(), "A still serves");
    assert_eq!(pid_lines(&s.marker).len(), 2, "nothing was spawned");

    // With the opt-in the sibling is told apart, and the restart goes through.
    let out = restart(&s.desc_a(true)).await;
    let _reaps = s.fx.reap_reported(&s.marker);
    let out = out.expect("restart of A beside the told-apart sibling");
    assert_eq!(
        out.stop,
        StopOutcome::Stopped {
            pid: a.pid(),
            forced: false
        }
    );
    assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
    s.assert_sibling_untouched(&sibling);
    assert_eq!(
        stop(&s.desc_a(true)).await.expect("cleanup stop"),
        StopOutcome::Stopped {
            pid: out.start.pid,
            forced: false
        }
    );
}

// #11085 AC10: a daemon whose socket bind failed is unreachable through the
// socket — `stop` refuses on it — and is stopped through its pid.
#[tokio::test]
async fn stop_pid_stops_a_daemon_whose_socket_bind_failed() {
    let fx = Fixture::new();
    let mut d = launch_unserved(&fx, &fx.socket, "marker", &[]);
    let desc = fx.descriptor(StoppedSignal::SocketRefuses);
    let rec = Recording::new(true);
    let by_socket = stop_with(&desc, &rec).await;
    assert!(
        matches!(&by_socket, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
        "precondition: the socket path cannot reach it, got {by_socket:?}"
    );
    let pid = d.pid();
    assert_eq!(
        stop_pid_with(&desc, pid, &rec).await.expect("stop by pid"),
        StopOutcome::Stopped { pid, forced: false }
    );
    assert_eq!(rec.sent(), vec![Signal::Term]);
    assert!(
        d.child.try_wait().expect("try_wait").is_some(),
        "pid must have exited"
    );
}

// #11085 AC10: the pid a caller names is a hint. A pid that runs another
// binary, a bridge of this binary, or a sibling instance is never signalled,
// and the answer is an error, never `NotRunning`.
#[tokio::test]
async fn stop_pid_refuses_a_pid_that_is_not_this_instance() {
    let fx = Fixture::new();
    let own_dir = fx.path("own");
    fs::create_dir(&own_dir).expect("own dir");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.instance_path_args = vec![(DIR_FLAG.to_string(), own_dir)];
    desc.spawn_args = daemon_args(
        "serve",
        &[format!("marker={}", fx.path("spawned").display())],
    );
    let other_sock = fx.instance_socket("b");
    let other = fx.launch(OTHER, "never-bind", &fx.socket, &[]);
    let bridge = fx.launch_as(ROLE_BRIDGE, DAEMON, "never-bind", &fx.socket, &[]);
    let env_sibling = launch_unserved(&fx, &other_sock, "env-marker", &[]);
    let path_sibling = launch_unserved(
        &fx,
        &fx.socket,
        "path-marker",
        &[
            DIR_FLAG.to_string(),
            PathSiblings::dir(&other_sock).display().to_string(),
        ],
    );
    for pid in [other.pid(), bridge.pid()] {
        assert!(
            wait_for(|| fs::read_link(format!("/proc/{pid}/exe"))
                .is_ok_and(|e| e.starts_with(&fx.install))),
            "fixture {pid} never ran"
        );
    }
    let rec = Recording::new(true);
    match stop_pid_with(&desc, other.pid(), &rec).await {
        Err(LifecycleError::IdentityMismatch { pid, found, .. }) => {
            assert_eq!((pid, found.as_str()), (other.pid(), OTHER));
        }
        out => panic!("another binary: expected IdentityMismatch, got {out:?}"),
    }
    for (what, pid) in [
        ("a bridge", bridge.pid()),
        ("an env sibling", env_sibling.pid()),
        ("a path sibling", path_sibling.pid()),
    ] {
        let stopped = stop_pid_with(&desc, pid, &rec).await;
        let restarted = restart_pid_with(&desc, pid, &rec).await;
        for (call, out) in [
            ("stop_pid", stopped.map(|o| format!("{o:?}"))),
            ("restart_pid", restarted.map(|o| format!("{o:?}"))),
        ] {
            assert!(
                matches!(&out, Err(LifecycleError::NotThisInstance { pid: p, .. }) if *p == pid),
                "{what}: {call}: expected NotThisInstance, got {out:?}"
            );
        }
    }
    std::thread::sleep(SPAWN_SETTLE);
    assert!(lines(&fx.path("spawned")).is_empty(), "restart_pid spawned");
    assert!(rec.sent().is_empty(), "no signal may be sent");
    for pid in [
        other.pid(),
        bridge.pid(),
        env_sibling.pid(),
        path_sibling.pid(),
    ] {
        assert!(is_alive(pid), "pid {pid} is untouched");
    }
}

// #11085: a stale pid (a pid file or address that outlived its daemon) proves
// nothing. The shortcut "the pid is gone ⇒ NotRunning" misses a daemon of this
// instance that runs under another pid.
#[tokio::test]
async fn stop_pid_of_a_pid_that_is_gone_answers_as_stop_does() {
    let fx = Fixture::new();
    let mut gone = fx.launch(DAEMON, "exit-now", &fx.socket, &[]);
    gone.child.wait().expect("reap the exited fixture");
    let stale = gone.pid();
    let desc = fx.descriptor(StoppedSignal::SocketRefuses);
    let rec = Recording::new(true);
    assert_eq!(
        stop_pid_with(&desc, stale, &rec)
            .await
            .expect("nothing runs"),
        StopOutcome::NotRunning
    );
    let d = launch_unserved(&fx, &fx.socket, "marker", &[]);
    let out = stop_pid_with(&desc, stale, &rec).await;
    assert!(
        matches!(&out, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
        "expected RunningUnserved naming pid {}, got {out:?}",
        d.pid()
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(d.pid()), "the daemon is untouched");
}

// #11085 AC10, D1: restart by pid stops the unserved daemon, proves it gone,
// and starts one that serves.
#[tokio::test]
async fn restart_pid_restarts_a_daemon_whose_socket_bind_failed() {
    let fx = Fixture::new();
    let d = launch_unserved(&fx, &fx.socket, "old-marker", &[]);
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let out = restart_pid(&desc, d.pid()).await;
    let mut reaps = fx.reap_reported(&marker);
    let out = out.expect("restart by pid");
    assert_eq!(
        out.stop,
        StopOutcome::Stopped {
            pid: d.pid(),
            forced: false
        }
    );
    let new = out.start.pid;
    assert_eq!(pid_lines(&marker), vec![new.to_string()], "one new daemon");
    assert!(UnixStream::connect(&fx.socket).is_ok(), "it serves");
    assert!(!is_alive(d.pid()), "the old daemon is gone");
    assert_eq!(
        stop_pid(&desc, new).await.expect("cleanup stop"),
        StopOutcome::Stopped {
            pid: new,
            forced: false
        }
    );
    reaps.iter_mut().for_each(Reap::disarm);
}

// #11085: two processes of this instance; restarting one by pid would stop it
// and then the start would refuse on the other.
#[tokio::test]
async fn restart_pid_refuses_before_any_signal_when_another_process_is_this_instance() {
    let fx = Fixture::new();
    let d = launch_unserved(&fx, &fx.socket, "d-marker", &[]);
    let twin = launch_unserved(&fx, &fx.socket, "twin-marker", &[]);
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let rec = Recording::new(true);
    let out = restart_pid_with(&desc, d.pid(), &rec).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);
    match &out {
        Err(LifecycleError::RestartBlocked {
            serving, others, ..
        }) => {
            assert_eq!(*serving, [d.pid()]);
            assert_eq!(*others, [twin.pid()]);
        }
        other => panic!("expected RestartBlocked, got {other:?}"),
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(lines(&marker).is_empty(), "nothing was spawned");
    assert!(is_alive(d.pid()) && is_alive(twin.pid()), "both untouched");
}

// #11085 AC2 by pid: a survivor fails the stop, and the restart starts nothing.
#[tokio::test]
async fn stop_pid_reports_a_survivor_and_restart_pid_starts_nothing() {
    let fx = Fixture::new();
    let d = fx.spawn(DAEMON, "ignore-term", &[]);
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    desc.stop_grace = Duration::from_millis(200);
    desc.kill_wait = Duration::from_millis(300);
    let stopped = stop_pid_with(&desc, d.pid(), &Recording::new(false)).await;
    let restarted = restart_pid_with(&desc, d.pid(), &Recording::new(false)).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);
    for (call, out) in [
        ("stop_pid", stopped.map(|o| format!("{o:?}"))),
        ("restart_pid", restarted.map(|o| format!("{o:?}"))),
    ] {
        assert!(
            matches!(&out, Err(LifecycleError::Survivor { pid }) if *pid == d.pid()),
            "{call}: expected Survivor, got {out:?}"
        );
    }
    assert!(lines(&marker).is_empty(), "nothing was spawned");
    assert!(is_alive(d.pid()), "the survivor still runs");
}

// #11085: the scan counts an undecided path flag as this instance and refuses,
// but a stop by pid must not signal a process nobody proved is this instance.
// Empty `liveness_args` lets every process of the binary pass, so it refuses.
#[tokio::test]
async fn stop_pid_and_restart_pid_refuse_an_undecided_instance_before_any_signal() {
    let fx = Fixture::new();
    let own_dir = fx.path("own");
    fs::create_dir(&own_dir).expect("own dir");
    let spawned = fx.path("spawned");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.instance_path_args = vec![(DIR_FLAG.to_string(), own_dir)];
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", spawned.display())]);
    let mut no_liveness = fx.descriptor(StoppedSignal::SocketRefuses);
    no_liveness.liveness_args.clear();
    no_liveness.spawn_args = desc.spawn_args.clone();
    let flag = |value: &str| vec![DIR_FLAG.to_string(), value.to_string()];
    let missing = fx.path("missing").display().to_string();
    let relative = launch_unserved(&fx, &fx.socket, "rel-marker", &flag("own"));
    let unresolvable = launch_unserved(&fx, &fx.socket, "abs-marker", &flag(&missing));
    let no_value = launch_unserved(&fx, &fx.socket, "none-marker", &[DIR_FLAG.to_string()]);
    let plain = launch_unserved(&fx, &fx.socket, "plain-marker", &[]);
    let rec = Recording::new(true);
    let mut results = Vec::new();
    for (what, d, pid, undecided) in [
        ("a relative value", &desc, relative.pid(), true),
        ("an unresolvable value", &desc, unresolvable.pid(), true),
        ("no value", &desc, no_value.pid(), true),
        ("empty liveness_args", &no_liveness, plain.pid(), false),
    ] {
        let stopped = stop_pid_with(d, pid, &rec).await.map(|o| format!("{o:?}"));
        let restarted = restart_pid_with(d, pid, &rec)
            .await
            .map(|o| format!("{o:?}"));
        results.push((what, pid, undecided, stopped, restarted));
    }
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&spawned);
    for (what, pid, undecided, stopped, restarted) in results {
        for (call, out) in [("stop_pid", stopped), ("restart_pid", restarted)] {
            let refused = match &out {
                Err(LifecycleError::InstanceUndecided { pid: p, flag, .. }) => {
                    undecided && *p == pid && flag == DIR_FLAG
                }
                Err(LifecycleError::InvalidDescriptor { .. }) => !undecided,
                _ => false,
            };
            assert!(refused, "{what}: {call}: expected a refusal, got {out:?}");
        }
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(lines(&spawned).is_empty(), "restart_pid spawned");
    for pid in [
        relative.pid(),
        unresolvable.pid(),
        no_value.pid(),
        plain.pid(),
    ] {
        assert!(is_alive(pid), "pid {pid} is untouched");
    }
}

// #11085: P is this instance but unserved; Q serves the socket. A restart of
// P stopped P and then `start` found Q serving, so the daemon reached by pid
// was down and nothing started; a stop of P could not reach the stopped
// signal. Both now refuse before any signal. Q runs another binary, so the
// `/proc` scan does not count it and only the socket check can refuse.
#[tokio::test]
async fn stop_pid_and_restart_pid_refuse_before_any_signal_when_another_pid_serves_the_socket() {
    let fx = Fixture::new();
    let p = launch_unserved(&fx, &fx.socket, "p-marker", &[]);
    let q = fx.spawn(OTHER, "serve", &[]);
    let marker = fx.path("marker");
    let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let rec = Recording::new(true);
    let restarted = restart_pid_with(&desc, p.pid(), &rec).await;
    let stopped = stop_pid_with(&desc, p.pid(), &rec).await;
    std::thread::sleep(SPAWN_SETTLE);
    let _reaps = fx.reap_reported(&marker);
    match &restarted {
        Err(LifecycleError::RestartBlocked {
            serving, others, ..
        }) => {
            assert_eq!(*serving, [p.pid()]);
            assert_eq!(*others, [q.pid()]);
        }
        other => panic!("restart_pid: expected RestartBlocked, got {other:?}"),
    }
    assert!(
        matches!(&stopped, Err(LifecycleError::ServedByAnother { pid, peer, .. })
            if (*pid, *peer) == (p.pid(), q.pid())),
        "stop_pid: expected ServedByAnother, got {stopped:?}"
    );
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(lines(&marker).is_empty(), "nothing was spawned");
    assert!(is_alive(p.pid()) && is_alive(q.pid()), "both untouched");
    assert!(UnixStream::connect(&fx.socket).is_ok(), "Q still serves");
}

// #11085: a socket that cannot be probed may be served by another pid, so a
// stop or restart by pid refuses before any signal.
#[tokio::test]
async fn stop_pid_and_restart_pid_stop_short_when_the_socket_cannot_be_probed() {
    let fx = Fixture::new();
    let dir = fx.path("locked");
    fs::create_dir(&dir).expect("socket dir");
    let socket = dir.join("d.sock");
    let p = launch_unserved(&fx, &socket, "p-marker", &[]);
    let marker = fx.path("marker");
    let mut desc = fx.descriptor_at(StoppedSignal::SocketRefuses, &socket);
    desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
    let guard = ModeGuard::lock(&dir);
    let probe = UnixStream::connect(&socket).map(drop);
    assert!(
        matches!(&probe, Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
        "fixture precondition: connect is refused with EACCES, got {probe:?}"
    );
    let rec = Recording::new(true);
    let restarted = restart_pid_with(&desc, p.pid(), &rec)
        .await
        .map(|o| format!("{o:?}"));
    let stopped = stop_pid_with(&desc, p.pid(), &rec)
        .await
        .map(|o| format!("{o:?}"));
    std::thread::sleep(SPAWN_SETTLE);
    drop(guard);
    let _reaps = fx.reap_reported(&marker);
    for (call, out) in [("restart_pid", restarted), ("stop_pid", stopped)] {
        assert!(
            matches!(&out, Err(LifecycleError::ProbeInconclusive { socket: s }) if *s == socket),
            "{call}: expected ProbeInconclusive, got {out:?}"
        );
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(lines(&marker).is_empty(), "nothing was spawned");
    assert!(is_alive(p.pid()), "the daemon is untouched");
}

// #11085: mid-upgrade the install binary is briefly absent. A restart that
// found that only at its start had already stopped the healthy daemon.
#[tokio::test]
async fn restart_and_restart_pid_stop_nothing_when_the_install_binary_is_missing() {
    let fx = Fixture::new();
    let d = fx.spawn(DAEMON, "serve", &[]);
    let desc = fx.descriptor(StoppedSignal::SocketRefuses);
    let program = fx.install.join(DAEMON);
    fs::remove_file(&program).expect("remove the install binary");
    let rec = Recording::new(true);
    let restarted = restart_with(&desc, &rec).await.map(|o| format!("{o:?}"));
    let by_pid = restart_pid_with(&desc, d.pid(), &rec)
        .await
        .map(|o| format!("{o:?}"));
    for (call, out) in [("restart", restarted), ("restart_pid", by_pid)] {
        assert!(
            matches!(&out, Err(LifecycleError::BinaryMissing { path }) if *path == program),
            "{call}: expected BinaryMissing, got {out:?}"
        );
    }
    assert!(rec.sent().is_empty(), "no signal may be sent");
    assert!(is_alive(d.pid()), "the daemon still runs");
    assert!(UnixStream::connect(&fx.socket).is_ok(), "it still serves");
}