cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
//! Windows Job Object containment: the root spawns suspended into a new console
//! group, is immediately assigned to a `KILL_ON_JOB_CLOSE` job, then resumed.
//! The kernel enforces the invariant: every descendant of the child inherits the
//! job (Windows jobs nest, so inner jobs are not a problem), and closing the job
//! handle terminates the whole tree.
//!
//! Kill-group race invariant (why `CREATE_SUSPENDED`):
//! the child must be inside the job before executing any instruction — otherwise
//! a fast-forking grandchild can escape the job before assignment completes.
//! Suspending the initial thread closes the race: assign the job while the child
//! is frozen, then resume so it can run.

use std::io;
use std::mem::size_of;
use std::ops::ControlFlow;
use std::os::windows::io::{AsRawHandle as _, BorrowedHandle};
use std::sync::atomic::{AtomicU32, Ordering};

use windows::Win32::Foundation::{
    CloseHandle, SetHandleInformation, HANDLE, HANDLE_FLAGS, HANDLE_FLAG_INHERIT, WAIT_FAILED, WAIT_OBJECT_0,
    WAIT_TIMEOUT,
};
use windows::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE};
use windows::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation, JobObjectBasicProcessIdList,
    JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject, TerminateJobObject,
    JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{
    GetProcessId, GetProcessIdOfThread, OpenProcess, OpenThread, ResumeThread, WaitForMultipleObjects,
    CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
    THREAD_QUERY_LIMITED_INFORMATION, THREAD_SUSPEND_RESUME,
};

use crate::containment::tree_kill::{Settled, Unnamed};
use crate::error::{io_context, win32_io_error};
use crate::identity::ProcessId;

/// Owns the Job Object handle. `KILL_ON_JOB_CLOSE` means the whole process tree
/// is terminated when this handle is closed (by `Drop`, unless [`disarm`](JobHandle::disarm)ed).
///
/// The handle stays open from construction until `Drop`, which needs `&mut self`: no `&self`
/// method can run while it closes, so none can see a recycled handle value.
pub(crate) struct JobHandle {
    raw: HANDLE,
    /// The job's [`JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::TotalProcesses`] as of the last drain whose
    /// confirmation waited for every member ([`confirm_drained`]); `0` before one. A process the job
    /// ever had counts, wherever it came from, and the count never falls, so an empty listing at the
    /// same count has no process that was not confirmed.
    confirmed: AtomicU32,
}

// A Windows job-object HANDLE is a process-wide kernel handle; using it
// (TerminateJobObject / SetInformationJobObject / ...) from another thread is sound because the
// kernel serialises job operations. The raw pointer inside `HANDLE` is otherwise
// `!Send`, which would prevent this type from crossing thread boundaries.
unsafe impl Send for JobHandle {}

// SAFETY: `raw` is never written after construction, and the job operations are serialised by
// the kernel.
unsafe impl Sync for JobHandle {}

impl std::fmt::Debug for JobHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JobHandle").field("raw", &self.raw.0).finish()
    }
}

impl JobHandle {
    fn new(handle: HANDLE) -> Self {
        debug_assert!(!handle.0.is_null(), "job handle must not be null");
        JobHandle {
            raw: handle,
            confirmed: AtomicU32::new(0),
        }
    }

    /// The job handle, open for as long as `self` is borrowed.
    pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
        // SAFETY: `self.raw` is open until `Drop`, which needs `&mut self`.
        unsafe { BorrowedHandle::borrow_raw(self.raw.0) }
    }

    /// Terminate every process in the job. The handle stays open, so the job can still be
    /// waited on ([`wait_drained`](JobHandle::wait_drained)) and disarmed; it closes in `Drop`.
    ///
    /// Returns the `TerminateJobObject` failure rather than only logging it: a caller that is
    /// told teardown succeeded while the tree is still running has no way to notice, and the
    /// other containment mechanisms already report this.
    pub(crate) fn hard_kill(&self) -> io::Result<()> {
        #[cfg(test)]
        {
            fault::run_before_job_kill();
            forced(fault::Step::JobKill, None).map_err(win32_io_error)?;
        }
        // SAFETY: `self.raw` is a valid handle we own for as long as `self` lives.
        unsafe { TerminateJobObject(self.raw, 1) }.map_err(win32_io_error)
    }

    /// Clear `KILL_ON_JOB_CLOSE` so closing this handle does NOT kill the tree.
    /// Called by `Child::detach()` before the handle is released: otherwise
    /// dropping the job handle terminates the tree the caller intended to keep alive.
    ///
    /// Returns the `SetInformationJobObject` failure, with the plain Win32 code: the flag is then
    /// still set, and closing this handle still kills the tree.
    pub(crate) fn disarm(&self) -> io::Result<()> {
        // A zeroed JOBOBJECT_EXTENDED_LIMIT_INFORMATION has LimitFlags == 0, which
        // clears KILL_ON_JOB_CLOSE.
        let info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
        // SAFETY: `self.raw` is a valid handle; info is fully initialised (zeroed by default()).
        unsafe {
            SetInformationJobObject(
                self.raw,
                JobObjectExtendedLimitInformation,
                std::ptr::addr_of!(info).cast(),
                size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
            )
        }
        .map_err(win32_io_error)
    }
}

#[cfg(all(windows, test))]
impl JobHandle {
    /// Test-only: a real but empty job object (no process assigned). Cheap to create and
    /// cleanly closed on `Drop`; for variant-level assertions like
    /// `Tree::contained(Mechanism::Job(_))`.
    pub(crate) fn create_empty_for_test() -> JobHandle {
        // Safety: CreateJobObjectW with null name/attrs returns an owned job handle.
        let handle = unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) }
            .expect("CreateJobObjectW for test placeholder");
        JobHandle::new(handle)
    }

    /// Test-only: assign the process at `process` to this job, beside its members.
    pub(crate) fn assign_for_test(&self, process: std::os::windows::io::RawHandle) -> io::Result<()> {
        // SAFETY: a standard Win32 call on handles the caller keeps open across it.
        unsafe { AssignProcessToJobObject(self.raw, HANDLE(process.cast())) }.map_err(win32_io_error)
    }

    /// Test-only: an empty job reached through a handle without `JOB_OBJECT_SET_ATTRIBUTES`, so the
    /// OS refuses `SetInformationJobObject` on it with `ERROR_ACCESS_DENIED`: a real refusal of
    /// `disarm`, which a handle the crate made itself never gives.
    pub(crate) fn create_without_set_access_for_test() -> JobHandle {
        use windows::Win32::System::SystemServices::{JOB_OBJECT_QUERY, JOB_OBJECT_TERMINATE};

        JobHandle::create_empty_for_test().duplicate_with_access_for_test(JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE)
    }

    /// Test-only: another handle to this job with only `access`: without `JOB_OBJECT_TERMINATE` the
    /// OS refuses `TerminateJobObject` on it with `ERROR_ACCESS_DENIED` while the job and its members
    /// live on, and without `JOB_OBJECT_QUERY` it cannot list them.
    pub(crate) fn duplicate_with_access_for_test(&self, access: u32) -> JobHandle {
        use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_HANDLE_OPTIONS};
        use windows::Win32::System::Threading::GetCurrentProcess;

        let mut weak = HANDLE::default();
        // SAFETY: `self`'s handle is live; `weak` is an out-parameter.
        unsafe {
            DuplicateHandle(
                GetCurrentProcess(),
                self.raw,
                GetCurrentProcess(),
                &mut weak,
                access,
                false,
                DUPLICATE_HANDLE_OPTIONS(0),
            )
        }
        .expect("DuplicateHandle with reduced access");
        JobHandle::new(weak)
    }
}

impl Drop for JobHandle {
    fn drop(&mut self) {
        // If `disarm` did not clear the flag, KILL_ON_JOB_CLOSE fires here when we close the
        // handle, tearing down the tree — the drop backstop for `kill_on_drop=true` semantics.
        // `hard_kill` terminates every member, including a child created during it, so this close
        // only reaps what an explicit post-kill assignment added. Whether a killed job accepts one
        // varies by Windows build (accepted on 10.0.26100, ACCESS_DENIED on the CI's Windows arm64
        // runner); cosca makes none.
        // SAFETY: `self.raw` is a valid handle we own, closed only here.
        unsafe {
            if let Err(e) = CloseHandle(self.raw) {
                // The close IS the teardown here: with KILL_ON_JOB_CLOSE still set, a
                // failed close means the tree was never reaped and the handle leaked.
                // Drop cannot report that, so it must at least be visible.
                log::warn!(
                    "closing the job handle failed ({report}); the tree may still be running",
                    report = crate::error::Report(&e)
                );
            }
        }
    }
}

impl JobHandle {
    /// The processes the job lists now, for the wait over a kill that follows: each is opened and
    /// proved a member through its own handle ([`member_to_watch`]), and its identity is read from
    /// that handle, which is then closed, so no handle is held per member. It is read before
    /// `TerminateJobObject`: the job's list is empty on its first read after the kill, whether or not
    /// the members have exited, so a list read after the kill would miss them. A member that exited
    /// naturally can be named by a listing begun before its exit, so [`wait_drained_raw`] lists again
    /// and a drain is only an empty listing. `root`, the root's pid, is left out: its owner waits for
    /// it. A member that cannot be named, or the listing itself failing, is returned as an error
    /// saying its exit cannot be observed, with its pid where it has one; the kill goes ahead
    /// regardless. A pid whose membership cannot be established is dropped if the listing taken right
    /// after does not name it again, else returned as unobserved (the rule of [`drain_round`], see
    /// [`settle_unproved`]). If that settling listing fails, the members proved are still returned,
    /// and `unobserved` holds each unproved pid (with its refusal) and one nameless entry for the
    /// failed listing.
    pub(crate) fn list_members(&self, root: Option<u32>) -> (Vec<ProcessId>, Vec<Unnamed>) {
        use crate::error::Error;

        let pids = match query_job_pid_list(self.raw) {
            Ok(pids) => pids,
            Err(e) => {
                let detail =
                    "the members of the job could not be listed before the kill, so their exit cannot be observed";
                return (Vec::new(), vec![unlisted(detail, e)]);
            }
        };
        let mut found = Listed::default();
        for pid in pids.into_iter().filter(|pid| Some(*pid) != root) {
            found.look(self.raw, pid, false);
        }
        let unproved = std::mem::take(&mut found.unproved);
        if unproved.is_empty() {
            return (found.members, found.unobserved);
        }
        match settle_unproved(self.raw, &unproved) {
            Err(e) => {
                // The members proved are waited for; these are neither named nor cleared.
                let detail = "the members of the job were listed, but the listing that settles the pids whose \
                              membership could not be established failed, so whether those exited cannot be observed";
                found.unobserved.push(unlisted(detail, e));
                found
                    .unobserved
                    .extend(unproved.into_iter().map(|(pid, e)| Unnamed::member(pid, Error::Io(e))));
            }
            Ok(ControlFlow::Break(())) => {}
            Ok(ControlFlow::Continue(named)) => {
                for pid in named {
                    found.look(self.raw, pid, true);
                }
            }
        }
        (found.members, found.unobserved)
    }
}

/// What [`JobHandle::list_members`] has made of the pids it looked at.
#[derive(Default)]
struct Listed {
    members: Vec<ProcessId>,
    unobserved: Vec<Unnamed>,
    /// Pids whose membership could not be established on the first look, each with the reason.
    unproved: Vec<(u32, io::Error)>,
}

impl Listed {
    /// Look at the listed pid `pid`. `settling`: the pid is one the settling listing named again
    /// ([`settle_unproved`]), so one still unproved is unobserved, not left to settle.
    fn look(&mut self, job: HANDLE, pid: u32, settling: bool) {
        use crate::error::Error;

        match member_identity(job, pid, open_for_membership(pid)) {
            Ok(Some(id)) => self.members.push(id),
            Ok(None) => {}
            Err(NotNamed::Membership(e)) if settling => self.unobserved.push(Unnamed::member(pid, Error::Io(e))),
            Err(NotNamed::Membership(e)) => self.unproved.push((pid, e)),
            Err(NotNamed::Identity(cause)) => self.unobserved.push(Unnamed::member(pid, cause)),
        }
    }
}

/// A failed listing of the job's members before a kill: `detail` says which, and that the members it
/// would have named cannot be waited for.
fn unlisted(detail: &str, cause: io::Error) -> Unnamed {
    Unnamed::nameless(crate::error::Error::Unassessable {
        detail: detail.to_owned(),
        source: Some(crate::error::Error::io_cause(cause)),
    })
}

/// `OpenProcess` for what proving membership and reading the identity need, and no more:
/// `PROCESS_QUERY_LIMITED_INFORMATION` is what `IsProcessInJob` needs, and the least right that
/// does, grantable across integrity levels. Whether the caller may also wait on a member is the wait's
/// own open's question, so a member it may not wait on is still a member. The handle is the caller's to close, or to pass to
/// [`member_to_watch`] or [`member_identity`], which close it unless they return it.
fn open_for_membership(pid: u32) -> windows::core::Result<HANDLE> {
    // SAFETY: a standard Win32 call with no borrowed arguments.
    unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
}

/// [`open_for_membership`] with `PROCESS_SYNCHRONIZE` too, for the handle a round's any-wait blocks
/// on. Closed or passed on as that one is.
fn open_for_wait(pid: u32) -> windows::core::Result<HANDLE> {
    #[cfg(test)]
    forced(fault::Step::WaitOpen, Some(pid))?;
    // SAFETY: a standard Win32 call with no borrowed arguments.
    unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
}

/// Why a process was not named a member of a job by its identity.
enum NotNamed {
    /// Whether it is a member could not be established: the open was refused, or `IsProcessInJob`
    /// failed.
    Membership(io::Error),
    /// It is a member, and its start time could not be read.
    Identity(crate::error::Error),
}

