windows-file-watcher 0.2.6

Memory-safe, queue-mediated Windows path-change watching over ReadDirectoryChangesW, with a coarse fallback.
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
// Copyright (c) 2026 Mike Grier
//! Unit tests for the detailed single-directory watcher.
//!
//! Every test drives a real `ReadDirectoryChangesW` against a real temp
//! directory, because what is under test is the arm/complete/re-arm loop against
//! the kernel, not a model of it.

use std::num::NonZeroUsize;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use windows_sys::Win32::Foundation::{
    ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_IO_PENDING, ERROR_NOT_SUPPORTED, FILETIME,
    HANDLE,
};
use windows_sys::Win32::Storage::FileSystem::{FILE_WRITE_ATTRIBUTES, SetFileTime};

use super::{ArmGate, DirectoryWatcher, Issued, ReadBuffer, lock};
use crate::directory::{
    DirectoryHandle, FailureCode, FaultDetail, OpenFailure, VolumeIdentity, classify_detail,
};
use crate::notify::{ChangeKind, DesyncCause};
use crate::queue::{Notification, Receiver, Sender, WatchId, channel, channel_with_bound};
use crate::retry::{FaultOperation, WatchMode};
use crate::route::{Route, RouteScope};
use crate::testing::TempDir;
use crate::watch::{RetryMode, VolumeChangeDecision, VolumeChangePolicy};

/// Upper bound for waiting on a notification the kernel really should deliver.
///
/// 5s, lowered from 30s once the cost was measured (M15.7). Instrumenting every
/// wait in this suite: 45 of 46 complete in **2.5ms or less**, and the entire
/// tail is one test gated on the retry *backoff timer* at ~515ms -- structural,
/// not notification latency. None of it moved under 4x oversubscription (three
/// concurrent suites plus a full release build), so the budget was absorbing no
/// contention it needed to.
///
/// Why lower it rather than leave it generous: when a mutation breaks delivery,
/// dozens of these waits each burn the full budget on the way to failing, and
/// the suite then overruns cargo-mutants' kill deadline -- so the mutant is
/// filed as `timeout` rather than `caught`, detected but recorded as though it
/// were not. Measured on one such mutant: **93.6s at 30s (killed) against 31.8s
/// at 5s (a clean red test)**.
///
/// The residual risk, stated because it is real: that was one 12-core developer
/// machine. 5s is ~10x the structural outlier and ~2000x the p95, but a much
/// slower runner is unmeasured. If this ever flakes, that is the reason, and the
/// answer is to raise it -- not to conclude the tests are wrong.
const NOTIFY_TIMEOUT: Duration = Duration::from_secs(5);

/// The subscription every test in this module watches under.
fn test_watch() -> WatchId {
    WatchId::from_raw(1)
}

/// A route with no fault-recovery involvement: `Defaults` retry, no liveness
/// reporting, no standing fault slot. What every test in this module needs
/// unless it is specifically exercising M5's fault machinery.
fn plain_route(watch: WatchId, scope: RouteScope, sink: Sender) -> Route {
    Route {
        watch,
        scope,
        sink,
        retry: RetryMode::Defaults,
        report_liveness: false,
        on_volume_change: VolumeChangePolicy::AutoContinue,
        fault_slot: None,
    }
}

/// Drains the queue in the background, so a test can assert on what has arrived
/// without ever running test code on the crate's cadence path.
///
/// This mirrors what a real client does: the crate enqueues, the client receives
/// on a thread of its own choosing.
struct Drained {
    seen: Arc<std::sync::Mutex<Vec<Notification>>>,
    _pump: std::thread::JoinHandle<()>,
}

impl Drained {
    fn start(receiver: Receiver) -> Self {
        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = Arc::clone(&seen);
        // `recv` returns None once every sender is gone, so this thread exits on
        // teardown rather than needing a stop flag.
        let pump = std::thread::spawn(move || {
            while let Some(item) = receiver.recv() {
                sink.lock().expect("record").push(item);
            }
        });
        Self { seen, _pump: pump }
    }

    fn notifications(&self) -> Vec<Notification> {
        self.seen.lock().expect("read").clone()
    }

    /// Every change across every delivered batch, flattened.
    fn changes(&self) -> Vec<(ChangeKind, String)> {
        self.notifications()
            .into_iter()
            .filter_map(|item| match item {
                Notification::Batch { changes, .. } => Some(changes),
                Notification::Desync { .. }
                | Notification::Completion { .. }
                | Notification::Suspended { .. }
                | Notification::Resumed { .. }
                | Notification::Established { .. }
                | Notification::RetryQuestion { .. }
                | Notification::VolumeChanged { .. } => None,
            })
            .flatten()
            .map(|change| {
                (
                    change.kind,
                    change.name.to_os_string().to_string_lossy().into_owned(),
                )
            })
            .collect()
    }

    fn desyncs(&self) -> Vec<DesyncCause> {
        self.notifications()
            .into_iter()
            .filter_map(|item| match item {
                Notification::Desync { cause, .. } => Some(cause),
                Notification::Batch { .. }
                | Notification::Completion { .. }
                | Notification::Suspended { .. }
                | Notification::Resumed { .. }
                | Notification::Established { .. }
                | Notification::RetryQuestion { .. }
                | Notification::VolumeChanged { .. } => None,
            })
            .collect()
    }

    /// Block until `predicate` holds over the drained notifications, failing
    /// rather than hanging if it never does.
    fn wait_until<F>(&self, what: &str, predicate: F)
    where
        F: Fn(&Drained) -> bool,
    {
        let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
        while !predicate(self) {
            assert!(
                std::time::Instant::now() < deadline,
                "timed out waiting for {what}; saw {:?}",
                self.notifications()
            );
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    fn wait_for_any(&self) {
        self.wait_until("any notification", |d| !d.notifications().is_empty());
    }

    fn wait_for_name(&self, name: &str) {
        self.wait_until(&format!("a change named {name}"), |d| {
            d.changes().iter().any(|(_, seen)| seen == name)
        });
    }
}

/// Start a watcher over `dir`, draining everything it enqueues.
fn watch(dir: &Path, subtree: bool) -> (DirectoryWatcher, Drained) {
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir).expect("open the directory");
    let route = plain_route(test_watch(), RouteScope::Directory { subtree }, sender);
    let watcher =
        DirectoryWatcher::start(handle, dir.to_path_buf(), route).expect("start the watcher");
    (watcher, Drained::start(receiver))
}

// --- the buffer ---

#[test]
fn the_completion_buffer_is_dword_aligned() {
    // ReadDirectoryChangesW requires DWORD alignment, which a Box<[u8]> would
    // not guarantee. This is the reason the buffer is u32-backed.
    for bytes in [1_usize, 3, 4, 17, 1024, 64 * 1024] {
        let mut buffer = ReadBuffer::new(bytes);
        let address = buffer.as_mut_ptr() as usize;
        assert_eq!(
            address % 4,
            0,
            "buffer of {bytes} bytes is not DWORD-aligned"
        );
    }
}

#[test]
fn the_completion_buffer_rounds_up_and_is_never_empty() {
    assert_eq!(
        ReadBuffer::new(0).byte_len(),
        4,
        "a zero request still allocates"
    );
    assert_eq!(ReadBuffer::new(1).byte_len(), 4);
    assert_eq!(ReadBuffer::new(4).byte_len(), 4);
    assert_eq!(ReadBuffer::new(5).byte_len(), 8);
    assert_eq!(ReadBuffer::new(64 * 1024).byte_len(), 64 * 1024);
}

#[test]
fn the_completion_buffer_clamps_an_overlong_fill() {
    // A length beyond the allocation must be clamped rather than trusted, or a
    // bad completion length would be an out-of-bounds read.
    let buffer = ReadBuffer::new(16);
    assert_eq!(buffer.filled(usize::MAX).len(), 16);
    assert_eq!(buffer.filled(8).len(), 8);
    assert_eq!(buffer.filled(0).len(), 0);
}

// --- arming ---

#[test]
fn starting_a_watch_arms_a_read() {
    let dir = TempDir::new("arm");
    let (watcher, _collected) = watch(dir.path(), false);
    assert!(watcher.is_watching());
    assert!(watcher.stop_reason().is_none());
    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_watcher_can_be_dropped_with_a_read_outstanding() {
    // The read is still pending here; teardown must cancel and drain rather than
    // block forever or leak the operation.
    let dir = TempDir::new("drop-outstanding");
    let (watcher, _collected) = watch(dir.path(), false);
    drop(watcher);
    dir.cleanup();
}

#[test]
fn many_watchers_can_start_and_stop_on_one_directory() {
    let dir = TempDir::new("many-watchers");
    for _ in 0..16 {
        let (watcher, _collected) = watch(dir.path(), false);
        drop(watcher);
    }
    dir.cleanup();
}

// --- completions ---

#[test]
fn creating_a_file_reports_it_as_added() {
    let dir = TempDir::new("added");
    let (watcher, collected) = watch(dir.path(), false);

    std::fs::write(dir.path().join("created.txt"), b"x").expect("create a file");
    collected.wait_for_name("created.txt");

    let changes = collected.changes();
    assert!(
        changes
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Added && name == "created.txt"),
        "expected an Added for created.txt, saw {changes:?}"
    );
    assert!(
        collected
            .notifications()
            .iter()
            .all(|item| item.watch() == test_watch()),
        "every notification is tagged with the subscription it belongs to"
    );
    drop(watcher);
    dir.cleanup();
}

#[test]
fn deleting_a_file_reports_it_as_removed() {
    let dir = TempDir::new("removed");
    let target = dir.path().join("doomed.txt");
    std::fs::write(&target, b"x").expect("create a file");

    let (watcher, collected) = watch(dir.path(), false);
    std::fs::remove_file(&target).expect("remove the file");
    collected.wait_for_name("doomed.txt");

    let changes = collected.changes();
    assert!(
        changes
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Removed && name == "doomed.txt"),
        "expected a Removed for doomed.txt, saw {changes:?}"
    );
    drop(watcher);
    dir.cleanup();
}