/// The identity of the process `OpenProcess` returned as `opened`, if it is a member of `job`; `None`
/// if it is not one (its pid is gone or was reused). The handle is closed on every path. A process
/// that is not shown to be a member, or a member that cannot be identified, is [`NotNamed`] for that
/// reason, which a caller treats by what it knows of the pid.
fn member_identity(
    job: HANDLE,
    pid: u32,
    opened: windows::core::Result<HANDLE>,
) -> Result<Option<ProcessId>, NotNamed> {
    use crate::error::Error;

    #[cfg(test)]
    if let Err(e) = forced(fault::Step::Membership, Some(pid)) {
        if let Ok(handle) = opened {
            // SAFETY: opened by the caller and kept nowhere else.
            _ = unsafe { CloseHandle(handle) };
        }
        return Err(NotNamed::Membership(win32_io_error(e)));
    }
    let handle = match member_to_watch(opened, job) {
        Standing::Member(handle) => handle,
        Standing::NotMember => return Ok(None),
        Standing::Unproved(e) => return Err(NotNamed::Membership(e)),
    };
    let id = crate::identity::windows_identity_from_handle_result(handle, pid);
    #[cfg(test)]
    let id = forced(fault::Step::Identity, Some(pid)).and(id);
    // SAFETY: opened by the caller and kept nowhere else.
    _ = unsafe { CloseHandle(handle) };
    id.map(Some).map_err(|e| {
        NotNamed::Identity(Error::Unassessable {
            detail: "its start time could not be read".to_owned(),
            source: Some(Error::io_cause(win32_io_error(e))),
        })
    })
}

impl crate::containment::Contains for JobHandle {
    /// `Ok` says the job was told to terminate every member, however it was spawned (see
    /// [`hard_kill`](JobHandle::hard_kill)). See [`list_members`](JobHandle::list_members) for what
    /// is named and why.
    fn kill(&self, root: Option<&dyn crate::containment::Root>) -> crate::containment::TreeKill<'_> {
        let (members, unobserved) = self.list_members(root.map(crate::containment::Root::pid));
        let sent = crate::containment::Contains::send_kill(self, root);
        crate::containment::TreeKill::listed(
            sent,
            members,
            unobserved,
            crate::containment::drain_edge::DrainEdge::Job(self),
        )
    }

    /// The bare `TerminateJobObject`: no member is listed, for a caller that waits for none.
    fn send_kill(&self, _root: Option<&dyn crate::containment::Root>) -> crate::containment::dispatch::TreeKillOutcome {
        use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
        TreeKillOutcome::Ran(
            self.hard_kill()
                .map_err(|e| crate::error::Error::Containment {
                    detail: "TerminateJobObject could not terminate the job".to_owned(),
                    source: Some(crate::error::Error::io_cause(e)),
                })
                .map_err(Unkilled::from),
        )
    }

    /// `CTRL_BREAK` to the root's console group `pid`: a nested contained descendant leads its own
    /// group and never receives it.
    fn send_terminate(
        &self,
        pid: u32,
        _root: Option<&dyn crate::containment::Root>,
    ) -> (
        crate::containment::TerminateOutcome,
        Option<crate::containment::treewalk::Listing>,
    ) {
        // One event, so an error is an event that was not sent (`NoConsole` or the OS's refusal).
        let sent = crate::containment::TerminateOutcome::of(terminate(pid).map(Ok), Some("the SIGTERM"));
        (sent, None)
    }

    fn drain_edge(&self) -> Option<crate::containment::drain_edge::DrainEdge<'_>> {
        Some(crate::containment::drain_edge::DrainEdge::Job(self))
    }

    fn kind(&self) -> crate::containment::Containment {
        crate::containment::Containment::JobObject
    }

    /// Clears `KILL_ON_JOB_CLOSE` (see [`disarm`](JobHandle::disarm)).
    fn disarm(&self) -> io::Result<()> {
        JobHandle::disarm(self)
    }
}

/// Pre-spawn creation flags for a root spawn.
/// `CREATE_SUSPENDED`: child must not execute before it is inside the job.
/// `CREATE_NEW_PROCESS_GROUP`: child leads its own console group so
/// `GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid)` can target it.
/// Shared by the std path and the raw `CreateProcessW` backend via `windows_contain_setup`.
/// What this word implies about cooperative shutdown is derived by [`mechanism_from_flags`].
pub(crate) fn root_flags() -> u32 {
    CREATE_SUSPENDED.0 | CREATE_NEW_PROCESS_GROUP.0
}

/// Pre-spawn creation flags for a nested (non-root) spawn.
/// Only `CREATE_NEW_PROCESS_GROUP` — no suspension needed for nested spawns.
/// What this word implies about cooperative shutdown is derived by [`mechanism_from_flags`].
pub(crate) fn group_flags() -> u32 {
    CREATE_NEW_PROCESS_GROUP.0
}

/// Which cooperative signal a child spawned with `creation_flags` can be sent, derived from the
/// flag word the spawn actually passed to `CreateProcessW`.
///
/// Three rows:
///
/// - `CREATE_NEW_PROCESS_GROUP` absent → [`GracefulMechanism::None`]. The child sits in the
///   spawner's group, so no console control event can ever be addressed to it individually by
///   any process, and group leadership cannot be changed after creation. This is the one flat
///   negative the flag word settles absolutely.
/// - the group flag set, and none of `DETACHED_PROCESS` / `CREATE_NEW_CONSOLE` /
///   `CREATE_NO_WINDOW` → [`GracefulMechanism::ConsoleGroup`].
/// - the group flag set together with any of those three → [`GracefulMechanism::OtherConsoleGroup`].
///
/// What the results do **not** mean. `ConsoleGroup` says the flags do not *exclude* in-process
/// delivery — it is not a claim the child is reachable. Console membership is not a function of
/// the flag word at all: a GUI-subsystem image never attaches to the spawner's console whatever
/// the flags say, and any child may `FreeConsole`/`AllocConsole`/`AttachConsole` after it starts.
/// An out-of-console group makes `GenerateConsoleCtrlEvent` report success while delivering
/// nothing, which is why the split exists. And `OtherConsoleGroup` is not "unreachable": a child
/// spawned with window suppression owns a *private* console a helper process can attach to, so
/// the claim is about the route from here, never a verdict on the child.
///
/// Any future creation-flag surface must extend this one function rather than deriving a
/// mechanism of its own.
pub(crate) fn mechanism_from_flags(creation_flags: u32) -> crate::graceful::GracefulMechanism {
    use crate::graceful::GracefulMechanism;
    use windows::Win32::System::Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW, DETACHED_PROCESS};

    if creation_flags & CREATE_NEW_PROCESS_GROUP.0 == 0 {
        return GracefulMechanism::None;
    }
    let out_of_console = DETACHED_PROCESS.0 | CREATE_NEW_CONSOLE.0 | CREATE_NO_WINDOW.0;
    if creation_flags & out_of_console != 0 {
        return GracefulMechanism::OtherConsoleGroup;
    }
    GracefulMechanism::ConsoleGroup
}

/// Clear the inherit flag on the parent's std handles before spawning. Prevents
/// the child from inheriting the test runner's console handles. Best-effort.
pub(crate) fn clear_std_handle_inheritance() {
    for std_handle in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
        // SAFETY: standard Win32 call; handle is not closed.
        unsafe {
            if let Ok(h) = GetStdHandle(std_handle) {
                if !h.is_invalid() {
                    // Clear the INHERIT flag; dwflags=0 means "clear all bits in mask".
                    _ = SetHandleInformation(h, HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0));
                }
            }
        }
    }
    #[cfg(test)]
    observe::record_inheritance_cleared();
}

/// Whether THIS process is attached to a console: `Ok(true)` attached, `Ok(false)` genuinely
/// none, `Err` the probe itself failed.
///
/// `GetConsoleProcessList` returns 0 both for "no console" and for an API-level failure, so
/// the two are told apart by the last OS error: a console-less caller gets 0 with
/// `ERROR_INVALID_HANDLE`. Unlike `GetConsoleWindow` this is correct for a *windowless*
/// console (`CREATE_NO_WINDOW`, ConPTY), which can signal fine.
///
/// Used only to CONFIRM a failure that already happened, never to gate one before it. Both
/// orderings race a concurrent `AttachConsole`/`FreeConsole`; a confirmation at worst
/// withholds the typed error, while a guard decides the outcome from state that may already
/// be gone.
pub(crate) fn caller_has_console() -> io::Result<bool> {
    use windows::Win32::Foundation::{SetLastError, ERROR_INVALID_HANDLE, WIN32_ERROR};
    use windows::Win32::System::Console::GetConsoleProcessList;
    #[cfg(test)]
    if fault::take_force_console_probe_error() {
        return Err(io::Error::from_raw_os_error(
            windows::Win32::Foundation::ERROR_INVALID_PARAMETER.0 as i32,
        ));
    }
    let mut list = [0u32; 1];
    // SAFETY: both calls are standard Win32; `list` is a valid writable slice. A buffer
    // smaller than the attached-process count is fine — the return is then the required
    // count, and only "is it zero" is read here. The last error is cleared first: a zero
    // return is only meaningful together with the code THIS call set, and the live caller
    // reaches here right after a `GenerateConsoleCtrlEvent` that itself failed with
    // `ERROR_INVALID_HANDLE` — reading that stale value would let the probe "confirm" an
    // absence it never measured.
    let n = unsafe {
        SetLastError(WIN32_ERROR(0));
        GetConsoleProcessList(&mut list)
    };
    if n != 0 {
        return Ok(true);
    }
    let err = io::Error::last_os_error();
    if err.raw_os_error() == Some(ERROR_INVALID_HANDLE.0 as i32) {
        Ok(false)
    } else {
        Err(err)
    }
}

/// Classify a `GenerateConsoleCtrlEvent` failure. Pure — the Win32 result and the console
/// probe are both parameters — so every arm is unit-testable without hooking the OS calls the
/// live path depends on (the same injection idiom as `treewalk::descendants_with`).
///
/// `err` carries the bare Win32 code (see [`win32_io_error`]).
///
/// `Error::NoConsole` is returned ONLY when the failure code matches AND the probe confirms
/// there is no console. A contradicted probe, a failed probe, or any other failure code keeps
/// the raw `Error::Io`: the typed variant must never assert a cause the process just measured
/// to be false.
pub(crate) fn classify_ctrl_event_failure(pid: u32, err: io::Error, console: io::Result<bool>) -> crate::error::Error {
    use windows::Win32::Foundation::ERROR_INVALID_HANDLE;
    let no_console = ERROR_INVALID_HANDLE.0 as i32;
    if err.raw_os_error() == Some(no_console) && matches!(console, Ok(true)) {
        // warn, not debug: the crate's core mapping (this code <=> no console) was just
        // contradicted. Either another thread attached a console in the confirmation gap, or
        // the mapping does not hold on this host — both deserve to be visible, and neither
        // may be reported as an ordinary Io passthrough without a trace.
        log::warn!(
            "CTRL_BREAK to group {pid} failed with ERROR_INVALID_HANDLE, but a console is \
             attached; surfacing the raw error rather than claiming NoConsole"
        );
        return crate::error::Error::Io(err);
    }
    if err.raw_os_error() == Some(no_console) {
        if let Err(probe) = &console {
            log::warn!(
                "CTRL_BREAK to group {pid}: the console probe failed ({report}); cannot classify",
                report = crate::error::Report(probe)
            );
            return crate::error::Error::Io(err);
        }
        return crate::error::Error::NoConsole {
            detail: format!(
                "cannot send CTRL_BREAK to process group {pid}: this process has no attached \
                 console. A GUI-subsystem binary, a service, or a detached spawn cannot deliver \
                 console control events — Windows delivers them only within the caller's \
                 console. Attach a console before spawning the tree, or use kill_tree() for a \
                 hard teardown."
            ),
        };
    }
    // The probe cannot change this classification, but if it ALSO failed that is a second,
    // independent OS failure and the arms above log theirs — say so here too rather than
    // dropping it silently.
    if let Err(probe) = &console {
        log::warn!(
            "CTRL_BREAK to group {pid} failed, and the console probe also failed ({report})",
            report = crate::error::Report(probe)
        );
    }
    crate::error::Error::Io(err)
}

/// What this process's ambient job object says about a child breaking away from it.
///
/// `Unknown` exists for the same reason `identity::Resolved::Unknown` does: cosca must not assert
/// a cause it could not measure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum JobBreakaway {
    NotInJob,
    Permitted,
    /// The job removes new children itself, without them asking — so it does not FORBID
    /// breakaway, and a message saying it does would be wrong about the world.
    SilentBreakaway,
    Forbidden,
    Unknown,
}

/// Read this process's ambient job's breakaway limits.
///
/// Impure, and called only to CLASSIFY a spawn failure that already happened — never to gate one
/// before it. Spawning does not disturb job membership, but membership changes on its own (a
/// process can be assigned to a job at any moment), so a pre-spawn guard would decide the outcome
/// from state that may already be stale, while a post-failure confirmation at worst withholds a
/// typed error. Same impure-probe / pure-classifier split as `caller_has_console` /
/// `classify_ctrl_event_failure`.
///
/// `Permitted` takes precedence over `SilentBreakaway`, because a job setting both does honour
/// the flag.
pub(crate) fn probe_job_breakaway() -> JobBreakaway {
    use windows::Win32::System::JobObjects::{
        IsProcessInJob, JobObjectBasicLimitInformation, QueryInformationJobObject, JOBOBJECT_BASIC_LIMIT_INFORMATION,
        JOB_OBJECT_LIMIT, JOB_OBJECT_LIMIT_BREAKAWAY_OK, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK,
    };
    use windows::Win32::System::Threading::GetCurrentProcess;

    #[cfg(test)]
    if fault::take_force_job_probe_error() {
        return JobBreakaway::Unknown;
    }

    let mut in_job = windows::core::BOOL(0);
    // SAFETY: standard Win32; `in_job` is a valid out-param, and `None` asks "in ANY job".
    if unsafe { IsProcessInJob(GetCurrentProcess(), None, &mut in_job) }.is_err() {
        return JobBreakaway::Unknown;
    }
    if !in_job.as_bool() {
        return JobBreakaway::NotInJob;
    }

    let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
    // SAFETY: standard Win32; `info` is a valid, correctly-sized out-param, and `None` asks about
    // the calling process's own job. The query class returns the BASIC structure even though the
    // matching setter needs the extended one — an asymmetry in the API, not a mistake here.
    let queried = unsafe {
        QueryInformationJobObject(
            None,
            JobObjectBasicLimitInformation,
            std::ptr::addr_of_mut!(info).cast(),
            size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
            None,
        )
    };
    if queried.is_err() {
        return JobBreakaway::Unknown;
    }
    if info.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
        return JobBreakaway::Permitted;
    }
    if info.LimitFlags & JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
        return JobBreakaway::SilentBreakaway;
    }
    JobBreakaway::Forbidden
}

/// Send `CTRL_BREAK_EVENT` to the process group rooted at `pid`.
/// The child was spawned with `CREATE_NEW_PROCESS_GROUP`, making it the leader;
/// targeting its `pid` reaches the whole group without affecting the parent's console.
/// `CTRL_C` cannot be group-targeted; `CTRL_BREAK` is the only option here.
///
/// **Precondition: the caller holds something that pins `pid`** — the owning `Child`'s process
/// handle, or an identity-verified `ProcessId`. This function takes a raw pid because Win32
/// offers no verify-then-signal primitive, so an unpinned pid could name a recycled process.
///
/// **Requires the CALLER to have a console.** That is the failure this classifies; Windows
/// can also report `ERROR_INVALID_PARAMETER` for a pid that names no process at all, which
/// stays a raw `Error::Io`. The failure code is authoritative; the console probe that follows
/// only *confirms* it, so a console state change in the gap degrades the result to a raw
/// `Error::Io` rather than to a false `NoConsole`.
///
/// **The Win32 return value is evidence in neither direction.** Measured: a target in another
/// console returns success having delivered nothing, and the same class of target returns
/// `ERROR_INVALID_PARAMETER` in another configuration. So the classification above must never
/// be replaced with a return-code check, and success must never be read as delivery.
///
/// **An already-exited target is `Ok`**, because the pinned pid stays allocated and the call
/// succeeds — matching the crate's "already-dead ⇒ `Ok`" contract for the lone signal. A dead
/// group leader is not proof of an empty group either: a signal addressed to one still reaches
/// live members of that group.
///
/// **Two known gaps a caller must plan around.** A target that shares no console with the caller
/// is reported as success and receives nothing; a process attached to the child's *own* console
/// can deliver an event to it, and `kill`/`kill_tree` need no console at all. And every call —
/// including one to an ordinary group that has already drained — leaves a dead entry in the
/// caller's console process list, which persists after the target exits.
///
/// **Absence from the caller's console list is not grounds to refuse.** Membership is readable
/// (`GetConsoleProcessList`), so the first gap's condition is decidable here; the inference is
/// what is missing. Absence is consistent with three states and only one of them is a
/// non-delivery. A contained child is absent at the instant `spawn()` returns — measured 0/10,
/// and 0/10 again for the suspend-then-resume shape a contained root uses — while a signal in
/// that window is delivered and kills it, so refusing would turn a working teardown into an
/// error. An already-exited child is absent too, because a real member's entry is removed on
/// exit, where this function's contract is "already-dead ⇒ `Ok`". The genuinely-elsewhere target
/// is the third, and separating it needs the TARGET's console rather than ours — a broker, not
/// a probe.
pub(crate) fn terminate(pid: u32) -> Result<(), crate::error::Error> {
    use windows::Win32::System::Console::{GenerateConsoleCtrlEvent, CTRL_BREAK_EVENT};
    debug_assert!(
        pid != 0,
        "pid 0 addresses every process attached to the caller's console, including the caller"
    );
    terminate_with(
        pid,
        // SAFETY: standard Win32 call targeting the child's own console group.
        || unsafe { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid) },
        caller_has_console,
    )
}

/// [`terminate`] with the OS call `send` and the console probe injected, so a test can make the
/// call fail with the code the OS reports without detaching the test process from its console.
fn terminate_with(
    pid: u32,
    send: impl FnOnce() -> windows::core::Result<()>,
    console: impl FnOnce() -> io::Result<bool>,
) -> Result<(), crate::error::Error> {
    match send() {
        Ok(()) => {
            #[cfg(test)]
            observe::record_ctrl_break(pid);
            Ok(())
        }
        Err(e) => Err(classify_ctrl_event_failure(pid, win32_io_error(e), console())),
    }
}

/// Test-only records of what THIS thread did, with take semantics, mirroring `fault`.
///
/// - `clear_std_handle_inheritance` ran, so a test can prove a refused spawn did not mutate this
///   process first. The real handle flags cannot serve as the observation: the mutation is
///   process-global and permanent, so any earlier contained spawn in the same test binary would
///   already have made it meaningless.
/// - A `CTRL_BREAK` went out: the group `terminate` addressed, once Windows accepted the event.
///   The event lands asynchronously, so a test asserts this before it waits for the target's own
///   evidence, and a call that sent nothing fails that assertion instead of leaving the wait
///   unbounded.
#[cfg(test)]
pub(crate) mod observe {
    use std::cell::{Cell, RefCell};
    thread_local! {
        static INHERITANCE_CLEARED: Cell<bool> = const { Cell::new(false) };
        static CTRL_BREAKS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
    }
    pub(crate) fn record_inheritance_cleared() {
        INHERITANCE_CLEARED.with(|f| f.set(true));
    }
    pub(crate) fn take_inheritance_cleared() -> bool {
        INHERITANCE_CLEARED.with(|f| f.replace(false))
    }
    pub(crate) fn record_ctrl_break(group: u32) {
        CTRL_BREAKS.with(|b| b.borrow_mut().push(group));
    }
    /// The groups sent a `CTRL_BREAK` on this thread since the last take, in order.
    pub(crate) fn take_ctrl_breaks() -> Vec<u32> {
        CTRL_BREAKS.with(|b| std::mem::take(&mut *b.borrow_mut()))
    }
}

/// Test-only: force the NEXT `caller_has_console` on THIS thread to report a probe failure,
/// so that arm's production is covered — a live `GetConsoleProcessList` cannot be made to
/// fail. Take semantics, mirroring `treewalk::fault`.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::{Cell, RefCell};
    thread_local! {
        static FORCE_CONSOLE_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
    }
    pub(crate) fn set_force_console_probe_error(on: bool) {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.set(on));
    }
    thread_local! {
        static FORCE_JOB_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
    }
    /// Force the NEXT `probe_job_breakaway` on THIS thread to report `Unknown`: neither Win32
    /// call it makes can be made to fail on a live system.
    pub(crate) fn set_force_job_probe_error(on: bool) {
        FORCE_JOB_PROBE_ERROR.with(|f| f.set(on));
    }
    pub(crate) fn take_force_job_probe_error() -> bool {
        FORCE_JOB_PROBE_ERROR.with(|f| f.replace(false))
    }
    pub(crate) fn take_force_console_probe_error() -> bool {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.replace(false))
    }

    thread_local! {
        static BEFORE_JOB_KILL: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    }
    /// Run `hook` once, right before the next `TerminateJobObject` on this thread; the guard clears
    /// it.
    pub(crate) fn set_before_job_kill(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
        crate::oneshot_hook::arm(&BEFORE_JOB_KILL, hook)
    }
    pub(crate) fn run_before_job_kill() {
        crate::oneshot_hook::fire(&BEFORE_JOB_KILL);
    }
    pub(crate) fn armed() -> bool {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.get())
    }

    /// The Win32 call `resume_if_owned` makes at each step, for [`force_next`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Step {
        QueryOpen,
        Owner,
        ResumeOpen,
        Resume,
        /// The read of a thread's creation time, in the search for a frozen child's initial thread.
        CreationTime,
        /// The assignment of a Strongest root's job.
        Assign,
        /// The read of a root's loader state, in the proof that it never ran.
        LoaderRead,
        JobKill,
        /// The membership check of a process by pid (`member_identity`, `member_to_watch_for_wait`),
        /// keyed by the pid.
        Membership,
        /// The next `open_for_wait` of a pid, keyed by the pid: refused once, as another process's
        /// hold on the number would have it.
        WaitOpen,
        /// The read of a member's identity by pid (`member_identity`), keyed by the pid.
        Identity,
    }

    /// The forced pid lists of this thread.
    enum ForcedPidLists {
        Unarmed,
        /// Forced lists, then an optional forced failure; the real list after.
        Armed {
            lists: std::collections::VecDeque<Vec<u32>>,
            then_fail: Option<u32>,
        },
    }
    thread_local! {
        static JOB_PID_LIST: RefCell<ForcedPidLists> = const { RefCell::new(ForcedPidLists::Unarmed) };
        static JOB_PID_LIST_QUERIES: Cell<u32> = const { Cell::new(0) };
    }
    /// [`force_job_pid_lists`] for one list.
    pub(crate) fn force_job_pid_list(pids: Vec<u32>) -> ForcedList {
        force_job_pid_lists([pids])
    }
    /// Answer `lists`, one per `query_job_pid_list` on this thread in order; counts the queries made
    /// ([`job_pid_list_queries`]) until dropped.
    pub(crate) fn force_job_pid_lists(lists: impl IntoIterator<Item = Vec<u32>>) -> ForcedList {
        arm_job_pid_lists(lists, None)
    }
    /// [`force_job_pid_lists`], and the query after `lists` fails with the Win32 code `code`.
    pub(crate) fn force_job_pid_lists_then_failure(lists: impl IntoIterator<Item = Vec<u32>>, code: u32) -> ForcedList {
        arm_job_pid_lists(lists, Some(code))
    }
    fn arm_job_pid_lists(lists: impl IntoIterator<Item = Vec<u32>>, then_fail: Option<u32>) -> ForcedList {
        JOB_PID_LIST.with(|f| {
            let mut f = f.borrow_mut();
            debug_assert!(
                matches!(*f, ForcedPidLists::Unarmed),
                "a pid list is forced and its guard is alive"
            );
            *f = ForcedPidLists::Armed {
                lists: lists.into_iter().collect(),
                then_fail,
            };
        });
        JOB_PID_LIST_QUERIES.with(|c| c.set(0));
        ForcedList(())
    }
    /// The next forced answer, if one is armed; counts every call.
    pub(crate) fn take_forced_job_pid_list() -> Option<std::io::Result<Vec<u32>>> {
        JOB_PID_LIST_QUERIES.with(|c| c.set(c.get() + 1));
        JOB_PID_LIST.with(|f| {
            let mut f = f.borrow_mut();
            let ForcedPidLists::Armed { lists, then_fail } = &mut *f else {
                return None;
            };
            lists.pop_front().map(Ok).or_else(|| {
                then_fail
                    .take()
                    .map(|code| Err(std::io::Error::from_raw_os_error(code as i32)))
            })
        })
    }
    /// How many `query_job_pid_list` calls this thread made since [`force_job_pid_list`] or
    /// [`force_job_pid_lists`] last armed it, or since its guard dropped.
    pub(crate) fn job_pid_list_queries() -> u32 {
        JOB_PID_LIST_QUERIES.with(|c| c.get())
    }
    #[must_use = "dropping this immediately disarms the forced pid list"]
    pub(crate) struct ForcedList(());
    impl Drop for ForcedList {
        fn drop(&mut self) {
            JOB_PID_LIST.with(|f| *f.borrow_mut() = ForcedPidLists::Unarmed);
            JOB_PID_LIST_QUERIES.with(|c| c.set(0));
        }
    }

    thread_local! {
        static INJECTED: Cell<Option<(u32, Option<u32>)>> = const { Cell::new(None) };
        static INJECTED_VISIT: Cell<Option<Option<super::Visit>>> = const { Cell::new(None) };
        static FORCED: RefCell<Vec<(Step, u32, Option<u32>)>> = const { RefCell::new(Vec::new()) };
        static EQUAL_CREATION_TIMES: Cell<bool> = const { Cell::new(false) };
    }
    /// Make `resume_initial_threads` on THIS thread walk one extra snapshot entry for thread
    /// `tid`, owned by `owner` (`None`: the CHILD's pid, which is what a stale id looks like).
    /// Reset on drop, which also clears the recorded visit and any forced failure.
    pub(crate) fn inject_snapshot_tid(tid: u32, owner: Option<u32>) -> Injected {
        INJECTED.with(|f| {
            debug_assert!(f.get().is_none(), "a snapshot tid is already injected");
            f.set(Some((tid, owner)));
        });
        INJECTED_VISIT.with(|f| f.set(None));
        Injected(())
    }
    /// The injected entry's `(tid, owner)`.
    pub(crate) fn injected_entry() -> Option<(u32, Option<u32>)> {
        INJECTED.with(|f| f.get())
    }
    /// Record what the walk did with the injected entry (`None`: the owner filter dropped it).
    pub(crate) fn record_injected_visit(visit: Option<super::Visit>) {
        INJECTED_VISIT.with(|f| f.set(Some(visit)));
    }
    /// What the walk did with the injected entry. The outer `None` means it was never walked.
    pub(crate) fn take_injected_visit() -> Option<Option<super::Visit>> {
        INJECTED_VISIT.with(|f| f.take())
    }
    /// Make the NEXT `step` call on THIS thread fail with Win32 error `code`. Different steps can
    /// be forced at once. Reset on drop of the guard. Neither an owner of 0 nor a failed
    /// `ResumeThread` can be produced on a live system.
    pub(crate) fn force_next(step: Step, code: u32) -> Forced {
        arm(step, code, None)
    }
    /// [`force_next`], but only for the call that handles thread `tid`; a call for another thread
    /// does not consume it.
    pub(crate) fn force_next_for_thread(step: Step, code: u32, tid: u32) -> Forced {
        arm(step, code, Some(tid))
    }
    fn arm(step: Step, code: u32, tid: Option<u32>) -> Forced {
        FORCED.with(|f| {
            let mut f = f.borrow_mut();
            debug_assert!(f.iter().all(|(armed, ..)| *armed != step), "{step:?} is already forced");
            f.push((step, code, tid));
        });
        Forced(())
    }
    /// Whether a forced failure is still armed: the call it was armed for never happened.
    pub(crate) fn forced_is_armed() -> bool {
        FORCED.with(|f| !f.borrow().is_empty())
    }
    /// Consume a forced failure for `step` (on thread `tid`, where the call has one), if one is
    /// armed for it.
    pub(crate) fn take_forced(step: Step, tid: Option<u32>) -> Option<u32> {
        FORCED.with(|f| {
            let mut f = f.borrow_mut();
            let at = f
                .iter()
                .position(|&(armed, _, only)| armed == step && (only.is_none() || only == tid))?;
            Some(f.remove(at).1)
        })
    }
    /// Make every creation time read on THIS thread answer the same value, as a coarse clock would,
    /// until the guard drops. No live system can be made to tie.
    pub(crate) fn equal_creation_times() -> EqualTimes {
        EQUAL_CREATION_TIMES.with(|f| f.set(true));
        EqualTimes(())
    }
    pub(crate) fn creation_times_are_equal() -> bool {
        EQUAL_CREATION_TIMES.with(|f| f.get())
    }
    #[must_use = "dropping this immediately restores the real clock"]
    pub(crate) struct EqualTimes(());
    impl Drop for EqualTimes {
        fn drop(&mut self) {
            EQUAL_CREATION_TIMES.with(|f| f.set(false));
        }
    }
    #[must_use = "dropping this immediately removes the injected entry"]
    pub(crate) struct Injected(());
    impl Drop for Injected {
        fn drop(&mut self) {
            INJECTED.with(|f| f.set(None));
            INJECTED_VISIT.with(|f| f.set(None));
        }
    }
    #[must_use = "dropping this immediately disarms the forced failure"]
    pub(crate) struct Forced(());
    impl Drop for Forced {
        fn drop(&mut self) {
            FORCED.with(|f| f.borrow_mut().clear());
        }
    }
}