#[test]
fn renaming_a_file_reports_both_halves_distinctly() {
    // D-9: the crate never joins a rename into one event.
    let dir = TempDir::new("renamed");
    let before = dir.path().join("before.txt");
    std::fs::write(&before, b"x").expect("create a file");

    let (watcher, collected) = watch(dir.path(), false);
    std::fs::rename(&before, dir.path().join("after.txt")).expect("rename");

    // Both halves can straddle a completion boundary, so wait until both are in.
    collected.wait_until("both rename halves", |d| {
        let changes = d.changes();
        changes
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::RenamedOldName && name == "before.txt")
            && changes
                .iter()
                .any(|(kind, name)| *kind == ChangeKind::RenamedNewName && name == "after.txt")
    });

    drop(watcher);
    dir.cleanup();
}

#[test]
fn the_watcher_re_arms_and_reports_a_later_change() {
    // The point of the re-arm: a second, independent change after the first
    // completion has already been delivered.
    let dir = TempDir::new("re-arm");
    let (watcher, collected) = watch(dir.path(), false);

    std::fs::write(dir.path().join("first.txt"), b"x").expect("first");
    collected.wait_for_name("first.txt");
    std::fs::write(dir.path().join("second.txt"), b"x").expect("second");
    collected.wait_for_name("second.txt");

    assert!(watcher.is_watching(), "still watching after re-arming");
    drop(watcher);
    dir.cleanup();
}