/// Create a `KILL_ON_JOB_CLOSE` job and assign the process at `proc_handle` to it.
///
/// `pub(crate)`: also the sole constructor behind the public [`crate::containment::job::Job`]
/// primitive — reused verbatim rather than duplicated, so `Command::contain()` and `Job::assign`
/// share exactly one implementation.
pub(crate) fn assign_to_kill_on_close_job(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
    // A Windows `RawHandle` is a `*mut c_void`.
    let raw_handle = HANDLE(proc_handle.cast());
    // SAFETY: a standard Win32 call; its handle is closed on every error path below.
    let job = owned_job(unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) })?;
    set_kill_on_close_or_close(job)?;
    assign_or_close(job, raw_handle)?;
    Ok(JobHandle::new(job))
}

/// The job `CreateJobObjectW` made, or its failure with the plain Win32 code.
fn owned_job(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
    created.map_err(win32_io_error)
}

/// Set `KILL_ON_JOB_CLOSE` on `job`. On failure `job` is closed and the error has the plain Win32
/// code.
fn set_kill_on_close_or_close(job: HANDLE) -> io::Result<()> {
    let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
    info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    // SAFETY: `info` is a live local of exactly the size passed.
    let set = unsafe {
        SetInformationJobObject(
            job,
            JobObjectExtendedLimitInformation,
            std::ptr::addr_of!(info).cast(),
            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
        )
    };
    if let Err(e) = set {
        // SAFETY: the caller hands `job` over; nothing else closes it.
        _ = unsafe { CloseHandle(job) };
        return Err(win32_io_error(e));
    }
    Ok(())
}

/// Assign `process` to `job`. On failure `job` is closed and the error has the plain Win32 code.
fn assign_or_close(job: HANDLE, process: HANDLE) -> io::Result<()> {
    // SAFETY: a standard Win32 call on handles the caller keeps open across it.
    if let Err(e) = unsafe { AssignProcessToJobObject(job, process) } {
        // SAFETY: the caller hands `job` over; nothing else closes it.
        _ = unsafe { CloseHandle(job) };
        return Err(win32_io_error(e));
    }
    Ok(())
}

/// [`assign_to_kill_on_close_job`] as `attach` takes it: the job is assigned and the child is NOT
/// resumed.
pub(crate) fn assign_held(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
    #[cfg(test)]
    forced(fault::Step::Assign, None).map_err(win32_io_error)?;
    assign_to_kill_on_close_job(proc_handle)
}

/// Read the job's LIVE member pids via `QueryInformationJobObject(JobObjectBasicProcessIdList)`
/// — the authoritative, always-fresh source `wait_drained` re-consults every round, independent
/// of any completion-port message. Grows the buffer and retries (no bound on retries: a job
/// that keeps growing needs an ever-larger buffer, but capping this would silently under-report
/// live membership rather than fail loudly).
pub(crate) fn query_job_pid_list(job: HANDLE) -> io::Result<Vec<u32>> {
    #[cfg(test)]
    if let Some(forced) = fault::take_forced_job_pid_list() {
        return forced;
    }
    let mut capacity: usize = 64;
    loop {
        let buf_len = size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() + capacity.saturating_sub(1) * size_of::<usize>();
        // Backed by `Vec<usize>`, not `Vec<u8>`: `JOBOBJECT_BASIC_PROCESS_ID_LIST` is 8-aligned
        // (it holds `usize` fields), but a `Vec<u8>`'s allocation is only ever requested at
        // alignment 1. Forming a `&JOBOBJECT_BASIC_PROCESS_ID_LIST` from a `Vec<u8>` buffer is
        // undefined behaviour regardless of what the allocator happens to return in practice —
        // the compiler is entitled to assume the reference's target is properly aligned. A
        // `Vec<usize>` buffer is naturally aligned for this header, and is read through raw
        // pointers below rather than a reference, so no alignment assumption is ever load-bearing.
        let mut buf: Vec<usize> = vec![0usize; buf_len.div_ceil(size_of::<usize>())];
        let mut returned = 0u32;
        let header_ptr = buf.as_mut_ptr().cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>();
        // SAFETY: `buf` is at least `buf_len` bytes (rounded up to whole `usize`s),
        // zero-initialized, matching the trailing `ProcessIdList` array's declared capacity; the
        // call writes at most `buf_len` bytes.
        let result = unsafe {
            QueryInformationJobObject(
                Some(job),
                JobObjectBasicProcessIdList,
                header_ptr.cast(),
                buf_len as u32,
                Some(&mut returned),
            )
        };
        // The fixed header (`NumberOfAssignedProcesses`/`NumberOfProcessIdsInList`) is always
        // written even when the call fails with a too-small buffer. Read both fields via
        // `addr_of!`/`read_unaligned` on the raw pointer rather than materialising a
        // `&JOBOBJECT_BASIC_PROCESS_ID_LIST` reference, so this call never depends on forming a
        // reference into a buffer the kernel writes out-of-band.
        // SAFETY: `header_ptr` is valid for reads of `size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>()`
        // bytes (`buf_len` is at least that size by construction) and initialized (zeroed above,
        // then possibly partially overwritten by the call).
        let assigned = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfAssignedProcesses).read_unaligned() } as usize;
        if result.is_err() {
            if assigned > capacity {
                capacity = assigned;
                continue;
            }
            return Err(io::Error::last_os_error());
        }
        // SAFETY: same as above.
        let n = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfProcessIdsInList).read_unaligned() } as usize;
        debug_assert!(
            n <= capacity,
            "kernel reported more pids than the queried buffer could hold"
        );
        // SAFETY: `ProcessIdList` is the header's trailing flexible-array member; `buf` was sized
        // for `capacity` entries starting right after the two `u32` counters, and
        // `n.min(capacity) <= capacity`, so every read below is in-bounds and initialized.
        let list_ptr = unsafe { std::ptr::addr_of!((*header_ptr).ProcessIdList).cast::<usize>() };
        let mut pids = Vec::with_capacity(n.min(capacity));
        for i in 0..n.min(capacity) {
            // SAFETY: see above.
            let raw = unsafe { list_ptr.add(i).read_unaligned() };
            pids.push(raw as u32);
        }
        return Ok(pids);
    }
}

/// The largest handle count a single `WaitForMultipleObjects` call accepts (`MAXIMUM_WAIT_OBJECTS`).
const MAXIMUM_WAIT_OBJECTS: usize = 64;

impl JobHandle {
    /// Block until every process in this job has EXITED (not reaped), or until `deadline`.
    ///
    /// Deliberately does not associate an I/O completion port with the job at all: every
    /// ordinary job-lifecycle completion-port message (`JOB_OBJECT_MSG_EXIT_PROCESS`,
    /// `JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO`, ...) is documented by Microsoft as **not guaranteed
    /// to be delivered** — only `JobObjectNotificationLimitInformation`-class resource-limit
    /// messages carry a delivery guarantee, a class unrelated to process lifecycle. Trusting a
    /// port for this call's own correctness would make an unbounded `wait_tree()` capable of a
    /// caller-invisible infinite hang on a single dropped packet — and with the port never read,
    /// associating one anyway would only cost unbounded kernel nonpaged-pool growth (one queued
    /// packet per job lifecycle event, for the job handle's whole lifetime) for nothing.
    ///
    /// Instead, each round: (1) re-enumerate the job's LIVE members via
    /// `QueryInformationJobObject(JobObjectBasicProcessIdList)` — the authoritative, always-fresh
    /// source of truth, independent of any notification; (2) if empty, the tree has drained; (3)
    /// otherwise open real `SYNCHRONIZE` handles to up to `MAXIMUM_WAIT_OBJECTS - 1` of those
    /// pids and block on `WaitForMultipleObjects(bWaitAll = FALSE)`. A process handle becoming
    /// signaled on exit is an unconditional, always-honored OS guarantee — unlike a job message
    /// — so as long as this round's tree is non-empty, at least one tracked handle WILL
    /// eventually signal, forcing a fresh re-enumeration next round. A member leaves the job's list
    /// before its process object is signalled, so an empty re-count (the first one too) is the drain
    /// only once the members a system process snapshot still names that are in this job have exited:
    /// the wait opens each, one at a time, waits for it and closes it ([`confirm_drained`]). Only an
    /// empty re-count with no such member left answers `AllMembersExited`, within the limit stated at
    /// [`Child::wait_tree`](crate::Child::wait_tree); with more than `MAXIMUM_WAIT_OBJECTS - 1` live
    /// members it may notice the drain late. The handle stays open after
    /// [`hard_kill`](JobHandle::hard_kill), so this also waits out a killed tree. A member
    /// the caller may open for membership but not wait on (an elevated one, under a caller that is not)
    /// is a member whose exit cannot be observed: the answer is `Unassessable` naming its pid, with the
    /// OS error as the cause, never `AllMembersExited`.
    ///
    /// A pid the list names is a member only if shown to be one. One shown not to be (opened,
    /// `IsProcessInJob` false) is dropped; a member that refuses only the wait open is `Unassessable`
    /// naming the pid, at once. When no listed pid can be waited for and some are unproved (their
    /// membership cannot be established), the round takes one more listing ([`settle_unproved`]): a pid
    /// it names again is looked at once more, and is watched if proved a member now, dropped if proved
    /// not one, and `Unassessable` naming it, with the refusal as the cause, if still unproved; a pid
    /// it does not name was a deleted member's, dropped. Nothing carries across rounds.
    /// [`JobHandle::list_members`], the kill's listing, applies the same rule.
    ///
    /// `deadline`: `None` is no deadline (see [`crate::wait::remaining`]). No interval is chosen
    /// anywhere in this path: every round blocks in one `WaitForMultipleObjects` call for exactly
    /// the caller's own remaining time. What a deadline answers is stated at [`wait_drained_raw`].
    ///
    /// The async drain runs the same rounds ([`drain_round`](JobHandle::drain_round)) and awaits each
    /// round's handles where this blocks on them.
    pub(crate) fn wait_drained(
        &self,
        deadline: Option<std::time::Instant>,
    ) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        wait_drained_raw(self, deadline)
    }

    /// [`wait_drained`](Self::wait_drained) for a caller that has waited for the members `settled`
    /// already ([`wait_drained_past`]).
    pub(crate) fn wait_drained_past(
        &self,
        deadline: Option<std::time::Instant>,
        settled: &Settled,
    ) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        wait_drained_past(self, deadline, settled)
    }

    /// What the confirmation of an empty listing must do ([`Round::Confirm`]): `None` if the
    /// job has had no process since a confirmation that waited for them all, so that none is left to
    /// wait for (a job that never had one has the count `0`, which the stored count starts at), and
    /// `Some(count)`, the job's [`total_processes`] read now, if the members its snapshot names must be
    /// waited for. Pass `count` to [`confirmed_at`](Self::confirmed_at) once they have been. The count
    /// is read after the listing that was empty and before the snapshot, so a process that joins
    /// later shows in the next count.
    pub(crate) fn count_to_confirm(&self) -> Result<Option<u32>, crate::error::Error> {
        let count = total_processes(self.raw).map_err(|e| crate::error::Error::Unassessable {
            detail: "the number of processes the job has had could not be read, so its drain cannot be confirmed"
                .to_owned(),
            source: Some(crate::error::Error::io_cause(e)),
        })?;
        Ok((count != self.confirmed.load(Ordering::Relaxed)).then_some(count))
    }

    /// Record that every member of the job was waited for when its count was `count`
    /// ([`count_to_confirm`](Self::count_to_confirm)).
    pub(crate) fn confirmed_at(&self, count: u32) {
        self.confirmed.store(count, Ordering::Relaxed);
    }

    /// One round of the drain wait: list the live members, open each (up to the wait-set cap) with
    /// `SYNCHRONIZE`, and say what the round decided. `last_round` is whether the caller's deadline
    /// has already passed, on the caller's clock. What a round answers is stated at
    /// [`wait_drained_raw`].
    #[cfg(feature = "tokio")]
    pub(crate) fn drain_round(&self, last_round: bool) -> Result<Round, crate::error::Error> {
        drain_round(HANDLE(self.handle().as_raw_handle()), last_round)
    }

    /// What follows a round's wait that ended on a member's handle: the answer or the confirmation of
    /// an empty listing if the round was the last, the next round if not.
    #[cfg(feature = "tokio")]
    pub(crate) fn after_signalled(&self, watch: &Watch) -> Result<Round, crate::error::Error> {
        after_signalled(HANDLE(self.handle().as_raw_handle()), watch)
    }
}

/// The members an empty listing leaves to be waited for ([`Round::Confirm`]) in the job `job` is a
/// handle to: see [`confirm_drained`]. A handle, not `&JobHandle`, so the async drain can run it on
/// the blocking pool with a duplicate of the job's handle: the scan opens every process on the system.
#[cfg(feature = "tokio")]
pub(crate) fn unsignalled_members_of(job: BorrowedHandle<'_>) -> Result<Vec<Found>, crate::error::Error> {
    unsignalled_members(HANDLE(job.as_raw_handle()))
}

/// What the job's list naming a pid amounts to once the caller has tried to open it.
#[derive(Debug)]
enum Standing {
    /// In the job; the handle is open.
    Member(HANDLE),
    /// Shown not to be one: its number is gone or was reused by a process that is not in the job.
    NotMember,
    /// Membership could not be established (the open was refused, or `IsProcessInJob` failed), for
    /// this reason, with the plain Win32 code.
    Unproved(io::Error),
}

/// The [`Standing`] of the process `OpenProcess` returned as `opened` in `job`. The handle is closed
/// unless it is returned.
fn member_to_watch(opened: windows::core::Result<HANDLE>, job: HANDLE) -> Standing {
    match opened {
        // A pid enumerated a moment ago can have exited and had its number reused by the time it
        // is opened, so membership is re-confirmed against the job rather than assumed. Waiting
        // on a bystander would either hang the drain (it outlives the tree) or, if it exits
        // first, report the tree drained while members run.
        Ok(h) => {
            use windows::Win32::System::JobObjects::IsProcessInJob;
            let mut in_job = windows::core::BOOL(0);
            // SAFETY: both handles are valid for the duration of the call.
            let confirmed = unsafe { IsProcessInJob(h, Some(job), &mut in_job) };
            match confirmed {
                // A member: wait on it.
                Ok(()) if in_job.as_bool() => Standing::Member(h),
                // Openable but not in this job: the pid was recycled between the enumeration and
                // the open. Filtering it out is the point.
                Ok(()) => {
                    // SAFETY: opened by the caller and not stored anywhere.
                    _ = unsafe { CloseHandle(h) };
                    Standing::NotMember
                }
                // Membership is unknown: the caller decides (see `Standing::Unproved`).
                Err(e) => {
                    // SAFETY: opened by the caller and not stored anywhere.
                    _ = unsafe { CloseHandle(h) };
                    Standing::Unproved(win32_io_error(e))
                }
            }
        }
        // ERROR_INVALID_PARAMETER: the pid no longer names a process: it exited in the race
        // between the enumeration and the open. Not a failure, and not a member either.
        Err(e) if e.code() == windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => Standing::NotMember,
        Err(e) => Standing::Unproved(win32_io_error(e)),
    }
}

/// The [`Standing`] of the listed pid `pid`, opened for the round's any-wait ([`open_for_wait`]). A
/// refused open leaves membership to the query-only open ([`open_for_membership`]), whose handle
/// holds the pid (an open handle keeps the process object, so the number cannot be reused): the wait
/// open is made again under it. If that now succeeds, the pid is a member the caller can wait on;
/// if it is refused again, that is the member's refusal, the `Err` here, at once. A pid the
/// query-only open proves not in the job is [`Standing::NotMember`]; one it cannot prove either way
/// is [`Standing::Unproved`], with the query-only open's (or `IsProcessInJob`'s) error.
fn member_to_watch_for_wait(pid: u32, job: HANDLE) -> io::Result<Standing> {
    #[cfg(test)]
    if let Err(e) = forced(fault::Step::Membership, Some(pid)) {
        return Ok(Standing::Unproved(win32_io_error(e)));
    }
    match open_for_wait(pid) {
        Err(refused) if refused.code() != windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => {
            match member_to_watch(open_for_membership(pid), job) {
                Standing::Member(proof) => {
                    let retried = open_for_wait(pid);
                    // SAFETY: `member_to_watch` handed over the handle it opened; closed once, here,
                    // after the retry it holds the pid for.
                    _ = unsafe { CloseHandle(proof) };
                    retried.map(Standing::Member).map_err(win32_io_error)
                }
                other => Ok(other),
            }
        }
        opened => Ok(member_to_watch(opened, job)),
    }
}

/// Take the listing that settles `unproved`, the pids a listing named whose membership could not be
/// established, each with the reason: `Break` if it is empty (a drain, for the caller to confirm),
/// else the pids of `unproved` it names again, none if it names none, for the caller to look at
/// again. A listing begun after an open found a pid's process gone never names that process
/// (measured with the deleting thread held, Windows 11 10.0.26100), so a pid this listing does not
/// name was a deleted member's and is dropped, with its reason logged; one it names is a live
/// member's, or a number reused twice. A failed listing is its own `Err`.
fn settle_unproved(job: HANDLE, unproved: &[(u32, io::Error)]) -> io::Result<ControlFlow<(), Vec<u32>>> {
    let again = match list_members_or_drained(job)? {
        ControlFlow::Break(()) => return Ok(ControlFlow::Break(())),
        ControlFlow::Continue(again) => again,
    };
    let listed: std::collections::HashSet<u32> = again.into_iter().collect();
    let mut named = Vec::new();
    for (pid, cause) in unproved {
        if listed.contains(pid) {
            named.push(*pid);
        } else {
            log::debug!(
                "the job's list named pid {pid}, whose membership could not be established ({report}), and the \
                 listing after it does not: a deleted member's pid; dropped",
                report = crate::error::Report(cause)
            );
        }
    }
    Ok(ControlFlow::Continue(named))
}

/// The Toolhelp thread snapshot `CreateToolhelp32Snapshot` made, or its failure with the plain
/// Win32 code.
fn thread_snapshot(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
    created.map_err(win32_io_error)
}

/// Every thread the system lists now, from one Toolhelp snapshot.
fn thread_entries() -> io::Result<Vec<windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32>> {
    use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD};

    // SAFETY: the snapshot is an owned handle, closed by `thread_entries_closing`.
    let snap = thread_snapshot(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) })?;
    thread_entries_closing(snap)
}

/// Every entry of the thread snapshot `snap`, which is closed on every path. A failure of the
/// snapshot API has the plain Win32 code; the end of the walk is not one.
fn thread_entries_closing(
    snap: HANDLE,
) -> io::Result<Vec<windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32>> {
    use windows::Win32::Foundation::ERROR_NO_MORE_FILES;
    use windows::Win32::System::Diagnostics::ToolHelp::{Thread32First, Thread32Next, THREADENTRY32};

    // Thread32First/Next signal end-of-enumeration with ERROR_NO_MORE_FILES.
    let end_of_walk = windows::core::HRESULT::from_win32(ERROR_NO_MORE_FILES.0);
    let mut entry = THREADENTRY32 {
        dwSize: size_of::<THREADENTRY32>() as u32,
        ..Default::default()
    };
    let mut entries = Vec::new();
    // SAFETY: `snap` is a handle the caller hands over; `entry` has its `dwSize` set.
    let mut step = unsafe { Thread32First(snap, &mut entry) };
    let walked = loop {
        match step {
            Ok(()) => {}
            Err(e) if e.code() == end_of_walk => break Ok(entries),
            // A snapshot-API fault, not normal end-of-iteration.
            Err(e) => break Err(win32_io_error(e)),
        }
        entries.push(entry);
        // SAFETY: as for `Thread32First`.
        step = unsafe { Thread32Next(snap, &mut entry) };
    };
    // SAFETY: handed over by the caller; closed once, here.
    _ = unsafe { CloseHandle(snap) };
    walked
}

/// The blocking driver of the drain wait's rounds ([`drain_round`]).
///
/// `MembersRemain` means the tree was not seen drained by the deadline. A round that starts past the
/// deadline (an already-elapsed or `Duration::ZERO` one, or one reached after a wait ended on a
/// member's exit) is the last. It lists: an empty listing is confirmed however late the caller
/// arrived. Live members that a zero-ms poll finds none signalled are `MembersRemain`. Otherwise the
/// listing may be stale (a listed pid was found gone or not a member when opened, or a polled handle
/// was signalled), and exactly one more listing is final: empty is confirmed, anything else
/// `MembersRemain`. When the pids that left it unproved are the whole reason, that listing is the one
/// the round takes to settle them ([`drain_round`]), and nothing lists after it.
///
/// An empty listing, the first one too, is confirmed by [`confirm_drained`]; one member still running
/// at the deadline is `MembersRemain`.
pub(crate) fn wait_drained_raw(
    job: &JobHandle,
    deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
    wait_drained_past(job, deadline, &Settled::default())
}

/// [`wait_drained_raw`] for a caller that has already waited for the members `settled` (each exited,
/// or failed in a way it reported): the confirmation of an empty listing does not wait for them or
/// report them again.
pub(crate) fn wait_drained_past(
    job_handle: &JobHandle,
    deadline: Option<std::time::Instant>,
    settled: &Settled,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
    use crate::containment::TreeDrain;

    let job = HANDLE(job_handle.handle().as_raw_handle());
    loop {
        // A round that starts past the deadline is the last: it lists and answers, with at most one
        // more listing (`final_listing`).
        let last_round = deadline.is_some_and(|at| crate::wait::now() >= at);
        let round = match drain_round(job, last_round)? {
            Round::Watch(watch) => match watch.wait(deadline)? {
                // `wait_until` returns a timeout only once the real deadline has passed.
                Ended::Deadline => return Ok(TreeDrain::MembersRemain),
                Ended::Signalled => after_signalled(job, &watch)?,
            },
            round => round,
        };
        match round {
            Round::Answer(drain) => return Ok(drain),
            Round::Confirm => return confirm_drained(job_handle, deadline, settled),
            // A tracked member exited, or the listing named no live member: the next round
            // re-enumerates the authoritative live set.
            Round::List | Round::Watch(_) => {}
        }
    }
}

/// What a round of the drain wait decided.
pub(crate) enum Round {
    /// The wait is over, with this answer.
    Answer(crate::containment::TreeDrain),
    /// No listed pid is a live member, which says nothing of one that joined after the listing: list
    /// again.
    List,
    /// Wait for one of these handles, then run the next round.
    Watch(Watch),
    /// The listing is empty: confirm it ([`confirm_drained`]).
    Confirm,
}

/// The handles one round waits on: each is open on a listed member, and closed with this.
pub(crate) struct Watch {
    handles: Vec<std::os::windows::io::OwnedHandle>,
    /// The same handles as the array `WaitForMultipleObjects` takes, built once with the round.
    set: HandleSet,
    /// The round started past the deadline: its wait is a poll and its answer final.
    last_round: bool,
}

/// The raw handles of a [`Watch`], which `HANDLE`'s raw pointer would make `!Send` and `!Sync`.
struct HandleSet(Vec<HANDLE>);

// SAFETY: a handle names a kernel object and has no thread affinity. The set is only read, by
// `WaitForMultipleObjects`, while the `OwnedHandle`s it mirrors, owned by the same `Watch`, are open.
unsafe impl Send for HandleSet {}
// SAFETY: as for `Send`; nothing writes the set after it is built.
unsafe impl Sync for HandleSet {}

/// How a round's wait ended, when it did not fail.
pub(crate) enum Ended {
    /// The deadline passed with no handle signalled.
    Deadline,
    /// A member's handle was signalled.
    Signalled,
}

impl Watch {
    /// The handles to wait on: the round ends when any one is signalled.
    #[cfg(feature = "tokio")]
    pub(crate) fn handles(&self) -> impl Iterator<Item = BorrowedHandle<'_>> + Clone {
        use std::os::windows::io::AsHandle as _;
        self.handles.iter().map(|h| h.as_handle())
    }

    /// Block until a handle is signalled or the real `deadline` passes. A `WAIT_TIMEOUT` is never
    /// trusted: the real deadline is rechecked each round (see `win32_timeout_ms`).
    fn wait(&self, deadline: Option<std::time::Instant>) -> Result<Ended, crate::error::Error> {
        self.ended(crate::wait::wait_until(deadline, |ms| {
            #[cfg(test)]
            crate::wait::block_probe::blocking(
                (ms != u32::MAX).then(|| std::time::Duration::from_millis(ms.into())),
                crate::wait::block_probe::WaitObject::Handles,
            );
            self.wait_for(ms)
        }))
    }

    /// Look once, without waiting, for a last round: an elapsed deadline arms `ms == 0` in
    /// [`wait`](Watch::wait), a real poll of the handles.
    #[cfg(feature = "tokio")]
    pub(crate) fn poll(&self) -> Result<Ended, crate::error::Error> {
        self.ended(self.wait_for(0))
    }

    fn wait_for(&self, ms: u32) -> windows::Win32::Foundation::WAIT_EVENT {
        // SAFETY: every handle in `set` is open for the call, owned by `self`.
        unsafe { WaitForMultipleObjects(&self.set.0, false, ms) }
    }

    fn ended(&self, waited: windows::Win32::Foundation::WAIT_EVENT) -> Result<Ended, crate::error::Error> {
        let wait_failed = (waited == WAIT_FAILED).then(io::Error::last_os_error);
        if waited == WAIT_TIMEOUT {
            return Ok(Ended::Deadline);
        }
        if let Some(e) = wait_failed {
            return Err(crate::error::Error::Io(e));
        }
        let idx = waited.0.wrapping_sub(WAIT_OBJECT_0.0) as usize;
        debug_assert!(
            idx < self.handles.len(),
            "unexpected WaitForMultipleObjects verdict: {waited:?}"
        );
        if idx >= self.handles.len() {
            // Same anomaly the debug_assert above catches in debug builds — surfaced here too
            // so a release build does not silently fall through to "treat as a member exit and
            // re-enumerate" without any trace of the OS having returned an unexpected verdict.
            log::warn!(
                "wait_tree: unexpected WaitForMultipleObjects verdict {waited:?} (index {idx} \
                 outside the {} handles waited on) - re-enumerating regardless",
                self.handles.len()
            );
        }
        Ok(Ended::Signalled)
    }
}