#[test]
fn many_sequential_changes_are_all_reported() {
    let dir = TempDir::new("sequential");
    let (watcher, collected) = watch(dir.path(), false);

    const COUNT: usize = 12;
    for index in 0..COUNT {
        std::fs::write(dir.path().join(format!("file-{index}.txt")), b"x").expect("create");
        // One at a time, so each has its own completion to be reported in and
        // the test exercises repeated re-arming rather than one batch.
        collected.wait_for_name(&format!("file-{index}.txt"));
    }

    assert!(watcher.is_watching());
    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_subtree_watch_reports_a_change_in_a_child_directory() {
    let dir = TempDir::new("subtree");
    let child = dir.path().join("child");
    std::fs::create_dir(&child).expect("create child dir");

    let (watcher, collected) = watch(dir.path(), true);
    std::fs::write(child.join("nested.txt"), b"x").expect("create nested");
    collected.wait_until("the nested file", |d| {
        d.changes()
            .iter()
            .any(|(_, name)| name.contains("nested.txt"))
    });

    let changes = collected.changes();
    // The name is relative to the opened directory (D-8), so it includes the
    // child component rather than being the bare leaf.
    assert!(
        changes
            .iter()
            .any(|(_, name)| name.contains('\\') || name.contains("child")),
        "the name is relative to the watched directory, saw {changes:?}"
    );
    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_non_subtree_watch_ignores_a_change_in_a_child_directory() {
    let dir = TempDir::new("no-subtree");
    let child = dir.path().join("child");
    std::fs::create_dir(&child).expect("create child dir");

    let (watcher, collected) = watch(dir.path(), false);
    std::fs::write(child.join("nested.txt"), b"x").expect("create nested");
    // Then a change that *is* in scope, so there is a definite point by which
    // the out-of-scope one would have arrived if it were going to.
    std::fs::write(dir.path().join("direct.txt"), b"x").expect("create direct");
    collected.wait_for_name("direct.txt");

    let changes = collected.changes();
    assert!(
        !changes.iter().any(|(_, name)| name.contains("nested.txt")),
        "a non-recursive watch must not report a nested change, saw {changes:?}"
    );
    drop(watcher);
    dir.cleanup();
}

// --- overflow ---

#[test]
fn a_tiny_buffer_surfaces_the_kernel_overflow_as_a_desync() {
    // The kernel reports overflow as a zero-byte completion, which the decoder
    // turns into Desync { Overflow } (D-12). A 4-byte buffer cannot hold even one
    // record, so any change overflows it.
    let dir = TempDir::new("overflow");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher =
        DirectoryWatcher::start_with(handle, dir.path().to_path_buf(), 4, route).expect("start");
    let collected = Drained::start(receiver);

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    let mut index = 0;
    loop {
        std::fs::write(dir.path().join(format!("burst-{index}.txt")), b"x").expect("create");
        index += 1;
        if collected.desyncs().contains(&DesyncCause::Overflow) {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "a 4-byte buffer never produced an overflow desync"
        );
        // Throttled rather than spinning: an untimed loop here creates files as
        // fast as the filesystem accepts them, which buries the temp directory
        // and makes cleanup dominate the test.
        std::thread::sleep(Duration::from_millis(5));
    }

    drop(watcher);
    dir.cleanup();
}

// --- teardown ---

#[test]
fn dropping_while_changes_are_arriving_does_not_deadlock() {
    // Regression: teardown cancels the outstanding read and waits for rundown,
    // but a completion callback already running could re-arm *after* the
    // cancellation. Rundown would then wait forever, because only a future
    // directory change could complete that fresh read. Arming is gated against
    // teardown to make that impossible.
    for _ in 0..8 {
        let dir = TempDir::new("teardown-race");
        let (watcher, collected) = watch(dir.path(), false);

        let churn_dir = dir.path().to_path_buf();
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let churn_stop = Arc::clone(&stop);
        let churn = std::thread::spawn(move || {
            let mut index = 0;
            while !churn_stop.load(std::sync::atomic::Ordering::Relaxed) {
                let _ = std::fs::write(churn_dir.join(format!("churn-{index}.txt")), b"x");
                index += 1;
                std::thread::sleep(Duration::from_millis(1));
            }
        });

        // Drop while completions are actively being delivered and re-armed.
        collected.wait_for_any();
        drop(watcher);

        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        churn.join().expect("churn thread");
        dir.cleanup();
    }
}

#[test]
fn a_dropped_watcher_stops_delivering() {
    let dir = TempDir::new("stops-delivering");

    // Received inline rather than through `Drained`, deliberately. What this
    // test claims is that teardown makes a later change *unobservable*, and a
    // background pump puts an unsynchronised thread between the queue and the
    // assertion: a notification enqueued before teardown but drained after the
    // count was sampled is indistinguishable from a post-teardown delivery. That
    // is not hypothetical -- it is what made this test intermittent on CI, and a
    // longer sleep would only have widened the window it depends on. Receiving
    // here lets the drain be a checked fact instead of a race against a sleep.
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open the directory");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start(handle, dir.path().to_path_buf(), route)
        .expect("start the watcher");

    fn record(item: Notification, into: &mut Vec<String>) {
        if let Notification::Batch { changes, .. } = item {
            into.extend(
                changes
                    .into_iter()
                    .map(|change| change.name.to_os_string().to_string_lossy().into_owned()),
            );
        }
    }

    // One `std::fs::write` is a create *and* a write, so it yields more than one
    // notification, and they need not share a completion. Waiting only for the
    // first change named `before-drop.txt` therefore leaves the rest in flight
    // on purpose: an in-flight completion is precisely the state teardown has to
    // be correct in, and the state this test exists to cover.
    let mut delivered: Vec<String> = Vec::new();
    std::fs::write(dir.path().join("before-drop.txt"), b"x").expect("create");
    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while !delivered.iter().any(|name| name == "before-drop.txt") {
        assert!(
            std::time::Instant::now() < deadline,
            "timed out waiting for a change named before-drop.txt; saw {delivered:?}"
        );
        if let Some(item) = receiver.recv_timeout(Duration::from_millis(50)) {
            record(item, &mut delivered);
        }
    }

    drop(watcher);
    std::fs::write(dir.path().join("after-drop.txt"), b"x").expect("create");

    // Teardown releases the last sender, so the queue can be drained to the end
    // of the stream rather than to an arbitrary deadline. Drain until
    // `recv_timeout` yields `None`, then assert `is_disconnected` -- that second
    // step is load-bearing rather than decorative, because `recv_timeout`
    // reports `None` on a timeout too, and only the disconnection distinguishes
    // "no sender remains" from "nothing arrived in time". A timeout would end
    // the loop early and leave the assertions below covering part of the
    // delivered set while appearing to cover all of it.
    //
    // Past a genuine disconnection nothing can ever be added, so everything the
    // watcher will ever deliver is in `delivered` -- including anything a
    // still-running callback managed to enqueue, since a live callback implies a
    // live sender and would keep the drain going.
    while let Some(item) = receiver.recv_timeout(NOTIFY_TIMEOUT) {
        record(item, &mut delivered);
    }
    assert!(
        receiver.is_disconnected(),
        "teardown must release the last sender; the drain above stopped on a \
         timeout rather than on the end of the stream, so the assertions below \
         would not cover the whole delivered set. Saw {delivered:?}"
    );

    assert!(
        !delivered.iter().any(|name| name == "after-drop.txt"),
        "a change after teardown must never be reported; saw {delivered:?}"
    );
    assert!(
        delivered.iter().all(|name| name == "before-drop.txt"),
        "a dropped watcher must deliver nothing further; saw {delivered:?}"
    );

    dir.cleanup();
}

// --- teardown (M2.4) ---

#[test]
fn stop_is_idempotent_and_drop_after_it_is_safe() {
    // Teardown is one operation with two triggers, so an explicit stop followed
    // by the implicit one must not double-cancel or double-drain.
    let dir = TempDir::new("stop-idempotent");
    let (watcher, _collected) = watch(dir.path(), false);

    watcher.stop();
    watcher.stop();
    watcher.stop();
    assert_eq!(watcher.gate(), ArmGate::TornDown);
    assert!(!watcher.is_watching());

    drop(watcher);
    dir.cleanup();
}

#[test]
fn stop_closes_the_gate_permanently() {
    // A watcher never re-opens: teardown is the one permanent reason for the
    // not-re-arming state, unlike the fault and backpressure reasons to come.
    let dir = TempDir::new("gate-permanent");
    let (watcher, collected) = watch(dir.path(), false);
    assert_eq!(watcher.gate(), ArmGate::Open);
    assert!(watcher.is_watching());

    watcher.stop();
    assert_eq!(watcher.gate(), ArmGate::TornDown);

    // A change after teardown must not re-open anything or produce a delivery.
    std::fs::write(dir.path().join("after-stop.txt"), b"x").expect("create");
    std::thread::sleep(Duration::from_millis(200));
    assert!(
        !collected
            .changes()
            .iter()
            .any(|(_, name)| name == "after-stop.txt"),
        "a stopped watcher must not report anything further"
    );

    drop(watcher);
    dir.cleanup();
}

#[test]
fn teardown_releases_the_sender_so_the_receiver_disconnects() {
    // A client's drain loop terminates on `recv() -> None`. If teardown left the
    // sender alive the loop would block forever on a queue nothing can fill,
    // which is a hang rather than a shutdown.
    let dir = TempDir::new("teardown-disconnect");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start(handle, dir.path().to_path_buf(), route)
        .expect("start the watcher");

    assert!(!receiver.is_disconnected(), "live while the watcher exists");
    drop(watcher);

    assert!(
        receiver.is_disconnected(),
        "dropping the watcher must release the queue sender"
    );
    // A blocking `recv()`, bounded by a thread and a deadline rather than by
    // swapping in `recv_timeout` -- the claim being made is about a *drain loop*
    // terminating, and a bounded read does not test that (M15.11).
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(receiver.recv().is_none());
    });
    match rx.recv_timeout(NOTIFY_TIMEOUT) {
        Ok(ended) => assert!(ended, "a drain loop must terminate rather than block"),
        Err(_) => panic!("a blocking recv did not return once the watcher was gone"),
    }

    dir.cleanup();
}

#[test]
fn teardown_with_a_read_outstanding_completes_promptly() {
    // Nothing is changing in the directory, so the outstanding read can only be
    // retired by the cancellation. If teardown waited on the read instead of
    // cancelling it, this would hang rather than fail.
    let dir = TempDir::new("teardown-outstanding");
    let (watcher, _collected) = watch(dir.path(), false);

    let started = std::time::Instant::now();
    drop(watcher);
    let elapsed = started.elapsed();

    assert!(
        elapsed < Duration::from_secs(5),
        "teardown took {elapsed:?}; the outstanding read was not cancelled"
    );
    dir.cleanup();
}

#[test]
fn teardown_is_prompt_even_with_a_subtree_watch_over_a_populated_tree() {
    // A recursive watch over a deep tree has more for the kernel to unwind, so
    // it is the case most likely to expose a teardown that waits rather than
    // cancels.
    let dir = TempDir::new("teardown-deep");
    let mut nested = dir.path().to_path_buf();
    for level in 0..12 {
        nested = nested.join(format!("level-{level}"));
    }
    std::fs::create_dir_all(&nested).expect("create deep tree");
    for index in 0..32 {
        std::fs::write(nested.join(format!("f-{index}.txt")), b"x").expect("write");
    }

    let (watcher, _collected) = watch(dir.path(), true);
    let started = std::time::Instant::now();
    drop(watcher);
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "recursive teardown did not converge promptly"
    );
    dir.cleanup();
}

#[test]
fn many_watchers_tear_down_concurrently_without_wedging() {
    // Each watcher runs its own cancel-and-drain against a shared pool, so this
    // is where a teardown that blocked a pool thread would starve the others.
    let dir = TempDir::new("teardown-concurrent");
    let mut watchers = Vec::new();
    let mut drains = Vec::new();
    for _ in 0..16 {
        let (watcher, collected) = watch(dir.path(), false);
        watchers.push(watcher);
        drains.push(collected);
    }

    // Churn so completions are in flight while the teardowns run.
    for index in 0..8 {
        std::fs::write(dir.path().join(format!("churn-{index}.txt")), b"x").expect("write");
    }

    let started = std::time::Instant::now();
    let handles: Vec<_> = watchers
        .into_iter()
        .map(|watcher| std::thread::spawn(move || drop(watcher)))
        .collect();
    for handle in handles {
        handle.join().expect("teardown thread");
    }
    assert!(
        started.elapsed() < Duration::from_secs(20),
        "concurrent teardown wedged"
    );

    dir.cleanup();
}

#[test]
fn teardown_from_a_thread_other_than_the_creator_is_safe() {
    // `DirectoryWatcher` is owned, and its teardown blocks; moving it to another
    // thread to be dropped is the shape a monitor will use when it releases a
    // watcher from its servicing path rather than from the caller's.
    let dir = TempDir::new("teardown-moved");
    let (watcher, collected) = watch(dir.path(), false);
    std::fs::write(dir.path().join("before-move.txt"), b"x").expect("write");
    collected.wait_for_name("before-move.txt");

    std::thread::spawn(move || drop(watcher))
        .join()
        .expect("teardown thread");

    dir.cleanup();
}