/// What follows a round's wait that ended on a member's handle: for the last round, whose own
/// listing may have named an exited member, the answer from one more listing (or the confirmation of
/// an empty one), and for any other the next round.
fn after_signalled(job: HANDLE, watch: &Watch) -> Result<Round, crate::error::Error> {
    if watch.last_round {
        return final_listing(job);
    }
    Ok(Round::List)
}

/// Confirm an empty listing: walk the members a snapshot names ([`ConfirmWalk`]), each waited for by
/// [`wait_for_member`](crate::containment::tree_kill::wait_for_member) against `deadline`; with an
/// unchanged `TotalProcesses` since a confirmation ([`JobHandle::count_to_confirm`]), no snapshot is
/// taken.
fn confirm_drained(
    job: &JobHandle,
    deadline: Option<std::time::Instant>,
    settled: &Settled,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
    use crate::containment::TreeDrain;

    let Some(count) = job.count_to_confirm()? else {
        return Ok(TreeDrain::AllMembersExited);
    };
    walk_confirm(
        ConfirmWalk::new(job, count, unsignalled_members(job.raw), settled),
        deadline,
    )
}

/// The blocking driver of a [`ConfirmWalk`].
fn walk_confirm(
    mut walk: ConfirmWalk<'_>,
    deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
    use crate::containment::tree_kill::wait_for_member;
    use crate::identity::HostKernel;

    loop {
        match walk.next() {
            ConfirmStep::Wait(id) => walk.waited(id, wait_for_member(&HostKernel, id, deadline)),
            ConfirmStep::Done(answer) => return answer,
        }
    }
}

/// A process a snapshot names that is a member of the job: its identity, or its pid and why the
/// identity could not be read.
pub(crate) type Found = Result<ProcessId, (u32, crate::error::Error)>;

/// What a [`ConfirmWalk`] asks of its driver.
pub(crate) enum ConfirmStep {
    /// Wait for this member to exit, against the one deadline of the confirmation (past it, a wait is
    /// a poll: the open still happens), and hand the outcome to [`ConfirmWalk::waited`].
    Wait(ProcessId),
    /// The confirmation's answer.
    Done(Result<crate::containment::TreeDrain, crate::error::Error>),
}

/// The confirmation of an empty listing as a step core, which the blocking driver ([`walk_confirm`])
/// and the async one ([`job_wait_tree_drained`](crate::containment::drain_edge)) both run: they differ
/// only in how a wait for a member is made.
///
/// 1. Every member the snapshot names that is not settled is waited for, whatever an earlier wait came
///    to: [`next`](Self::next) asks for them all, in the snapshot's order, against one deadline. A
///    member still running at the deadline, or a failed wait, ends nothing early.
/// 2. Failures come last and outrank `MembersRemain`: a member whose identity the snapshot could not
///    read, and a wait that failed (a refused open, a failed wait), are collected, and the answer is
///    them (one, or every one once in an [`Error::Several`]); else `MembersRemain` if a member was not
///    seen to exit; else `AllMembersExited`, and the job's count is stored
///    ([`JobHandle::confirmed_at`]). With no deadline that is [`KillWait::wait`]'s contract: the error
///    comes once every other member has been waited for.
/// 3. A snapshot entry is settled by what the kill's wait did ([`Settled`]).
///
/// The count is not stored when a settled member was left out: it may still be running, and a later
/// drain must not stand for it.
///
/// [`KillWait::wait`]: crate::containment::tree_kill::KillWait::wait
/// [`Error::Several`]: crate::error::Error::Several
pub(crate) struct ConfirmWalk<'a> {
    job: &'a JobHandle,
    /// The job's count of processes ever when the snapshot was taken ([`JobHandle::count_to_confirm`]).
    count: u32,
    /// The members still to be waited for, in the snapshot's order.
    queue: std::collections::VecDeque<ProcessId>,
    /// What cannot be observed, in the order it was found: a failed snapshot, a member whose identity
    /// the snapshot could not read, a failed wait.
    failures: Vec<crate::error::Error>,
    /// A member was not seen to exit.
    remain: bool,
    /// A settled member was left out of the walk.
    left_out: bool,
    /// [`ConfirmStep::Done`] was given.
    done: bool,
}

impl<'a> ConfirmWalk<'a> {
    /// The walk of `snapshot`, the result of the system snapshot taken after the empty listing, when
    /// the job's `count` was read ([`JobHandle::count_to_confirm`]), less what `settled` has settled.
    pub(crate) fn new(
        job: &'a JobHandle,
        count: u32,
        snapshot: Result<Vec<Found>, crate::error::Error>,
        settled: &Settled,
    ) -> ConfirmWalk<'a> {
        let mut walk = ConfirmWalk {
            job,
            count,
            queue: std::collections::VecDeque::new(),
            failures: Vec::new(),
            remain: false,
            left_out: false,
            done: false,
        };
        match snapshot {
            Err(failed) => walk.failures.push(failed),
            Ok(found) => {
                for member in found {
                    match member {
                        Ok(id) if settled.covers_identity(id) => walk.left_out = true,
                        Ok(id) => walk.queue.push_back(id),
                        Err((pid, _)) if settled.covers_unreadable(pid) => walk.left_out = true,
                        Err((pid, cause)) => walk.failures.push(member_unobserved(pid, cause)),
                    }
                }
            }
        }
        walk
    }

    /// The next member to wait for, or the answer once every one has been.
    pub(crate) fn next(&mut self) -> ConfirmStep {
        debug_assert!(!self.done, "a confirmation walk was asked for a step after its answer");
        match self.queue.pop_front() {
            Some(id) => ConfirmStep::Wait(id),
            None => {
                self.done = true;
                ConfirmStep::Done(self.answer())
            }
        }
    }

    /// What the wait for the member `id` (the last [`ConfirmStep::Wait`]) came to: `Ok(true)` it has
    /// exited, `Ok(false)` it was running at the deadline, and a wait that could not be made is a
    /// failure naming it ([`member_unobserved`]).
    pub(crate) fn waited(&mut self, id: ProcessId, outcome: Result<bool, crate::error::Error>) {
        match outcome {
            Ok(true) => {}
            Ok(false) => self.remain = true,
            Err(cause) => self.failures.push(member_unobserved(id.pid(), cause)),
        }
    }

    fn answer(&mut self) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        use crate::containment::TreeDrain;

        let mut failures = std::mem::take(&mut self.failures).into_iter();
        if let Some(first) = failures.next() {
            return Err(first.with_peers(failures.map(std::sync::Arc::new)));
        }
        if self.remain {
            return Ok(TreeDrain::MembersRemain);
        }
        if !self.left_out {
            self.job.confirmed_at(self.count);
        }
        Ok(TreeDrain::AllMembersExited)
    }
}

/// The identity of every process a system snapshot names that is a member of `job`, decided with the
/// least access that answers `IsProcessInJob` ([`open_for_membership`]), so a member the caller may
/// not wait on is still named; the wait then fails for it, as an error naming its pid
/// ([`member_unobserved`]), and is never an exit. A pid that cannot be opened, or whose
/// `IsProcessInJob` fails (logged), is skipped: the stated limit at
/// [`Child::wait_tree`](crate::Child::wait_tree). A member whose start time cannot be
/// read is in the result as the pid and the cause ([`Found`]), for the walk to report unless it is
/// settled. A failed snapshot is an error: it is not an empty job.
fn unsignalled_members(job: HANDLE) -> Result<Vec<Found>, crate::error::Error> {
    use crate::identity::HostKernel;

    let mut members = Vec::new();
    for (pid, _parent) in crate::containment::enumerate::process_parents(&HostKernel)? {
        // Dropped on purpose: a non-member such as a system process always refuses, and a member that
        // refuses is the stated limit.
        let Ok(handle) = open_for_membership(pid) else {
            continue;
        };
        match member_identity(job, pid, Ok(handle)) {
            Ok(Some(id)) => members.push(Ok(id)),
            Ok(None) => {}
            Err(NotNamed::Membership(e)) => log::debug!(
                "the drain's snapshot names pid {pid}, whose membership of the job cannot be established ({report}); \
                 it is not waited for",
                report = crate::error::Report(&e)
            ),
            Err(NotNamed::Identity(cause)) => members.push(Err((pid, cause))),
        }
    }
    Ok(members)
}

/// The job's `TotalProcesses`: processes ever in it. It never falls.
fn total_processes(job: HANDLE) -> io::Result<u32> {
    let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
    // SAFETY: `info` is the structure the class asks for, and the job handle is open for the call.
    unsafe {
        QueryInformationJobObject(
            Some(job),
            JobObjectBasicAccountingInformation,
            std::ptr::addr_of_mut!(info).cast(),
            size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
            None,
        )
    }
    .map_err(win32_io_error)?;
    Ok(info.TotalProcesses)
}

/// The failure of a drain that cannot establish whether the job's member `pid` has exited.
fn member_unobserved(pid: u32, cause: crate::error::Error) -> crate::error::Error {
    crate::error::Error::Unassessable {
        detail: format!("a member of the job, pid {pid}, could not be waited for"),
        source: Some(std::sync::Arc::new(cause)),
    }
}

/// One round of the drain wait, shared by the blocking driver ([`wait_drained_raw`]) and the async
/// one: list the live members, open them, and say what to do next. `last_round` is whether the
/// caller's deadline has passed, on the caller's clock.
///
/// When no listed pid can be watched and some are unproved (their membership could not be
/// established), the round takes the listing that settles them ([`settle_unproved`]) and looks again
/// at the unproved pids it names: each is watched (proved a member now), dropped (proved not one), or
/// `Unassessable` (still unproved, or a member that refuses the wait open). An empty settling listing
/// is [`Round::Confirm`]; on a last round a non-empty one is `MembersRemain` and opens no wait handle.
fn drain_round(job: HANDLE, last_round: bool) -> Result<Round, crate::error::Error> {
    use crate::error::Error;

    // List BEFORE consulting the deadline for a return, so an elapsed deadline (a `Duration::ZERO`
    // probe) still observes the tree's actual state and an empty listing is confirmed, as an
    // unbounded wait's is. This mirrors `Kqueue::wait` on the macOS side, which takes one look at an
    // elapsed deadline.
    let pids = match list_members_or_drained(job)? {
        ControlFlow::Break(()) => return Ok(Round::Confirm),
        ControlFlow::Continue(pids) => pids,
    };

    let mut looks = Looks {
        job,
        last_round,
        handles: Vec::new(),
        denied: None,
        unproved: Vec::new(),
    };
    looks.look(&pids, false)?;

    if looks.handles.is_empty() {
        if let Some((pid, e)) = looks.denied.take() {
            // A persistent, actionable open failure (not a benign exit-race): looping
            // back here without ever holding a real handle to block on would busy-spin.
            log::warn!(
                "wait_tree: could not open any live job member to watch for its exit ({report})",
                report = crate::error::Report(&e)
            );
            return Err(member_unobserved(pid, Error::Io(e)));
        }
        if looks.unproved.is_empty() {
            // Gone or reused pids say nothing of a member that joined since the listing: only a
            // fresh empty listing is a drain.
            if last_round {
                return final_listing(job);
            }
            return Ok(Round::List);
        }
        // Looping back through `Round::List` here would spin on a live member that refuses the caller.
        match settle_unproved(job, &looks.unproved)? {
            ControlFlow::Break(()) => return Ok(Round::Confirm),
            ControlFlow::Continue(named) => looks.look(&named, true)?,
        }
        // This listing is the one more listing a last round takes: it names a live member or more,
        // so the tree was not seen drained by the deadline.
        if last_round {
            return Ok(Round::Answer(crate::containment::TreeDrain::MembersRemain));
        }
        if looks.handles.is_empty() {
            return Ok(Round::List);
        }
    }
    let Looks { handles, denied, .. } = looks;
    if let Some((_, e)) = &denied {
        // A sibling was openable, so the round proceeds; log the actionable open failure, which
        // would otherwise stay invisible for the tree's lifetime.
        log::debug!(
            "wait_tree: could not open one live job member to watch for its exit, but \
                 other members are still trackable this round: {report}",
            report = crate::error::Report(e)
        );
    }

    let set = HandleSet(handles.iter().map(|h| HANDLE(h.as_raw_handle())).collect());
    Ok(Round::Watch(Watch {
        handles,
        set,
        last_round,
    }))
}