// --- backpressure (D-29) ---

/// A watcher over `dir` feeding a queue of exactly `bound` notifications, with no
/// one draining it.
fn watch_bounded(dir: &Path, bound: usize) -> (DirectoryWatcher, Receiver) {
    let handle = DirectoryHandle::open(dir).expect("open the watched directory");
    let (sender, receiver) =
        channel_with_bound(NonZeroUsize::new(bound).expect("a non-zero bound"));
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher =
        DirectoryWatcher::start(handle, dir.to_path_buf(), route).expect("arm the first read");
    (watcher, receiver)
}

/// Block until `predicate` holds, failing rather than hanging.
fn wait_for<F: FnMut() -> bool>(what: &str, mut predicate: F) {
    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while !predicate() {
        assert!(
            std::time::Instant::now() < deadline,
            "timed out waiting for {what}"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// Make changes until `predicate` holds, failing rather than hanging.
fn churn_until<F: Fn() -> bool>(dir: &Path, what: &str, predicate: F) {
    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    let mut index = 0_usize;
    while !predicate() {
        assert!(
            std::time::Instant::now() < deadline,
            "timed out waiting for {what} after {index} changes"
        );
        std::fs::write(dir.join(format!("churn-{index}.txt")), b"x").expect("create");
        index += 1;
        std::thread::sleep(Duration::from_millis(5));
    }
}

#[test]
fn a_full_queue_stops_the_re_arm_rather_than_dropping() {
    let dir = TempDir::new("backpressure-stop");
    let (watcher, receiver) = watch_bounded(dir.path(), 1);

    churn_until(dir.path(), "the watcher to pause", || {
        watcher.gate() == ArmGate::Backpressured
    });

    assert_eq!(watcher.gate(), ArmGate::Backpressured);
    assert!(
        watcher.is_watching(),
        "a paused watcher is not a stopped one: {:?}",
        watcher.stop_reason()
    );
    assert!(receiver.len() <= 1, "the bound still holds");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn draining_resumes_a_paused_watcher() {
    let dir = TempDir::new("backpressure-resume");
    let (watcher, receiver) = watch_bounded(dir.path(), 1);

    churn_until(dir.path(), "the watcher to pause", || {
        watcher.gate() == ArmGate::Backpressured
    });

    // Nothing else will prod it: the resume has to come from the client draining.
    while receiver.try_recv().is_some() {}
    wait_for("the watcher to resume", || watcher.gate() == ArmGate::Open);

    // And it is really watching again, not merely reporting that it is.
    std::fs::write(dir.path().join("after.txt"), b"after").expect("create");
    wait_for("a change after the pause", || {
        !receiver.is_empty() || receiver.latched() > 0
    });

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_pause_is_a_grace_period_rather_than_a_loss() {
    // The property that makes refusing to re-arm better than dropping at the
    // enqueue: with no read outstanding the kernel keeps accumulating, so a
    // client that drains in time loses nothing at all (D-29).
    let dir = TempDir::new("backpressure-grace");
    let (watcher, receiver) = watch_bounded(dir.path(), 4);

    churn_until(dir.path(), "the watcher to pause", || {
        watcher.gate() == ArmGate::Backpressured
    });

    // Made while no read is armed, so this exists only in the kernel's buffer.
    std::fs::write(dir.path().join("during-the-pause.txt"), b"x").expect("create");

    let mut seen: Vec<String> = Vec::new();
    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    loop {
        assert!(
            std::time::Instant::now() < deadline,
            "the change made during the pause never arrived; saw {seen:?}"
        );
        while let Some(item) = receiver.try_recv() {
            if let Notification::Batch { changes, .. } = item {
                seen.extend(
                    changes
                        .iter()
                        .map(|c| c.name.to_os_string().to_string_lossy().into_owned()),
                );
            }
        }
        if seen.iter().any(|name| name == "during-the-pause.txt") {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    drop(watcher);
    dir.cleanup();
}

#[test]
fn teardown_while_paused_is_prompt() {
    // A paused watcher has no read outstanding, so teardown must not wait for a
    // completion that is never coming.
    let dir = TempDir::new("backpressure-teardown");
    let (watcher, _receiver) = watch_bounded(dir.path(), 1);

    churn_until(dir.path(), "the watcher to pause", || {
        watcher.gate() == ArmGate::Backpressured
    });

    let started = std::time::Instant::now();
    watcher.stop();
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "teardown of a paused watcher took {:?}",
        started.elapsed()
    );
    assert_eq!(watcher.gate(), ArmGate::TornDown);

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_torn_down_watcher_is_not_resumed_by_a_drain() {
    // The gate's reasons are not interchangeable: teardown is permanent, and a
    // drain that prods every registered producer must not re-open it.
    let dir = TempDir::new("backpressure-torn");
    let (watcher, receiver) = watch_bounded(dir.path(), 1);

    churn_until(dir.path(), "the watcher to pause", || {
        watcher.gate() == ArmGate::Backpressured
    });
    watcher.stop();

    while receiver.try_recv().is_some() {}
    std::thread::sleep(Duration::from_millis(50));
    assert_eq!(
        watcher.gate(),
        ArmGate::TornDown,
        "a drain must not resurrect a torn-down watcher"
    );

    drop(watcher);
    dir.cleanup();
}

#[test]
fn pausing_and_resuming_repeatedly_does_not_wedge() {
    // The lost-wakeup hazard the gate's re-check exists for: a resume that runs
    // between the room check and the gate being set would otherwise leave the
    // watcher parked with room available and nothing left to prod it. Cycling
    // many times makes that window likely to be hit.
    let dir = TempDir::new("backpressure-cycle");
    let (watcher, receiver) = watch_bounded(dir.path(), 2);

    for round in 0..20 {
        churn_until(dir.path(), "the watcher to pause", || {
            watcher.gate() == ArmGate::Backpressured
        });
        while receiver.try_recv().is_some() {}
        wait_for("the watcher to resume", || watcher.gate() == ArmGate::Open);
        assert!(
            watcher.is_watching(),
            "round {round}: {:?}",
            watcher.stop_reason()
        );
    }

    drop(watcher);
    dir.cleanup();
}

#[test]
fn an_overflowed_read_is_reported_as_a_desync_and_the_watch_continues() {
    // Moved here from the integration suite when M3.8 retired the test-only
    // surface: forcing an overflow needs the completion buffer undersized below a
    // single record, and buffer size is deliberately not a client's business.
    //
    // Overflow is otherwise a race a test cannot win reliably -- the kernel only
    // discards when records pile up in the window between a completion and the
    // re-arm, and nothing outside this crate can widen that window. Driving a
    // burst against a roomy buffer does overflow, but was measured between 1.5
    // and 15 seconds for the same assertion.
    const UNDERSIZED_BUFFER_BYTES: usize = 16;

    let dir = TempDir::new("watcher-overflow");
    let handle = DirectoryHandle::open(dir.path()).expect("open the watched directory");
    let (sender, receiver) = channel();
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start_with(
        handle,
        dir.path().to_path_buf(),
        UNDERSIZED_BUFFER_BYTES,
        route,
    )
    .expect("arm the first read");

    let overflows = |receiver: &Receiver| {
        let mut count = 0;
        while let Some(item) = receiver.try_recv() {
            if matches!(
                item,
                Notification::Desync {
                    cause: DesyncCause::Overflow,
                    ..
                }
            ) {
                count += 1;
            }
        }
        count
    };

    let mut seen = 0;
    std::fs::write(dir.path().join("first.txt"), b"first").expect("the first change");
    wait_for("the overflow", || {
        seen += overflows(&receiver);
        seen >= 1
    });

    // A second one can only arrive if the completion path re-armed after the
    // first: an overflow is a report, not a stop.
    std::fs::write(dir.path().join("second.txt"), b"second").expect("the second change");
    wait_for("a second overflow, which requires a re-arm", || {
        seen += overflows(&receiver);
        seen >= 2
    });

    assert!(
        watcher.is_watching(),
        "an overflow must not stop the watcher: {:?}",
        watcher.stop_reason()
    );

    drop(watcher);
    dir.cleanup();
}

// --- adding and removing routes without disturbing the others (D-6/M4.4) ---

/// Start a watcher over `dir` with one route, returning the sender too so a
/// test can add a second route delivering to the same drained receiver.
fn watch_with_sink(dir: &Path, subtree: bool) -> (DirectoryWatcher, Sender, Drained) {
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir).expect("open the directory");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree },
        sender.clone(),
    );
    let watcher =
        DirectoryWatcher::start(handle, dir.to_path_buf(), route).expect("start the watcher");
    (watcher, sender, Drained::start(receiver))
}

#[test]
fn adding_a_shallow_route_to_a_shallow_watcher_needs_no_rearm() {
    let dir = TempDir::new("route-add-shallow");
    let (watcher, sink, collected) = watch_with_sink(dir.path(), false);

    watcher.add_route(
        plain_route(
            WatchId::from_raw(2),
            RouteScope::Directory { subtree: false },
            sink,
        ),
        DirectoryHandle::open(dir.path()).expect("open a second handle"),
    );

    std::fs::write(dir.path().join("a.txt"), b"x").expect("create");
    collected.wait_for_name("a.txt");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_recursive_route_added_to_a_shallow_watcher_widens_its_reach() {
    // The case D-6/M4.4 exists for: a second subscription asks for recursion the
    // first one never needed, and the *first* subscription's own read has to
    // start reaching nested changes too, since there is only one kernel read per
    // directory. Widening reopens the directory (see `WatcherInner::reopen`):
    // cancelling and resubmitting on the same handle was tried first and
    // measured not to work -- the kernel kept reporting only direct children.
    let dir = TempDir::new("route-widen");
    let (watcher, sink, collected) = watch_with_sink(dir.path(), false);

    let nested = dir.path().join("nested");
    std::fs::create_dir(&nested).expect("create the nested directory");
    std::fs::write(nested.join("deep.txt"), b"x").expect("create a nested file");
    std::thread::sleep(Duration::from_millis(100));
    assert!(
        !collected
            .changes()
            .iter()
            .any(|(_, name)| name.contains("deep.txt")),
        "a shallow watcher must not have reported the nested file yet"
    );

    watcher.add_route(
        plain_route(
            WatchId::from_raw(2),
            RouteScope::Directory { subtree: true },
            sink,
        ),
        DirectoryHandle::open(dir.path()).expect("open a second handle"),
    );

    std::fs::write(nested.join("deep2.txt"), b"y").expect("create a second nested file");
    collected.wait_for_name("nested\\deep2.txt");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_concurrent_widen_and_retry_reestablish_do_not_corrupt_the_watcher() {
    // PR #20 review response: `install`'s ArmGate::Reopening marks state but
    // did not serialize the reopen transaction. A widening `add_route` and
    // the retry timer's `retry_reestablish` could both pass the "not
    // TornDown" gate check and run their own teardown/establish/arm sequence
    // concurrently, each capable of tearing down or replacing the endpoint
    // the other had just installed. Driving both at once here, repeatedly,
    // is the regression test for `WatcherInner::reopen_lock` serializing
    // them: whichever ordering the scheduler picks, the watcher must end up
    // functional rather than wedged or panicking.
    let dir = TempDir::new("route-widen-concurrent-reopen");
    let (watcher, sink, collected) = watch_with_sink(dir.path(), false);
    let watcher = std::sync::Arc::new(watcher);

    let nested = dir.path().join("nested");
    std::fs::create_dir(&nested).expect("create the nested directory");

    let retrying = {
        let watcher = std::sync::Arc::clone(&watcher);
        std::thread::spawn(move || {
            for _ in 0..20 {
                watcher.inner.retry_reestablish();
            }
        })
    };
    watcher.add_route(
        plain_route(
            WatchId::from_raw(2),
            RouteScope::Directory { subtree: true },
            sink,
        ),
        DirectoryHandle::open(dir.path()).expect("open a second handle"),
    );
    retrying.join().expect("the retry thread panicked");

    assert_ne!(
        watcher.gate(),
        ArmGate::TornDown,
        "the watcher must still be functional after the race"
    );
    std::fs::write(nested.join("after-race.txt"), b"z").expect("create a nested file");
    collected.wait_for_name("nested\\after-race.txt");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn removing_the_only_recursive_route_leaves_the_watcher_functional() {
    // Contraction is never forced (see `DirectoryWatcher::add_route`'s docs): the
    // remaining shallow route just gets an over-broad read filtered back down,
    // which costs nothing but a few decoded bytes.
    let dir = TempDir::new("route-remove-recursive");
    let (watcher, sink, collected) = watch_with_sink(dir.path(), true);

    watcher.add_route(
        plain_route(
            WatchId::from_raw(2),
            RouteScope::Directory { subtree: false },
            sink,
        ),
        DirectoryHandle::open(dir.path()).expect("open a second handle"),
    );
    assert_eq!(watcher.remove_route(test_watch()).0, 1, "one route remains");

    std::fs::write(dir.path().join("a.txt"), b"x").expect("create");
    collected.wait_for_name("a.txt");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn removing_every_route_is_observed_by_the_caller() {
    let dir = TempDir::new("route-remove-all");
    let (watcher, collected) = watch(dir.path(), false);
    assert_eq!(watcher.remove_route(test_watch()).0, 0);
    drop(collected);
    drop(watcher);
    dir.cleanup();
}

// --- fault recovery and the retry protocol (D-14/D-15/D-27, M5.1-M5.6) ---

/// An interactive route (D-27), with its standing fault-question reservation
/// (D-28) taken from `sink`.
fn interactive_route(watch: WatchId, sink: Sender, report_liveness: bool) -> Route {
    let fault_slot = sink
        .reserve_standing()
        .expect("room for the standing fault-question slot");
    Route {
        watch,
        scope: RouteScope::Directory { subtree: false },
        sink,
        retry: RetryMode::Interactive,
        report_liveness,
        on_volume_change: VolumeChangePolicy::AutoContinue,
        fault_slot: Some(fault_slot),
    }
}

#[test]
fn a_fresh_watcher_reports_not_faulted() {
    let dir = TempDir::new("fault-not-yet");
    let (watcher, _collected) = watch(dir.path(), false);
    assert!(!watcher.is_faulted());
    drop(watcher);
    dir.cleanup();
}

#[test]
fn the_current_fault_reports_its_classification_and_code() {
    let dir = TempDir::new("fault-detail");
    let (watcher, _collected) = watch(dir.path(), false);
    assert_eq!(watcher.fault_detail(), None);

    let error = std::io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as i32);
    watcher
        .inner
        .enter_fault(classify_detail(&error), FaultOperation::Arm);

    assert_eq!(
        watcher.fault_detail(),
        Some(FaultDetail {
            failure: OpenFailure::Unsupported,
            code: FailureCode::Win32(ERROR_NOT_SUPPORTED),
        })
    );

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_fault_with_only_default_routes_closes_the_gate_until_the_timer_resolves_it() {
    let dir = TempDir::new("fault-default");
    let (watcher, _collected) = watch(dir.path(), false);

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );

    assert!(watcher.is_faulted());
    assert_eq!(watcher.gate(), ArmGate::Faulted);
    assert!(
        watcher.is_watching(),
        "a fault is recovering, not a permanent stop"
    );

    drop(watcher);
    dir.cleanup();
}

#[test]
fn an_interactive_route_is_asked_and_its_answer_resolves_the_fault() {
    let dir = TempDir::new("fault-interactive");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = interactive_route(test_watch(), sender, false);
    let watcher = DirectoryWatcher::start(handle, dir.path().to_path_buf(), route).expect("start");
    let collected = Drained::start(receiver);

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );
    assert!(watcher.is_faulted());
    collected.wait_until("the retry question", |d| {
        d.notifications().iter().any(
            |n| matches!(n, Notification::RetryQuestion { watch, .. } if *watch == test_watch()),
        )
    });

    watcher.answer(test_watch(), Some(Duration::from_millis(1)));

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.is_faulted() {
        assert!(
            std::time::Instant::now() < deadline,
            "the fault never resolved after being answered"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
    assert!(watcher.is_watching());

    drop(watcher);
    dir.cleanup();
}

#[test]
fn the_earliest_of_several_answers_wins_and_a_decliner_counts_at_the_default() {
    let dir = TempDir::new("fault-earliest");
    let (sender_a, _receiver_a) = channel();
    let (sender_b, _receiver_b) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let watch_a = WatchId::from_raw(10);
    let watch_b = WatchId::from_raw(11);
    let route_a = interactive_route(watch_a, sender_a, false);
    let watcher =
        DirectoryWatcher::start(handle, dir.path().to_path_buf(), route_a).expect("start");
    let fresh = DirectoryHandle::open(dir.path()).expect("a second handle");
    watcher.add_route(interactive_route(watch_b, sender_b, false), fresh);

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );
    assert!(watcher.is_faulted());

    // `watch_a` declines (counted at the 500ms default); `watch_b` names the
    // floor. The earliest of the two must win regardless of answer order.
    watcher.answer(watch_a, None);
    watcher.answer(watch_b, Some(Duration::from_millis(1)));

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.is_faulted() {
        assert!(
            std::time::Instant::now() < deadline,
            "the fault never resolved once both routes answered"
        );
        std::thread::sleep(Duration::from_millis(5));
    }

    drop(watcher);
    dir.cleanup();
}

#[test]
fn removing_the_only_awaited_route_resolves_the_fault_rather_than_wedging_it() {
    let dir = TempDir::new("fault-cancel-awaited");
    let (sender, _receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = interactive_route(test_watch(), sender, false);
    let watcher = DirectoryWatcher::start(handle, dir.path().to_path_buf(), route).expect("start");

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );
    assert!(watcher.is_faulted());

    assert_eq!(
        watcher.remove_route(test_watch()).0,
        0,
        "the only route is gone"
    );

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.is_faulted() {
        assert!(
            std::time::Instant::now() < deadline,
            "removing the last awaited route must resolve the fault, not wedge it"
        );
        std::thread::sleep(Duration::from_millis(5));
    }

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_resolved_fault_reports_reestablished_and_the_opt_in_liveness_brackets() {
    let dir = TempDir::new("fault-resolved-notify");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = Route {
        watch: test_watch(),
        scope: RouteScope::Directory { subtree: false },
        sink: sender,
        retry: RetryMode::Interactive,
        report_liveness: true,
        on_volume_change: VolumeChangePolicy::AutoContinue,
        fault_slot: None,
    };
    // Interactive with no fault_slot: never asked (there is nowhere to ask), so
    // this resolves at the default delay exactly like a Defaults route would.
    let watcher = DirectoryWatcher::start(handle, dir.path().to_path_buf(), route).expect("start");
    let collected = Drained::start(receiver);

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );
    collected.wait_until("suspended", |d| {
        d.notifications()
            .iter()
            .any(|n| matches!(n, Notification::Suspended { .. }))
    });

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.is_faulted() {
        assert!(
            std::time::Instant::now() < deadline,
            "the default-delay fault never resolved"
        );
        std::thread::sleep(Duration::from_millis(5));
    }

    collected.wait_until("resumed, established, and reestablished", |d| {
        let seen = d.notifications();
        seen.iter()
            .any(|n| matches!(n, Notification::Resumed { .. }))
            && seen
                .iter()
                .any(|n| matches!(n, Notification::Established { .. }))
            && seen.iter().any(|n| {
                matches!(
                    n,
                    Notification::Desync {
                        cause: DesyncCause::Reestablished,
                        ..
                    }
                )
            })
    });

    drop(watcher);
    dir.cleanup();
}

// --- the coarse fallback (D-17, M6) ---

#[test]
fn forcing_coarse_establishes_in_coarse_mode() {
    let dir = TempDir::new("coarse-forced");
    let (sender, _receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start_forcing_coarse(handle, dir.path().to_path_buf(), route)
        .expect("start in forced-coarse mode");

    assert_eq!(watcher.mode(), WatchMode::Coarse);
    assert!(watcher.is_watching());
    assert!(!watcher.is_faulted());

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_forced_coarse_watch_reports_a_change_as_desync_coarse() {
    let dir = TempDir::new("coarse-desync");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start_forcing_coarse(handle, dir.path().to_path_buf(), route)
        .expect("start in forced-coarse mode");
    let collected = Drained::start(receiver);

    std::fs::write(dir.path().join("changed.txt"), b"x").expect("create a file");
    collected.wait_until("a coarse desync", |d| {
        d.desyncs().contains(&DesyncCause::Coarse)
    });

    assert!(
        watcher.is_watching(),
        "a coarse activation must not stop the watcher: {:?}",
        watcher.stop_reason()
    );

    drop(watcher);
    dir.cleanup();
}

#[test]
fn a_recovered_fault_in_forced_coarse_mode_reports_established_coarse() {
    let dir = TempDir::new("coarse-established");
    let (sender, receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = Route {
        watch: test_watch(),
        scope: RouteScope::Directory { subtree: false },
        sink: sender,
        retry: RetryMode::Defaults,
        report_liveness: true,
        on_volume_change: VolumeChangePolicy::AutoContinue,
        fault_slot: None,
    };
    let watcher = DirectoryWatcher::start_forcing_coarse(handle, dir.path().to_path_buf(), route)
        .expect("start in forced-coarse mode");
    let collected = Drained::start(receiver);

    watcher.inner.enter_fault(
        classify_detail(&std::io::Error::other("synthetic")),
        FaultOperation::Arm,
    );

    collected.wait_until("resumed, established coarse, and reestablished", |d| {
        let seen = d.notifications();
        seen.iter()
            .any(|n| matches!(n, Notification::Resumed { .. }))
            && seen.iter().any(|n| {
                matches!(
                    n,
                    Notification::Established {
                        mode: WatchMode::Coarse,
                        ..
                    }
                )
            })
            && seen.iter().any(|n| {
                matches!(
                    n,
                    Notification::Desync {
                        cause: DesyncCause::Reestablished,
                        ..
                    }
                )
            })
    });
    assert_eq!(watcher.mode(), WatchMode::Coarse);

    drop(watcher);
    dir.cleanup();
}

#[test]
fn teardown_of_a_forced_coarse_watch_is_prompt() {
    let dir = TempDir::new("coarse-teardown");
    let (sender, _receiver) = channel();
    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route = plain_route(
        test_watch(),
        RouteScope::Directory { subtree: false },
        sender,
    );
    let watcher = DirectoryWatcher::start_forcing_coarse(handle, dir.path().to_path_buf(), route)
        .expect("start in forced-coarse mode");

    let started = std::time::Instant::now();
    drop(watcher);
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "coarse teardown did not converge promptly"
    );
    dir.cleanup();
}

// --- volume-change confirmation (D-78, M12) ---

/// A route that has opted in to confirming a volume change (M12.1), with its
/// standing question reservation taken from `sink`.
fn confirm_route(watch: WatchId, sink: Sender) -> Route {
    let fault_slot = sink
        .reserve_standing()
        .expect("room for the standing question slot");
    Route {
        watch,
        scope: RouteScope::Directory { subtree: false },
        sink,
        retry: RetryMode::Defaults,
        report_liveness: false,
        on_volume_change: VolumeChangePolicy::Confirm,
        fault_slot: Some(fault_slot),
    }
}

#[test]
fn only_the_confirm_route_is_asked_and_continuing_keeps_both_routes() {
    let dir = TempDir::new("volume-change-continue");
    let (sender_a, receiver_a) = channel();
    let (sender_b, receiver_b) = channel();
    let watch_a = WatchId::from_raw(20);
    let watch_b = WatchId::from_raw(21);

    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route_a = confirm_route(watch_a, sender_a);
    let watcher =
        DirectoryWatcher::start(handle, dir.path().to_path_buf(), route_a).expect("start");
    let fresh_handle = DirectoryHandle::open(dir.path()).expect("open again to coalesce");
    watcher.add_route(
        plain_route(watch_b, RouteScope::Directory { subtree: false }, sender_b),
        fresh_handle,
    );

    // Rig the recorded baseline so the *real* current volume identity this
    // watcher reads fresh below is guaranteed to differ from it -- a real
    // removable-media swap is not otherwise reproducible in an automated test.
    *lock(&watcher.inner.volume_identity) = Some(VolumeIdentity::synthetic(
        0xDEAD_BEEF,
        "FAKE-FS",
        "FAKE-LABEL",
    ));
    watcher.inner.retry_reestablish();

    assert_eq!(watcher.gate(), ArmGate::VolumeChangePending);

    let collected_a = Drained::start(receiver_a);
    collected_a.wait_until("the volume-change question", |d| {
        d.notifications()
            .iter()
            .any(|n| matches!(n, Notification::VolumeChanged { watch, .. } if *watch == watch_a))
    });
    assert!(
        receiver_b.try_recv().is_none(),
        "an AutoContinue route must never be asked"
    );

    let (remaining, _stopped) = watcher
        .answer_volume_change(watch_a, VolumeChangeDecision::Continue)
        .expect("this answer resolves the question");
    assert_eq!(remaining, 2, "continuing keeps both routes");

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.gate() == ArmGate::VolumeChangePending {
        assert!(
            std::time::Instant::now() < deadline,
            "the watcher never resumed arming after the volume change was confirmed"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
    assert_eq!(watcher.gate(), ArmGate::Open);

    drop(watcher);
    dir.cleanup();
}

#[test]
fn stopping_a_volume_change_removes_only_that_route() {
    let dir = TempDir::new("volume-change-stop");
    let (sender_a, receiver_a) = channel();
    let (sender_b, receiver_b) = channel();
    let watch_a = WatchId::from_raw(22);
    let watch_b = WatchId::from_raw(23);

    let handle = DirectoryHandle::open(dir.path()).expect("open");
    let route_a = confirm_route(watch_a, sender_a);
    let watcher =
        DirectoryWatcher::start(handle, dir.path().to_path_buf(), route_a).expect("start");
    let fresh_handle = DirectoryHandle::open(dir.path()).expect("open again to coalesce");
    watcher.add_route(
        plain_route(watch_b, RouteScope::Directory { subtree: false }, sender_b),
        fresh_handle,
    );

    *lock(&watcher.inner.volume_identity) = Some(VolumeIdentity::synthetic(
        0xDEAD_BEEF,
        "FAKE-FS",
        "FAKE-LABEL",
    ));
    watcher.inner.retry_reestablish();
    assert_eq!(watcher.gate(), ArmGate::VolumeChangePending);

    let collected_a = Drained::start(receiver_a);
    collected_a.wait_until("the volume-change question", |d| {
        d.notifications()
            .iter()
            .any(|n| matches!(n, Notification::VolumeChanged { watch, .. } if *watch == watch_a))
    });

    let (remaining, stopped) = watcher
        .answer_volume_change(watch_a, VolumeChangeDecision::Stop)
        .expect("this answer resolves the question");
    assert_eq!(remaining, 1, "only the declining route is removed");
    assert_eq!(
        stopped,
        vec![watch_a],
        "the declining route is reported stopped"
    );

    let deadline = std::time::Instant::now() + NOTIFY_TIMEOUT;
    while watcher.gate() == ArmGate::VolumeChangePending {
        assert!(
            std::time::Instant::now() < deadline,
            "the watcher never resumed arming after the volume change resolved"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
    assert_eq!(watcher.gate(), ArmGate::Open);

    // The remaining (AutoContinue) route is still served: a real change still
    // reaches it.
    let collected_b = Drained::start(receiver_b);
    std::fs::write(dir.path().join("after.txt"), b"x").expect("create a file");
    collected_b.wait_until("a change after the volume-change resolved", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Added && name == "after.txt")
    });

    drop(watcher);
    dir.cleanup();
}

// --- the notification filter's less-travelled categories (mutation gap) ---
//
// `ALL_NOTIFY_FILTERS` is seven flags OR'd together. Replacing one `|` with `&`
// zeroes the two flags on either side of it -- `A | B & C | D` parses as
// `A | (B & C) | D`, and disjoint flags AND to nothing -- so each such mutant
// silently drops a whole category of change from what the kernel is asked to
// report. That is a real gap rather than a curiosity: a watcher that reports
// creation and deletion but silently never reports a write is a plausible
// defect, and for a while nothing here would have noticed.
//
// **All six are now caught**, each confirmed by injecting it and watching this
// module go red. The last two to fall were the pairs LAST_WRITE+CREATION and
// CREATION+SECURITY, closed by the two `SetFileTime` tests below.
//
// What made them closable was measuring which filter bit actually reports which
// operation -- arming a watch with a single bit at a time -- rather than
// reasoning about it. The result, and it corrects two claims this comment used
// to make:
//
//   SetFileTime last-write only   -> LAST_WRITE alone
//   SetFileTime creation only     -> CREATION alone
//   SetFileTime last-access only  -> LAST_ACCESS alone
//   DACL edit (icacls)            -> SECURITY alone
//   same-length rewrite           -> SIZE and LAST_WRITE (not ATTRIBUTES)
//
// The corrections: a same-length rewrite is *not* masked by the archive bit --
// ATTRIBUTES does not fire for it at all, and what actually reports it is SIZE,
// because `std::fs::write` truncates before writing, so the length does change
// on the way through. And a DACL edit *is* reported by SECURITY alone, so the
// permissions test below does isolate that category; the earlier note saying it
// did not was simply wrong.

#[test]
fn writing_to_an_existing_file_is_reported_as_modified() {
    // Covers FILE_NOTIFY_CHANGE_SIZE and FILE_NOTIFY_CHANGE_LAST_WRITE: the
    // file already exists and keeps its name, so neither of the name filters
    // can account for this notification.
    let dir = TempDir::new("modified-write");
    std::fs::write(dir.path().join("existing.txt"), b"first").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    std::fs::write(dir.path().join("existing.txt"), b"second, and longer").expect("rewrite");

    collected.wait_until("a Modified for existing.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "existing.txt")
    });

    drop(watcher);
    dir.cleanup();
}

#[test]
fn changing_an_existing_files_attributes_is_reported_as_modified() {
    // Covers FILE_NOTIFY_CHANGE_ATTRIBUTES. The file's name, size and contents
    // are untouched, so this is the one category that can report it.
    let dir = TempDir::new("modified-attrs");
    let path = dir.path().join("attrs.txt");
    std::fs::write(&path, b"x").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    let mut permissions = std::fs::metadata(&path)
        .expect("read metadata")
        .permissions();
    permissions.set_readonly(true);
    std::fs::set_permissions(&path, permissions).expect("mark read-only");

    collected.wait_until("a Modified for attrs.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "attrs.txt")
    });

    // Clear it again so the temp directory can be removed.
    let mut permissions = std::fs::metadata(&path)
        .expect("read metadata")
        .permissions();
    // clippy warns that this makes a file world-writable *on Unix*. This crate
    // is entirely `cfg(windows)`, where the call clears the read-only attribute
    // and nothing more -- which is exactly what the cleanup below needs.
    #[allow(clippy::permissions_set_readonly_false)]
    permissions.set_readonly(false);
    std::fs::set_permissions(&path, permissions).expect("clear read-only");

    drop(watcher);
    dir.cleanup();
}

#[test]
fn the_default_buffer_is_the_documented_size() {
    // `64 * 1024` survived being changed to `64 + 1024`, which would leave a
    // 1088-byte buffer: still large enough for the handful of records a test
    // produces, so nothing noticed, but small enough to overflow under the
    // burst this constant's doc comment says it is sized for.
    //
    // Asserting a constant's value is usually circular. It is not here: this is
    // `pub`, so the number is part of the crate's published surface, and the
    // doc comment two lines above it states the size in prose that a reader is
    // entitled to trust.
    assert_eq!(
        super::DEFAULT_BUFFER_BYTES,
        64 * 1024,
        "the documented default is 64 KiB"
    );
}

#[test]
fn rewriting_a_file_without_changing_its_length_is_reported_as_modified() {
    // A rewrite whose *net* length is unchanged.
    //
    // It was written to isolate FILE_NOTIFY_CHANGE_LAST_WRITE and it does not,
    // but not for the reason first recorded here. Measured, one filter bit at a
    // time: this operation fires SIZE and LAST_WRITE, and does *not* fire
    // ATTRIBUTES -- the archive bit was a red herring. What defeats the
    // isolation is that `std::fs::write` truncates before writing, so the length
    // really does change on the way through and SIZE reports it. Isolating
    // last-write needs a change that touches only the timestamp, which
    // `changing_only_a_files_last_write_time_is_reported_as_modified` below now
    // does.
    //
    // Kept anyway, because a same-length rewrite being reported at all is worth
    // asserting and nothing else here does it.
    let dir = TempDir::new("modified-same-size");
    let path = dir.path().join("fixed-size.txt");
    std::fs::write(&path, b"aaaa").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    std::fs::write(&path, b"bbbb").expect("rewrite at the same length");

    collected.wait_until("a Modified for fixed-size.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "fixed-size.txt")
    });

    drop(watcher);
    dir.cleanup();
}

#[test]
fn changing_only_a_files_last_write_time_is_reported_as_modified() {
    // Isolates FILE_NOTIFY_CHANGE_LAST_WRITE, which nothing else here does: a
    // `SetFileTime` touching only the last-write stamp changes no name, no
    // length, and no attribute, so no other filter in `ALL_NOTIFY_FILTERS` can
    // account for the notification. Measured before it was written -- armed one
    // filter bit at a time, this operation fires LAST_WRITE and nothing else.
    //
    // The handle is opened for `FILE_WRITE_ATTRIBUTES` alone rather than for
    // writing, deliberately: a write-access handle can set the archive bit when
    // it closes, which would let ATTRIBUTES report this instead and quietly undo
    // the isolation.
    let dir = TempDir::new("modified-timestamp");
    let path = dir.path().join("stamped.txt");
    std::fs::write(&path, b"unchanged").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    set_last_write_time(&path);

    collected.wait_until("a Modified for stamped.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "stamped.txt")
    });

    drop(watcher);
    dir.cleanup();
}

#[test]
fn changing_only_a_files_creation_time_is_reported_as_modified() {
    // Isolates FILE_NOTIFY_CHANGE_CREATION on the same principle. Worth having
    // separately from the last-write case because the two surviving mutants drop
    // *pairs* of adjacent flags -- LAST_WRITE+CREATION and CREATION+SECURITY --
    // so a creation-only change is the one operation that fails under both.
    let dir = TempDir::new("modified-creation");
    let path = dir.path().join("born.txt");
    std::fs::write(&path, b"unchanged").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    set_creation_time(&path);

    collected.wait_until("a Modified for born.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "born.txt")
    });

    drop(watcher);
    dir.cleanup();
}

/// An arbitrary fixed instant, far enough in the past that it cannot equal the
/// stamp already on a file this test just created.
fn a_distinct_filetime() -> FILETIME {
    // 100ns ticks since 1601, i.e. some time in 2013.
    const TICKS: u64 = 130_000_000_000_000_000;
    FILETIME {
        dwLowDateTime: (TICKS & 0xFFFF_FFFF) as u32,
        dwHighDateTime: (TICKS >> 32) as u32,
    }
}

/// Open for `FILE_WRITE_ATTRIBUTES` only -- see the tests above for why the
/// narrower access matters.
fn open_for_timestamps(path: &Path) -> std::fs::File {
    use std::os::windows::fs::OpenOptionsExt;
    std::fs::OpenOptions::new()
        .access_mode(FILE_WRITE_ATTRIBUTES)
        .open(path)
        .expect("open the file for its timestamps")
}

fn set_last_write_time(path: &Path) {
    let file = open_for_timestamps(path);
    let stamp = a_distinct_filetime();
    // SAFETY: `file` is live for the call, and the two null pointers are the
    // documented way to leave creation and last-access untouched.
    let ok = unsafe {
        SetFileTime(
            file.as_raw_handle() as HANDLE,
            std::ptr::null(),
            std::ptr::null(),
            &stamp,
        )
    };
    assert!(ok != 0, "SetFileTime(last write) failed");
}

fn set_creation_time(path: &Path) {
    let file = open_for_timestamps(path);
    let stamp = a_distinct_filetime();
    // SAFETY: as above, leaving last-access and last-write untouched.
    let ok = unsafe {
        SetFileTime(
            file.as_raw_handle() as HANDLE,
            &stamp,
            std::ptr::null(),
            std::ptr::null(),
        )
    };
    assert!(ok != 0, "SetFileTime(creation) failed");
}

#[test]
fn changing_a_files_permissions_is_reported_as_modified() {
    // A DACL edit, which is a change no other test here makes.
    //
    // This **does** isolate FILE_NOTIFY_CHANGE_SECURITY, and an earlier note
    // here claiming otherwise was wrong. Measured one filter bit at a time, a
    // DACL edit fires SECURITY and nothing else; injecting the mutant that drops
    // SECURITY turns this test red. Whatever the earlier check did, it was not
    // measuring this.
    //
    // `icacls` rather than a Win32 call, because the point is to make a real
    // security-descriptor change and observe that the watch reports it, not to
    // exercise any particular way of making one.
    let dir = TempDir::new("modified-acl");
    let path = dir.path().join("acl.txt");
    std::fs::write(&path, b"x").expect("seed the file");

    let (watcher, collected) = watch(dir.path(), false);

    // *S-1-1-0 is the well-known Everyone SID, named by SID so this does not
    // depend on the machine's language.
    let granted = std::process::Command::new("icacls.exe")
        .arg(path.as_os_str())
        .args(["/grant", "*S-1-1-0:(R)"])
        .output()
        .expect("run icacls");
    assert!(
        granted.status.success(),
        "could not change the file's DACL, so the security half of the filter \
         went untested: {}",
        String::from_utf8_lossy(&granted.stderr)
    );

    collected.wait_until("a Modified for acl.txt", |d| {
        d.changes()
            .iter()
            .any(|(kind, name)| *kind == ChangeKind::Modified && name == "acl.txt")
    });

    drop(watcher);
    dir.cleanup();
}

// --- the arming contract: which submission results mean "a packet is coming" ---
//
// This is the crate's most dangerous misreading, and before these tests the only
// thing standing between getting it wrong and a green suite was whether the
// allocator happened to notice. Telling the pool that a genuinely-pending read
// failed makes it cancel its accounting for an I/O the kernel is still going to
// complete, and the completion lands in a freed buffer -- so detection depended
// on heap layout. The same mutation was recorded `MISSED` in one sweep and
// crashed the process in another; two crashes were even scored as "caught"
// purely because the process exited non-zero. A crash is not a test (M15.5).
//
// `classify_submission` exists so the contract can be asserted directly instead.

#[test]
fn a_synchronous_success_still_means_a_completion_is_coming() {
    // The counter-intuitive half: `TRUE` says the *I/O* finished, not that the
    // *packet* is not coming. Treating it as "done, nothing to wait for" would
    // free a buffer the kernel has already queued a completion for.
    let issued = super::classify_submission(1, || {
        panic!("GetLastError must not be consulted after a success")
    });
    assert!(
        matches!(issued, Ok(Issued::Pending)),
        "a native success must still be reported as pending"
    );
}

#[test]
fn a_pending_submission_is_armed_rather_than_failed() {
    // The half that corrupts the heap when it is wrong.
    let issued = super::classify_submission(0, || {
        std::io::Error::from_raw_os_error(ERROR_IO_PENDING as i32)
    });
    assert!(
        matches!(issued, Ok(Issued::Pending)),
        "ERROR_IO_PENDING is how a submission reports success, not failure"
    );
}

#[test]
fn a_genuinely_failed_submission_is_reported_as_failed() {
    // The other direction, and the one that hangs a watcher rather than
    // corrupting it: claiming a failed submission is pending leaves the pool
    // waiting for a completion that will never arrive. `ERROR_INVALID_PARAMETER`
    // is the real case -- it is what a directory handle opened by file id
    // answers (D-80).
    for code in [
        ERROR_INVALID_PARAMETER as i32,
        ERROR_ACCESS_DENIED as i32,
        ERROR_NOT_SUPPORTED as i32,
    ] {
        let issued = super::classify_submission(0, || std::io::Error::from_raw_os_error(code));
        match issued {
            Err(error) => assert_eq!(
                error.raw_os_error(),
                Some(code),
                "the failure must be reported with the code the OS gave"
            ),
            Ok(_) => panic!("error {code} must not be reported as armed"),
        }
    }
}

#[test]
fn a_submission_failure_with_no_os_code_is_still_a_failure() {
    // Nothing guarantees the seam only ever sees OS-coded errors, and the
    // pending test is an equality against a code -- an error carrying none must
    // fall through to the failure arm rather than matching anything.
    let issued = super::classify_submission(0, || std::io::Error::other("no raw code"));
    assert!(
        issued.is_err(),
        "an error with no OS code cannot be a pending submission"
    );
}