/// What a round has made of the pids it looked at ([`drain_round`]).
struct Looks {
    job: HANDLE,
    /// The round's deadline has passed: its wait is a poll and its answer final.
    last_round: bool,
    /// Handles on the members to watch, at most the wait set's size.
    handles: Vec<std::os::windows::io::OwnedHandle>,
    /// The member that refused the wait open, with the refusal.
    denied: Option<(u32, io::Error)>,
    /// Pids whose membership could not be established, each with the reason.
    unproved: Vec<(u32, io::Error)>,
}

impl Looks {
    /// Look at each of the listed pids `pids`, unless the wait set is already full: a pid that is
    /// gone does not use up the budget a live member needs. `settling`: they are the pids the
    /// settling listing named again ([`settle_unproved`]), so one still unproved, or a member that
    /// refuses the wait open, is `Unassessable` naming it at once. On a last round the settling
    /// listing is the round's answer (`MembersRemain`), so a member's wait handle is closed, not held:
    /// it is opened only so that a refusal answers as the first look's does.
    fn look(&mut self, pids: &[u32], settling: bool) -> Result<(), crate::error::Error> {
        use crate::error::Error;

        let budget = MAXIMUM_WAIT_OBJECTS - 1;
        for &pid in pids {
            if self.handles.len() == budget {
                break;
            }
            let holds = !(settling && self.last_round);
            match member_to_watch_for_wait(pid, self.job) {
                Ok(Standing::Member(h)) if holds => {
                    // SAFETY: `member_to_watch` hands over the handle `OpenProcess` returned, owned
                    // nowhere else.
                    self.handles
                        .push(unsafe { std::os::windows::io::FromRawHandle::from_raw_handle(h.0) });
                }
                Ok(Standing::Member(h)) => {
                    // SAFETY: as above, closed here and nowhere else.
                    _ = unsafe { CloseHandle(h) };
                }
                Ok(Standing::NotMember) => {}
                Ok(Standing::Unproved(cause)) | Err(cause) if settling => {
                    return Err(member_unobserved(pid, Error::Io(cause)))
                }
                Ok(Standing::Unproved(cause)) => self.unproved.push((pid, cause)),
                Err(e) => self.denied = Some((pid, e)),
            }
        }
        Ok(())
    }
}

/// The one more listing a last round takes when its own is no proof: an empty listing is to be
/// confirmed ([`Round::Confirm`]), anything else is `MembersRemain`. Nothing follows it.
fn final_listing(job: HANDLE) -> Result<Round, crate::error::Error> {
    use crate::containment::TreeDrain;

    Ok(match list_members_or_drained(job)? {
        ControlFlow::Break(()) => Round::Confirm,
        ControlFlow::Continue(_) => Round::Answer(TreeDrain::MembersRemain),
    })
}

/// One listing of the job: an empty one is `Break`, any other is the listed pids.
fn list_members_or_drained(job: HANDLE) -> io::Result<ControlFlow<(), Vec<u32>>> {
    let pids = query_job_pid_list(job)?;
    Ok(if pids.is_empty() {
        ControlFlow::Break(())
    } else {
        ControlFlow::Continue(pids)
    })
}

/// What `resume_if_owned` did with one thread id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Visit {
    Resumed,
    /// The opened thread belongs to `owner`, not to the child: the id was reused.
    Foreign {
        owner: u32,
    },
    /// No thread has this id any more (`ERROR_INVALID_PARAMETER`).
    Gone,
    /// The query-only open was denied. The child's own threads are openable by its creator, so
    /// the id belongs to someone else.
    Denied,
    /// A call failed on a thread that is the child's; recorded in `last_err`.
    Failed,
}

/// What a resume asks of the suspend count it answers.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum SuspendCount {
    /// Any count: the ordinary `contain()` spawn resumes whatever the snapshot lists and accepts a
    /// thread something else already ran.
    #[default]
    Any,
    /// A frozen child's release: resumes the child's INITIAL thread only, and only if its previous
    /// count was exactly 1. An initial thread that ran, or that something else suspended again,
    /// means the child is not as its creator left it. Every other thread (one an EDR agent or a
    /// debugger started) is opened query-only, to read its creation time, and never for
    /// suspend/resume: the creator suspended only the initial thread, so a resume of any other would
    /// take away a suspension that is someone else's. Other threads are never resumed and keep
    /// their count. The initial thread is the one created first, so the release fails, resuming
    /// nothing, if the creation time of any thread of the child cannot be read or the earliest two
    /// are equal. A thread that is gone, or that the creator cannot open, is skipped.
    ExactlyOne,
}

/// The state of one walk over the snapshot.
#[derive(Default)]
struct Walk {
    expected: SuspendCount,
    resumed: u32,
    /// The FIRST failure: it is the root cause, and later ones are logged as they happen.
    last_err: Option<io::Error>,
    /// Reason for the latest stale skip, for the none-resumed error.
    last_skip: Option<String>,
}

impl Walk {
    fn skip(&mut self, reason: String) {
        log::debug!("resume_initial_threads: {reason}; skipped");
        self.last_skip = Some(reason);
    }

    /// Record that the initial thread of `process_pid` cannot be told from the threads `first` and
    /// `second`.
    fn fail_unidentified(&mut self, process_pid: u32, first: u32, second: u32) {
        let msg = format!(
            "the initial thread of pid {process_pid} cannot be identified: threads {first} and {second} have the same creation time"
        );
        log::warn!("resume_initial_threads: {msg}");
        self.last_err.get_or_insert_with(|| io::Error::other(msg));
    }

    /// Record a failure that is cosca's own finding about a thread. No OS call failed, so the error
    /// has no OS code.
    fn fail(&mut self, call: &str, tid: u32, process_pid: u32, cause: impl std::fmt::Display) -> Visit {
        let msg = format!("{call} failed for thread {tid} of pid {process_pid}: {cause}");
        log::warn!("resume_initial_threads: {msg}");
        self.last_err.get_or_insert_with(|| io::Error::other(msg));
        Visit::Failed
    }

    /// Record the failure of the Win32 call `call`, keeping its code as the error's source.
    fn fail_win32(&mut self, call: &str, tid: u32, process_pid: u32, cause: windows::core::Error) -> Visit {
        let context = format!("{call} failed for thread {tid} of pid {process_pid}");
        let err = io_context(context, win32_io_error(cause));
        log::warn!("resume_initial_threads: {report}", report = crate::error::Report(&err));
        self.last_err.get_or_insert(err);
        Visit::Failed
    }
}

/// A thread handle, closed on drop.
#[derive(Debug)]
struct ThreadHandle(HANDLE);

impl Drop for ThreadHandle {
    fn drop(&mut self) {
        // SAFETY: the handle is owned and closed exactly once.
        unsafe { _ = CloseHandle(self.0) };
    }
}

/// Fail with the Win32 error a test armed for `step`, if any.
#[cfg(test)]
fn forced(step: fault::Step, tid: Option<u32>) -> windows::core::Result<()> {
    match fault::take_forced(step, tid) {
        Some(code) => Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
            code,
        ))),
        None => Ok(()),
    }
}

fn open_query(tid: u32) -> windows::core::Result<ThreadHandle> {
    #[cfg(test)]
    forced(fault::Step::QueryOpen, Some(tid))?;
    // SAFETY: plain Win32 call; the handle is owned by the returned guard.
    unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}

fn open_for_resume(tid: u32) -> windows::core::Result<ThreadHandle> {
    #[cfg(test)]
    forced(fault::Step::ResumeOpen, Some(tid))?;
    // SAFETY: plain Win32 call; the handle is owned by the returned guard.
    unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}

fn owner_of(thread: &ThreadHandle) -> windows::core::Result<u32> {
    #[cfg(test)]
    forced(fault::Step::Owner, None)?;
    // SAFETY: `thread` is a live handle with THREAD_QUERY_LIMITED_INFORMATION.
    match unsafe { GetProcessIdOfThread(thread.0) } {
        0 => Err(windows::core::Error::from_thread()),
        pid => Ok(pid),
    }
}

/// `ResumeThread`, answering the suspend count the thread had before: a frozen child's initial
/// thread has exactly 1.
fn resume_thread(thread: &ThreadHandle) -> windows::core::Result<u32> {
    #[cfg(test)]
    forced(fault::Step::Resume, None)?;
    // ResumeThread returns the previous suspend count, or u32::MAX on failure.
    // SAFETY: `thread` is a live handle with THREAD_SUSPEND_RESUME.
    match unsafe { ResumeThread(thread.0) } {
        u32::MAX => Err(windows::core::Error::from_thread()),
        previous => Ok(previous),
    }
}

/// `SuspendThread`, answering the suspend count the thread had before.
fn suspend_thread(thread: &ThreadHandle) -> windows::core::Result<u32> {
    // SuspendThread returns the previous suspend count, or u32::MAX on failure.
    // SAFETY: `thread` is a live handle with THREAD_SUSPEND_RESUME.
    match unsafe { windows::Win32::System::Threading::SuspendThread(thread.0) } {
        u32::MAX => Err(windows::core::Error::from_thread()),
        previous => Ok(previous),
    }
}

/// Walk one snapshot entry; `None` if the snapshot lists it under another pid. Ownership is then
/// re-checked on the opened handle by [`resume_if_owned`].
fn visit_thread_entry(
    entry: &windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32,
    process_pid: u32,
    walk: &mut Walk,
) -> Option<Visit> {
    (entry.th32OwnerProcessID == process_pid).then(|| resume_if_owned(entry.th32ThreadID, process_pid, walk))
}

/// Resume thread `tid` only if it provably belongs to `process_pid`.
///
/// The Toolhelp snapshot is stale by the time the thread is opened: an id can be released and
/// reused by another process, or released and not reused. So:
/// 1. Open with query-only rights and KEEP the handle: it pins the thread, so the id cannot be
///    reused while it is held. Read the owner through it. A thread's owner never changes.
/// 2. Only for the child's own thread, open with suspend/resume rights (the pin guarantees it
///    is the same thread), re-check the owner on that handle, and resume.
///
/// A stale id (reused, gone, or not openable by the child's creator) means the child's own thread
/// with that id has exited, so nothing is left to resume: skipped, not an error. A failed call on
/// the child's own thread is recorded in `last_err`.
fn resume_if_owned(tid: u32, process_pid: u32, walk: &mut Walk) -> Visit {
    use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER};

    let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
    let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);

    let query = match open_query(tid) {
        Ok(h) => h,
        Err(e) if e.code() == gone => {
            walk.skip(format!("thread {tid} no longer exists"));
            return Visit::Gone;
        }
        Err(e) if e.code() == denied => {
            walk.skip(format!(
                "thread {tid} cannot be opened for query (access denied), so it is not the child's"
            ));
            return Visit::Denied;
        }
        Err(e) => return walk.fail_win32("OpenThread(query)", tid, process_pid, e),
    };

    match owner_of(&query) {
        Ok(owner) if owner == process_pid => {}
        Ok(owner) => {
            walk.skip(format!("thread {tid} now belongs to pid {owner}"));
            return Visit::Foreign { owner };
        }
        Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
    }

    let resume = match open_for_resume(tid) {
        Ok(h) => h,
        Err(e) => return walk.fail_win32("OpenThread(suspend/resume)", tid, process_pid, e),
    };
    match owner_of(&resume) {
        Ok(again) if again == process_pid => {}
        Ok(again) => {
            return walk.fail(
                "OpenThread(suspend/resume)",
                tid,
                process_pid,
                format_args!("opened a thread of pid {again}, not the thread just checked"),
            )
        }
        Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
    }

    match resume_thread(&resume) {
        Ok(1) => {
            walk.resumed += 1;
            Visit::Resumed
        }
        Ok(_) if walk.expected == SuspendCount::Any => {
            walk.resumed += 1;
            Visit::Resumed
        }
        // Anything else leaves a process that is not running the way its creator left it. A count
        // above 1 is an initial thread still suspended after this resume (a debugger, an EDR agent
        // or the caller's own tooling suspended it in the window); 0 is an initial thread that was
        // already running, so the child ran before it was released.
        Ok(previous) => walk.fail(
            "ResumeThread",
            tid,
            process_pid,
            format_args!(
                "the previous suspend count was {previous}, not 1: {}",
                if previous > 1 {
                    "the thread is still suspended"
                } else {
                    "the thread was not suspended, so the child had already run"
                }
            ),
        ),
        Err(e) => walk.fail_win32("ResumeThread", tid, process_pid, e),
    }
}

/// The creation time of thread `tid` (100 ns ticks) if it is a thread of `process_pid`; `None` if
/// the id is stale (gone, another process's, not openable by the child's creator). The error names
/// the failed call.
fn creation_time_if_owned(tid: u32, process_pid: u32) -> Result<Option<u64>, (&'static str, windows::core::Error)> {
    use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, FILETIME};
    use windows::Win32::System::Threading::GetThreadTimes;

    let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
    let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);

    // SAFETY: plain Win32 call; the handle is owned by the returned guard, which pins the thread.
    let thread = match unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) } {
        Ok(h) => ThreadHandle(h),
        Err(e) if e.code() == gone || e.code() == denied => return Ok(None),
        Err(e) => return Err(("OpenThread(query)", e)),
    };
    match owner_of(&thread) {
        Ok(owner) if owner == process_pid => {}
        Ok(_) => return Ok(None),
        Err(e) => return Err(("GetProcessIdOfThread", e)),
    }
    let (mut created, mut exited, mut kernel, mut user) = (
        FILETIME::default(),
        FILETIME::default(),
        FILETIME::default(),
        FILETIME::default(),
    );
    #[cfg(test)]
    forced(fault::Step::CreationTime, Some(tid)).map_err(|e| ("GetThreadTimes", e))?;
    // SAFETY: `thread` is a live handle with THREAD_QUERY_LIMITED_INFORMATION; the out-parameters
    // are valid.
    unsafe { GetThreadTimes(thread.0, &mut created, &mut exited, &mut kernel, &mut user) }
        .map_err(|e| ("GetThreadTimes", e))?;
    #[cfg(test)]
    if fault::creation_times_are_equal() {
        return Ok(Some(1));
    }
    Ok(Some(
        (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
    ))
}

/// The id of the child's initial thread among `tids`: the thread of `process_pid` created first.
///
/// A frozen child has one thread, its initial one, until someone else starts another; a thread
/// created later has a later creation time. Thread ids say nothing about order, and the snapshot
/// lists threads in no promised order.
///
/// `None`, with the cause in `walk`, when the initial thread cannot be told: the snapshot lists no
/// thread of the child, every listed thread is stale, the creation time of a thread of the child
/// cannot be read (it might be the earlier), or the earliest two are equal. The
/// clock was measured only on Windows 11 10.0.26100, where 300 threads started back to back in one
/// process were 56 us or more apart; whether an older build's clock can tie is unmeasured, so a tie
/// is a failure, never a guess by thread id.
fn initial_thread_id(process_pid: u32, tids: &[u32], walk: &mut Walk) -> Option<u32> {
    let mut times = Vec::with_capacity(tids.len());
    for &tid in tids {
        match creation_time_if_owned(tid, process_pid) {
            Ok(Some(created)) => times.push((created, tid)),
            Ok(None) => walk.skip(format!(
                "thread {tid} is gone, is not pid {process_pid}'s, or cannot be opened by the child's creator"
            )),
            Err((call, e)) => {
                walk.fail_win32(call, tid, process_pid, e);
                return None;
            }
        }
    }
    match earliest_created(times) {
        Earliest::NoThread => None,
        Earliest::Unique(tid) => Some(tid),
        Earliest::Tie(first, second) => {
            walk.fail_unidentified(process_pid, first, second);
            None
        }
    }
}

/// The initial thread of `process_pid` among the snapshot's `entries`: [`initial_thread_id`] over the
/// ids the snapshot lists under that pid.
fn initial_thread_among(
    entries: &[windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32],
    process_pid: u32,
    walk: &mut Walk,
) -> Option<u32> {
    let own: Vec<u32> = entries
        .iter()
        .filter(|e| e.th32OwnerProcessID == process_pid)
        .map(|e| e.th32ThreadID)
        .collect();
    initial_thread_id(process_pid, &own, walk)
}

/// Which of some `(creation time, thread id)` pairs is the earliest.
#[derive(Debug, PartialEq, Eq)]
enum Earliest {
    NoThread,
    Unique(u32),
    /// Two threads share the earliest time, in the order they were listed: which came first is
    /// unknowable.
    Tie(u32, u32),
}

fn earliest_created(times: impl IntoIterator<Item = (u64, u32)>) -> Earliest {
    let mut best: Option<(u64, u32)> = None;
    let mut tied: Option<u32> = None;
    for (created, tid) in times {
        match best {
            Some((time, _)) if created > time => {}
            Some((time, _)) if created == time => {
                tied.get_or_insert(tid);
            }
            _ => {
                best = Some((created, tid));
                tied = None;
            }
        }
    }
    match (best, tied) {
        (None, _) => Earliest::NoThread,
        (Some((_, tid)), None) => Earliest::Unique(tid),
        (Some((_, first)), Some(second)) => Earliest::Tie(first, second),
    }
}

/// The pid of the process at `raw_handle`, or an error naming `GetProcessId` that keeps its Win32
/// code as its source.
///
/// `GetProcessId` answers 0 on failure, and a walk filtered to owner 0 would match the System
/// Idle process instead of the child.
fn process_pid_of(raw_handle: HANDLE) -> io::Result<u32> {
    // SAFETY: `GetProcessId` only reads the handle; an invalid one is reported as 0.
    let pid = unsafe { GetProcessId(raw_handle) };
    if pid == 0 {
        return Err(io_context(
            "GetProcessId failed on the child's handle",
            io::Error::last_os_error(),
        ));
    }
    Ok(pid)
}

/// The error for a walk that resumed nothing, naming why every listed thread was skipped.
fn none_resumed_error(process_pid: u32, last_skip: Option<&str>) -> io::Error {
    match last_skip {
        Some(reason) => io::Error::other(format!(
            "no suspended threads resumed: every thread the snapshot listed for pid {process_pid} was stale (last: {reason})"
        )),
        None => io::Error::other(format!(
            "no suspended threads resumed: the snapshot listed no threads for pid {process_pid}"
        )),
    }
}

/// The outcome of a finished walk. A failed resume is an error even when siblings resumed: a
/// thread left suspended is exactly the "frozen process" `resume_initial_threads` exists to rule
/// out, however many of its siblings got moving first.
fn walk_verdict(process_pid: u32, walk: Walk) -> io::Result<()> {
    let Walk {
        resumed,
        last_err,
        last_skip,
        ..
    } = walk;
    if let Some(e) = last_err {
        log::warn!(
            "resume_initial_threads: failed to resume one or more of this child's initial threads \
             ({resumed} resumed successfully before the failure): {report}",
            report = crate::error::Report(&e)
        );
        return Err(e);
    }
    if resumed == 0 {
        return Err(none_resumed_error(process_pid, last_skip.as_deref()));
    }
    Ok(())
}

/// Resume every suspended thread of the process at `proc_handle` after job assignment.
///
/// Why resume REGARDLESS of job-assign result: the kill-group race invariant
/// requires the child to be inside the job before executing, so it was spawned
/// frozen (CREATE_SUSPENDED). Whether or not job assignment succeeded, the child
/// MUST be resumed — a frozen process is unacceptable. If `ResumeThread` fails
/// the child is killed immediately and an error returned.
///
/// `expected` is what each resume's previous suspend count must be; see [`SuspendCount`].
///
/// PID-reuse safety: the caller holds the child's process handle (via the owning
/// `Child`), keeping its PID alive for the duration of the Toolhelp snapshot walk.
pub(crate) fn resume_initial_threads(
    proc_handle: std::os::windows::io::RawHandle,
    expected: SuspendCount,
) -> io::Result<()> {
    let raw_handle = HANDLE(proc_handle.cast());

    let mut walk = Walk {
        expected,
        ..Walk::default()
    };

    let process_pid = process_pid_of(raw_handle);
    debug_assert!(
        process_pid.is_ok(),
        "the caller must pass a live process handle: {process_pid:?}"
    );
    let process_pid = process_pid?;

    let entries = thread_entries()?;
    if walk.expected == SuspendCount::ExactlyOne {
        // Only the initial thread is resumed. The others are opened query-only, to read their
        // creation time, and that read failing fails the release.
        if let Some(initial) = initial_thread_among(&entries, process_pid, &mut walk) {
            resume_if_owned(initial, process_pid, &mut walk);
        }
    } else {
        for entry in &entries {
            visit_thread_entry(entry, process_pid, &mut walk);
        }
    }

    // Test-only: the injected entry goes through the same owner filter as a real one.
    #[cfg(test)]
    if let Some((tid, owner)) = fault::injected_entry() {
        let entry = windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32 {
            th32OwnerProcessID: owner.unwrap_or(process_pid),
            th32ThreadID: tid,
            ..Default::default()
        };
        fault::record_injected_visit(visit_thread_entry(&entry, process_pid, &mut walk));
    }

    walk_verdict(process_pid, walk)
}

/// Assign the process at `proc_handle` to a `KILL_ON_JOB_CLOSE` job and resume its
/// initial threads. `strict`: the request accepts no weaker mechanism than the job.
///
/// `proc_handle` must remain open for the whole call (it pins the pid against reuse during the
/// Toolhelp thread walk in `resume_initial_threads`). Every caller holds the process it spawned
/// across the call, so it does.
///
/// Returns `Ok(Some(JobHandle))` on full success (job assigned AND resumed).
/// Returns `Ok(None)` when job assignment fails and the request is not `strict`: the child is
/// resumed, the failure is logged at `warn`, and the caller falls back to the universal
/// `Containment::TreeWalk` mechanism (identity teardown).
/// Returns `Err` when job assignment fails and the request is `strict`: the child is left
/// suspended, for the caller to terminate. The failure says the program never ran when
/// [`prove_not_started`](not_started::prove_not_started) proves it from the process, and then holds the root's initial thread
/// suspended ([`ProvenRoot`]) so nothing resumes it before the caller's termination. A root that may
/// have run, or whose state cannot be read, fails as one that may have started, with a `warn` naming
/// why.
/// Returns `Err` when resume fails — a frozen child is unacceptable; the
/// child+job are killed and the failure propagates to fail the spawn. The resume failure is its
/// cause; a failure of the job's kill after it is its cleanup (a teardown failure of the failed
/// spawn), which cannot change the outcome.
pub(crate) fn attach_job(
    proc_handle: std::os::windows::io::RawHandle,
    strict: bool,
) -> Result<Option<JobHandle>, crate::containment::dispatch::AttachFailure> {
    let job_result = match assign_held(proc_handle) {
        Err(e) if strict => {
            let proven = match not_started::prove_not_started(proc_handle) {
                Ok(proven) => Some(Box::new(proven)),
                Err(why) => {
                    log::warn!(
                        "the child may have run, so its failed Job assignment is not a not-started failure: {why}"
                    );
                    None
                }
            };
            let detail = "the child could not be put in its Job Object";
            return Err(crate::containment::dispatch::AttachFailure {
                cause: crate::error::Error::Containment {
                    detail: if proven.is_some() {
                        format!("{detail}, so the program did not run")
                    } else {
                        detail.to_owned()
                    },
                    source: Some(crate::error::Error::io_cause(e)),
                },
                cleanup: None,
                not_started: proven.is_some(),
                proven,
            });
        }
        other => other,
    };

    // Resume REGARDLESS of job assignment result. A frozen child cannot be left running.
    if let Err(resume_err) = resume_initial_threads(proc_handle, SuspendCount::Any) {
        let cleanup = match job_result {
            // Kill via the job first (catches any threads the walk may have missed).
            Ok(job) => job
                .hard_kill()
                .err()
                .map(|e| crate::error::Error::io_cause(crate::error::io_context("terminating the job", e))),
            Err(_) => None,
        };
        // Both the warn and the `cleanup` are deliberate: a failed kill logs at warn naming the
        // resource (principle 7), and the error carries it too.
        if let Some(failure) = &cleanup {
            log::warn!(
                "job kill after a failed resume also failed ({report}); the tree may still be running",
                report = crate::error::Report(&**failure)
            );
        }
        return Err(crate::containment::dispatch::AttachFailure {
            cause: crate::error::Error::Containment {
                detail: "the child's initial threads could not be resumed".to_owned(),
                source: Some(crate::error::Error::io_cause(resume_err)),
            },
            cleanup: crate::error::Failures::collect(cleanup),
            not_started: false,
            proven: None,
        });
    }

    match job_result {
        Ok(job) => Ok(Some(job)),
        Err(e) => {
            // Job assignment failed, and the request accepts a weaker mechanism: dispatch
            // falls back to the TreeWalk mechanism.
            let child = process_pid_of(HANDLE(proc_handle.cast()))
                .map_or_else(|_| "the child".to_owned(), |pid| format!("pid {pid}"));
            log::warn!(
                "Job Object containment: {child} could not be put in its Job Object ({report}); falling back to a process-tree walk",
                report = crate::error::Report(&e)
            );
            Ok(None)
        }
    }
}

/// Test-only membership probe: whether `pid` is inside the Job Object `job`, via
/// `IsProcessInJob` against that job handle (not "any job"). Membership is immutable once assigned,
/// so it is deterministic for a handle-pinned child regardless of run state. Shared by the sync and
/// async `Child::test_job_handle_contains_self` accessors (both compiled outside `cfg(test)` so
/// integration crates can call them). Panics, naming the Win32 error, when `OpenProcess` or
/// `IsProcessInJob` fails, so a failed query is not read as "not a member".
pub(crate) fn job_contains_pid(job: &JobHandle, pid: u32) -> bool {
    use windows::Win32::System::JobObjects::IsProcessInJob;
    use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION};

    // Open the child process by PID; the backend doesn't expose its handle.
    // SAFETY: standard Win32 call; the handle is closed below.
    let process_handle = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION, false, pid) }
        .unwrap_or_else(|e| panic!("OpenProcess({pid}) failed: {e}"));

    let mut in_job = windows::core::BOOL(0);
    // SAFETY: both handles are valid for the duration of the call.
    let queried = unsafe { IsProcessInJob(process_handle, Some(job.raw), &mut in_job) };
    // SAFETY: `process_handle` was opened above and must be closed.
    unsafe {
        _ = CloseHandle(process_handle);
    }
    queried.unwrap_or_else(|e| panic!("IsProcessInJob({pid}) failed: {e}"));
    in_job.as_bool()
}

/// The limit flags `job` holds now.
pub(crate) fn job_limit_flags(
    job: &JobHandle,
) -> windows::core::Result<windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT> {
    use windows::Win32::System::JobObjects::{JobObjectBasicLimitInformation, JOBOBJECT_BASIC_LIMIT_INFORMATION};

    let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
    // SAFETY: the handle is live for the call, and `info` is a correctly sized out-parameter.
    unsafe {
        QueryInformationJobObject(
            Some(job.raw),
            JobObjectBasicLimitInformation,
            std::ptr::addr_of_mut!(info).cast(),
            size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
            None,
        )
    }?;
    Ok(info.LimitFlags)
}

/// Test-only: whether the Job Object `job` kills its members when its last handle closes. Panics,
/// naming the cause, when the query fails, so a failed query is not read as "no kill-on-close".
pub(crate) fn job_kills_on_close(job: &JobHandle) -> bool {
    let flags = job_limit_flags(job).unwrap_or_else(|e| panic!("querying the job's limits failed: {e}"));
    flags.0 & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0 != 0
}

#[path = "windows/not_started.rs"]
mod not_started;
pub(crate) use not_started::ProvenRoot;

#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;

#[cfg(test)]
#[path = "windows_confirm_tests.rs"]
mod windows_confirm_tests;