windows-file-watcher 0.2.1

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
// Copyright (c) 2026 Mike Grier
//! The detailed single-directory watcher: arm a `ReadDirectoryChangesW`, decode
//! its completion, and re-arm.
//!
//! Reads are issued through `windows-threadpool-sys`' [`ThreadpoolIo`], which
//! owns the balanced `StartThreadpoolIo` accounting, and through the
//! `windows-overlapped-io-sys` submission seam, whose generation-stamped
//! `OperationId` is what stops a stale completion being misattributed to the
//! next read that reuses the same `OVERLAPPED` address (D-3/D-4).
//!
//! # Re-arm before processing
//!
//! The kernel stops recording changes for a directory between the moment a read
//! completes and the moment the next one is armed. That window is inherent to
//! `ReadDirectoryChangesW` -- it cannot be closed, only made small -- so the
//! completion path re-arms *first* and decodes afterwards. Decoding is pure
//! computation over a buffer the next read does not touch, so nothing about it
//! needs to happen before the re-arm. This crate surfaces the residual loss
//! honestly as a `Desync` rather than pretending it does not exist.
//!
//! # Why the buffer is `u32`-backed
//!
//! `ReadDirectoryChangesW` requires a DWORD-aligned buffer. A `Box<[u8]>` is only
//! byte-aligned, so the completion buffer is allocated as `Box<[u32]>` and viewed
//! as bytes. The allocation also has to be *stable*: the operation's payload
//! moves when the operation is boxed for submission, so the buffer cannot be
//! inline in the payload -- the `Box` indirection is what keeps the address the
//! kernel was given valid.

use std::collections::{HashMap, HashSet};
use std::io;
use std::os::windows::io::AsRawHandle;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
use std::time::Duration;

use windows_overlapped_io_sys::{Issued, Operation, Submitted, UnassociatedEndpoint};
use windows_sys::Win32::Foundation::ERROR_IO_PENDING;
use windows_sys::Win32::Storage::FileSystem::{
    FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_DIR_NAME,
    FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY,
    FILE_NOTIFY_CHANGE_SIZE, FindNextChangeNotification, ReadDirectoryChangesW,
};
use windows_threadpool_sys::io::{IoCompletion, ThreadpoolIo};
use windows_threadpool_sys::timer::ThreadpoolTimer;
use windows_threadpool_sys::wait::{ThreadpoolWait, WaitActivation};
use windows_threadpool_sys::work::ThreadpoolWork;

use crate::coarse::CoarseHandle;
use crate::directory::{
    DirectoryHandle, DirectoryId, FaultDetail, OpenFailure, VolumeIdentity, classify,
    classify_detail,
};
use crate::monitor::{Resident, rekey};
use crate::notify::{DecodedBatch, DesyncCause, decode_batch};
use crate::queue::{Notification, Resume, WatchId};
use crate::retry::{FaultOperation, WatchMode, clamp};
use crate::route::Route;
use crate::watch::{RetryMode, VolumeChangeDecision, VolumeChangePolicy};

/// The completion-buffer size used unless a caller chooses otherwise.
///
/// Large enough that ordinary activity does not overflow the kernel's per
/// directory record queue, small enough to be unremarkable per watched
/// directory. Overflow remains possible under a burst and is reported rather
/// than hidden (D-12).
pub const DEFAULT_BUFFER_BYTES: usize = 64 * 1024;

/// The bytes in one `u32`, the unit the completion buffer is allocated in so it
/// satisfies `ReadDirectoryChangesW`'s DWORD alignment requirement.
const BYTES_PER_WORD: usize = size_of::<u32>();

/// Every `FILE_NOTIFY_CHANGE_*` class this crate can report.
///
/// Every watcher always asks for all of them. This is the permanent arrangement,
/// not a placeholder for a later per-subscription union: D-77 withdrew the
/// change-type filter outright, so there is nothing to narrow this to and never
/// will be (D-51).
pub(crate) const ALL_NOTIFY_FILTERS: u32 = FILE_NOTIFY_CHANGE_FILE_NAME
    | FILE_NOTIFY_CHANGE_DIR_NAME
    | FILE_NOTIFY_CHANGE_ATTRIBUTES
    | FILE_NOTIFY_CHANGE_SIZE
    | FILE_NOTIFY_CHANGE_LAST_WRITE
    | FILE_NOTIFY_CHANGE_CREATION
    | FILE_NOTIFY_CHANGE_SECURITY;

/// A DWORD-aligned completion buffer with a stable address.
///
/// See the module docs for why both properties are required.
struct ReadBuffer {
    words: Box<[u32]>,
}

impl ReadBuffer {
    /// Allocate a zeroed buffer of at least `bytes` bytes, rounded up to a whole
    /// number of DWORDs.
    fn new(bytes: usize) -> Self {
        let words = bytes.div_ceil(BYTES_PER_WORD).max(1);
        Self {
            words: vec![0_u32; words].into_boxed_slice(),
        }
    }

    /// The base address the kernel writes to. Stable across moves of the owner,
    /// because the data lives in the `Box`'s allocation rather than inline.
    fn as_mut_ptr(&mut self) -> *mut core::ffi::c_void {
        self.words.as_mut_ptr().cast()
    }

    /// The buffer length in bytes, as the Win32 parameter type.
    fn byte_len(&self) -> u32 {
        let bytes = self.words.len() * BYTES_PER_WORD;
        u32::try_from(bytes).expect("the completion buffer is sized in this crate and fits a u32")
    }

    /// The first `len` bytes, as the kernel described them.
    ///
    /// A `len` beyond the buffer is clamped rather than trusted; the decoder
    /// then reports the truncation as a desync.
    fn filled(&self, len: usize) -> &[u8] {
        let bytes = self.words.len() * BYTES_PER_WORD;
        let len = len.min(bytes);
        // SAFETY: `u32` has no padding or invalid bit patterns, so its backing
        // allocation is always a valid `[u8]` of four times the length, and `len`
        // has just been clamped to it.
        unsafe { std::slice::from_raw_parts(self.words.as_ptr().cast::<u8>(), len) }
    }
}

/// Whether the watcher may still submit a read, and if not, why.
///
/// A bare boolean would be enough for teardown alone, but "not re-arming" is a
/// state three different decisions reach for different reasons -- teardown here,
/// a latched fault (D-28), and queue backpressure (D-29) -- and only the first is
/// permanent. Naming the reason now means the later two add a variant rather than
/// discovering that a `bool` cannot say which of them stopped the watcher, and it
/// keeps `stop_reason` from having to guess.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArmGate {
    /// Reads may be submitted.
    Open,
    /// The client's queue is full, so re-arming would produce a batch with
    /// nowhere to go. Transient: the loss becomes a grace period in the kernel's
    /// own change buffer, and the watch resumes when the client drains (D-29).
    Backpressured,
    /// Transiently closed while the directory is being reopened to widen its
    /// reach to recursive (M4.4/D-6). Self-resolving: it becomes `Open` once the
    /// new endpoint is armed, or `TornDown` if teardown wins the race.
    Reopening,
    /// Transiently closed while the monitor works to re-establish this watcher
    /// after an open or arm fault (D-14/D-15/M5.1): asking any interactive
    /// routes, waiting for their answers, backed off on a timer, or in the
    /// middle of a retry attempt. Self-resolving: it becomes `Open` once a retry
    /// succeeds, or `TornDown` if teardown wins the race. A permanent open
    /// failure (D-22) is the one edge that does not return here -- see
    /// `WatcherInner::stopped`.
    Faulted,
    /// Transiently closed while a path-based reopen's candidate handle sits
    /// unresolved, waiting for every `Confirm`-opted route to answer whether
    /// it landed on a different volume than before (D-78/M12). Self-resolving:
    /// it becomes `Open` (via a normal reopen) once every asked route has
    /// answered, or `TornDown` if teardown wins the race.
    VolumeChangePending,
    /// Torn down. Permanent: a watcher never re-opens.
    TornDown,
}

/// Fault-recovery state (D-14/D-15/D-27/M5.1): held while this watcher is
/// working to re-establish itself, and absent otherwise.
struct FaultState {
    /// Which operation faulted -- an open (of the reopened directory) or an
    /// arm (a live `ReadDirectoryChangesW` completion or resubmission). Each
    /// carries its own default delay (D-15).
    operation: FaultOperation,
    /// Interactive routes (D-27) that have not yet answered this fault's
    /// question. Emptied by an answer arriving, or by the route leaving
    /// (M5.5): either way, once empty the resolved delay is scheduled.
    awaiting: HashSet<WatchId>,
    /// The soonest delay any answer has named so far, seeded at the
    /// operation's default (D-27) and only ever lowered.
    earliest: Duration,
    /// The classification and raw code behind the failure that opened this
    /// fault (D-79).
    detail: FaultDetail,
}

/// Held while asking `Confirm`-opted routes about a volume change a
/// path-based reopen found, between detection and every asked route
/// answering (D-78/M12).
struct VolumeChangeState {
    /// The already-opened candidate handle, not yet installed -- installing
    /// it is deferred until this resolves, so a client that wants to decide
    /// gets to before arming continues.
    handle: DirectoryHandle,
    /// `Confirm`-opted routes that have not yet answered.
    awaiting: HashSet<WatchId>,
    /// Each route's answer, as it arrives. Applied when `awaiting` empties:
    /// `Stop` removes that route, `Continue` leaves it running (M12.4).
    decisions: HashMap<WatchId, VolumeChangeDecision>,
}

/// Which tier is servicing a directory's watch (D-17): the preferred detailed
/// path, or the coarse floor a detailed arm downgrades to (M6.3).
enum Endpoint {
    /// `ReadDirectoryChangesW` on a `ThreadpoolIo`.
    Detailed(ThreadpoolIo),
    /// `FindFirstChangeNotification` on a `ThreadpoolWait` (M6.1/M6.2).
    Coarse(ThreadpoolWait),
}

/// The shared state a completion callback reaches.
struct WatcherInner {
    /// The path this directory was opened from, kept so re-establishment
    /// (M5.1) knows what to reopen -- a live handle cannot be recovered once
    /// its directory is gone, but the path can still be retried. Also what a
    /// downgrade to coarse (M6.3) opens its own handle from, since a coarse
    /// watch is a wholly separate handle from the detailed one.
    path: PathBuf,
    /// The endpoint currently in use. Replaced, not merely set once: widening a
    /// watcher's reach to recursive (M4.4) reopens the directory rather than
    /// cancelling and resubmitting on the same handle, because the latter was
    /// measured to leave the filesystem's recursive attachment unchanged --
    /// direct children kept being reported, nested ones never were. See
    /// [`WatcherInner::reopen`]. Re-establishment (M5.1) reuses the same
    /// mechanism after a fresh open, and so does a tier downgrade (M6.3): both
    /// are "tear down whatever is here, install something new".
    endpoint: Mutex<Option<Endpoint>>,
    /// Set once, as for `endpoint` before it started being replaced. Queues the
    /// re-arm that ends a backpressure pause onto this crate's own pool, so it
    /// never runs on a client's thread.
    resume_work: OnceLock<ThreadpoolWork>,
    /// Set once at construction. Fires the next re-establish attempt after a
    /// fault's resolved delay (D-27); re-armed with a fresh due time, never
    /// recreated, across however many faults this watcher lives through.
    retry_timer: OnceLock<ThreadpoolTimer>,
    /// Every `FILE_NOTIFY_CHANGE_*` class this watcher asks for. Constant rather
    /// than a per-subscription union: no subscription can select a filter
    /// (`WatchOptions` has no such field, and D-77 withdrew the feature outright),
    /// so the union over any set of subscriptions is trivially this same
    /// constant. Shared by both tiers: the wire type (`FILE_NOTIFY_CHANGE`, a
    /// `u32`) is identical between `ReadDirectoryChangesW` and
    /// `FindFirstChangeNotificationW`.
    filter: u32,
    buffer_bytes: usize,
    /// Every subscription this directory currently serves, keyed by the
    /// identifier that tags its notifications (D-6). Read at every arm to decide
    /// the kernel's own `bWatchSubtree` reach, and at every completion to
    /// de-multiplex the decoded batch (D-6/D-7).
    routes: Mutex<HashMap<WatchId, Route>>,
    /// Whether arming is still permitted, held under a lock rather than an
    /// atomic *deliberately*. Teardown must be able to establish that no further
    /// read can be submitted, and a flag checked before a submission leaves a
    /// window: the callback could pass the check, then teardown could cancel and
    /// begin waiting, and only then would the callback submit -- leaving a fresh
    /// pending read that rundown waits on forever, because nothing will complete
    /// it. Holding this lock across the submission means teardown's own
    /// acquisition waits for any in-flight submission to finish, after which no
    /// new one can start.
    gate: Mutex<ArmGate>,
    /// Held while this watcher is working to re-establish itself; absent while
    /// watching normally. See [`FaultState`].
    fault: Mutex<Option<FaultState>>,
    /// The failure that stopped re-arming *permanently*, if any. Only reached
    /// by a re-establish attempt that finds its target permanently unwatchable
    /// (D-22's `NotADirectory`/`InvalidPath`) -- every other failure retries
    /// indefinitely through `fault` instead (D-14).
    stopped: Mutex<Option<io::Error>>,
    /// M6.4's test seam: when set, `reopen` skips the detailed attempt entirely
    /// and establishes coarse from the start, regardless of what the
    /// underlying volume actually supports. Always present rather than
    /// `#[cfg(test)]`-gated (one bool costs nothing and never leaves the
    /// crate), but never set outside a test.
    force_coarse: AtomicBool,
    /// The `DirectoryId` this watcher is currently known by -- i.e. the key
    /// `Resident.directories` holds it under. A reopen is always path-based
    /// (D-80 removed the by-reference fast path), and a path-based reopen can
    /// legitimately land on a different filesystem object, so this is updated
    /// on every one (M11.2/D-78).
    directory_id: Mutex<DirectoryId>,
    /// The last volume identity recorded from an installed handle (M11.3,
    /// D-78 groundwork), compared against on the next reopen. `None` only if
    /// `GetVolumeInformationByHandleW` itself failed when this watcher was
    /// last installed.
    volume_identity: Mutex<Option<VolumeIdentity>>,
    /// The resident-state map this watcher's directory entry lives in, bound
    /// once by [`DirectoryWatcher::bind_resident`] immediately after
    /// construction (M11.4) -- unset for a watcher built directly by a unit
    /// test, which has no real `Resident` to re-key and simply skips it.
    resident: OnceLock<Weak<Mutex<Resident>>>,
    /// Held while asking about a volume change found by a path-based reopen;
    /// absent otherwise (D-78/M12). See [`VolumeChangeState`].
    volume_change: Mutex<Option<VolumeChangeState>>,
    /// Whether this directory is case-sensitive (PR #20 review response),
    /// queried fresh from the handle every time `install` installs one --
    /// read by [`WatcherInner::publish`] to select exact-ordinal or
    /// case-folding leaf-name matching per [`Route::select`]. Almost always
    /// `false`; see [`DirectoryHandle::is_case_sensitive`].
    case_sensitive: AtomicBool,
    /// Serializes the whole `install` transaction (PR #20 review response):
    /// `ArmGate::Reopening` marks that a reopen is in progress, but marking
    /// state is not mutual exclusion, and both the retry timer's callback
    /// (`retry_reestablish`) and a widening `add_route` can call `install`
    /// around the same time. Without this, a second caller's own
    /// `teardown_endpoint`/establish/arm sequence could interleave with the
    /// first's -- tearing down or replacing the endpoint the other just
    /// installed, or submitting a duplicate read. Held for `install`'s
    /// entire body, so a second caller simply waits for the first to finish
    /// (and then re-reads the gate fresh, which by then reflects what the
    /// first caller left it as) rather than proceeding concurrently.
    reopen_lock: Mutex<()>,
}

impl WatcherInner {
    /// Arm one read. Returns the submission outcome.
    ///
    /// The buffer travels as the operation's payload, so it lives exactly as
    /// long as the operation the kernel owns.
    ///
    /// A no-op, like [`ArmGate::TornDown`], while [`ArmGate::Reopening`] is in
    /// progress (PR #20 review response): `install` tears the old endpoint
    /// down (dropping `self.endpoint` to `None`) before installing the new
    /// one, and a completion callback for the *old* endpoint can still be
    /// draining concurrently -- `teardown_endpoint`'s `run_down`/
    /// `stop_and_drain` blocks for it to finish, it does not prevent it from
    /// running. Without this check, that draining callback's own
    /// re-arm-before-decode step would find no endpoint installed, treat the
    /// transient gap as an arm failure, and spuriously enter the fault loop
    /// even though the reopen it raced against was about to succeed. `install`
    /// arms fresh itself once the replacement endpoint is ready, strictly
    /// after every old callback has drained, so skipping the arm here loses
    /// nothing.
    fn arm(self: &Arc<Self>) -> Result<(), io::Error> {
        // Held for the whole submission; see the field's documentation.
        let mut gate = self
            .gate
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if matches!(*gate, ArmGate::TornDown | ArmGate::Reopening) {
            return Ok(());
        }
        self.arm_locked(&mut gate)
    }

    /// Arm the freshly (re-)established endpoint from inside [`install`],
    /// transitioning the gate out of [`ArmGate::Reopening`] itself rather
    /// than going through the callback-facing [`arm`](Self::arm) above, which
    /// deliberately no-ops while `Reopening` is set. Otherwise `install`'s own
    /// legitimate first arm of the replacement endpoint would be swallowed by
    /// that same no-op. A no-op only for [`ArmGate::TornDown`] (teardown won
    /// the race against this reopen); `install` may call this a second time
    /// after a detailed-unsupported downgrade to coarse, by which point the
    /// gate is already `Open` from the first call, not `Reopening` -- both
    /// are accepted here.
    fn arm_after_install(self: &Arc<Self>) -> Result<(), io::Error> {
        let mut gate = self
            .gate
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if *gate == ArmGate::TornDown {
            return Ok(());
        }
        self.arm_locked(&mut gate)
    }

    /// Re-arm if backpressure was the only thing stopping this watcher.
    ///
    /// Only from [`ArmGate::Backpressured`], never from [`ArmGate::Open`]: an
    /// open gate means a read is already outstanding, and a second one against
    /// the same handle would be a duplicate the design never issues.
    fn resume_arm(self: &Arc<Self>) {
        let mut gate = self
            .gate
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if *gate != ArmGate::Backpressured {
            return;
        }
        if let Err(error) = self.arm_locked(&mut gate) {
            drop(gate);
            // An arm failure is always retry-class (D-15), never terminal.
            self.enter_fault(classify_detail(&error), FaultOperation::Arm);
        }
    }

    /// Submit a read (or arm the coarse wait), or record why not. The gate
    /// lock is held throughout (D-23). Dispatches on which tier is currently
    /// installed (D-17); backpressure (D-29) applies uniformly to both, since
    /// a client's queue does not care which tier filled it.
    fn arm_locked(self: &Arc<Self>, gate: &mut ArmGate) -> Result<(), io::Error> {
        // Checked here rather than at the enqueue: refusing to arm leaves the
        // changes in the kernel's own buffer, which is a grace period rather than
        // a loss, where discovering a full queue after the read has completed is
        // a batch with nowhere to go (D-29). Paused only when *every* route is
        // full: a route with room still benefits from the grace period, and one
        // with none falls back to its own latch (D-29's fallback) -- arming
        // would not have helped it either way.
        if !self.any_route_has_room() {
            *gate = ArmGate::Backpressured;
            // Re-checked *under this lock* because a drain may have freed a slot
            // since the check above. Without it the wake could be missed: a
            // resume that ran before the gate was set would find it open and do
            // nothing, and the watcher would stay parked with room available and
            // nothing left to prod it.
            if !self.any_route_has_room() {
                return Ok(());
            }
        }
        *gate = ArmGate::Open;

        let endpoint_guard = lock(&self.endpoint);
        match endpoint_guard.as_ref() {
            Some(Endpoint::Detailed(io)) => self.arm_detailed_read(io),
            Some(Endpoint::Coarse(wait)) => {
                wait.arm(None);
                Ok(())
            }
            None => {
                // Unreachable in practice: an endpoint is installed before the
                // first arm and no callback can run before one exists.
                Err(io::Error::other("the watcher's endpoint is not yet set"))
            }
        }
    }

    /// Submit one overlapped `ReadDirectoryChangesW` against `io`.
    fn arm_detailed_read(&self, io: &ThreadpoolIo) -> Result<(), io::Error> {
        let mut operation = Operation::new(ReadBuffer::new(self.buffer_bytes));
        // Read the buffer's address and length *before* submitting, because
        // `submit` consumes the operation. Both stay valid: the bytes live in the
        // payload's `Box`, whose allocation does not move when the operation is
        // boxed for submission.
        let buffer_ptr = operation.payload_mut().as_mut_ptr();
        let buffer_len = operation.payload().byte_len();
        let filter = self.filter;
        // Read fresh at every arm: a route joining or leaving between arms
        // changes what the *next* read needs (D-6). Downstream routing narrows
        // each route back to what it actually asked for regardless of what the
        // kernel was told to reach.
        let subtree = i32::from({
            let routes = lock(&self.routes);
            routes
                .values()
                .any(|route| route.scope.needs_kernel_subtree())
        });

        // SAFETY: issues exactly one overlapped `ReadDirectoryChangesW` against
        // the supplied `OVERLAPPED`, writing only into the operation's own
        // payload buffer, which the kernel owns until the completion arrives.
        // `lpBytesReturned` is null, which is what the SDK requires for an
        // asynchronous call, and no completion routine is used because the pool
        // delivers the completion. The closure cannot unwind: it performs one FFI
        // call and returns a classification.
        let submitted = unsafe {
            io.submit(operation, |handle, overlapped| {
                let ok = ReadDirectoryChangesW(
                    handle.as_raw_handle(),
                    buffer_ptr,
                    buffer_len,
                    subtree,
                    filter,
                    std::ptr::null_mut(),
                    overlapped,
                    None,
                );
                classify_submission(ok, io::Error::last_os_error)
            })
        };

        match submitted {
            Submitted::Pending(_) => Ok(()),
            // No handle this crate opens is in skip-on-success mode, so this arm
            // is not reachable; treat it as armed rather than inventing a
            // completion the pool will not deliver.
            Submitted::Completed { .. } => Ok(()),
            Submitted::Failed { error, .. } => Err(error),
        }
    }

    /// Handle one completion: re-arm, then decode and publish.
    fn on_completion(self: &Arc<Self>, completion: &IoCompletion) {
        // SAFETY: this object only ever submits `Operation<ReadBuffer>` (in
        // `arm` above), and each completion is claimed exactly once, here.
        let operation = unsafe { completion.claim::<ReadBuffer>() };

        if let Some(error) = completion.error() {
            // A cancelled read is teardown, not a fault: stay silent and do not
            // re-arm, or rundown would never converge. Widening to recursive
            // reach (M4.4) no longer cancels the live read to do it -- it
            // reopens the directory instead (see `reopen`), so every abort seen
            // here is teardown's.
            if error.raw_os_error() == Some(OPERATION_ABORTED) {
                return;
            }
            // Every other completion failure is an arm-class fault (D-15):
            // re-established indefinitely rather than treated as terminal
            // (D-14). `stopped` is reserved for the one edge that genuinely
            // cannot recover -- a permanent open failure discovered while
            // re-establishing.
            self.enter_fault(classify_detail(&error), FaultOperation::Arm);
            return;
        }

        // Re-arm before decoding: the kernel records nothing for this directory
        // until the next read is outstanding, so that window is minimised by
        // doing the re-arm first. Decoding touches only this completed buffer.
        if let Err(error) = self.arm() {
            self.enter_fault(classify_detail(&error), FaultOperation::Arm);
        }

        let transferred = completion.bytes_transferred();
        let batch = decode_batch(operation.payload().filled(transferred));
        self.publish(batch);
    }

    /// Handle one coarse activation: re-arm, then publish (M6.2).
    ///
    /// The handle stays signalled until `FindNextChangeNotification` is called,
    /// so that has to happen *before* re-arming the wait -- otherwise the pool
    /// would see the handle still signalled and could queue the next activation
    /// immediately, overlapping this one. A coarse activation carries no detail
    /// at all (unlike a detailed completion, which at least has a buffer to
    /// decode), so the whole report is `Desync { Coarse }` (D-17).
    fn on_activation(self: &Arc<Self>, activation: &WaitActivation<'_>) {
        // SAFETY: the endpoint owns this handle for as long as it is installed,
        // and this runs only from within the wait's own callback while it
        // still is.
        let reset = unsafe { FindNextChangeNotification(activation.handle().as_raw_handle()) };
        if reset == 0 {
            // A failed reset leaves the handle's signalled state undefined, so
            // re-arming on top of it could wedge (repeated callbacks) or wait
            // on a handle that will never signal again -- treat it exactly
            // like any other arm-class fault (D-15) rather than proceeding.
            self.enter_fault(
                classify_detail(&io::Error::last_os_error()),
                FaultOperation::Arm,
            );
            return;
        }
        if let Err(error) = self.arm() {
            self.enter_fault(classify_detail(&error), FaultOperation::Arm);
            return;
        }
        self.publish(DecodedBatch::Desync(DesyncCause::Coarse));
    }

    /// Tag a decoded batch with this watcher's subscription and enqueue it.
    ///
    /// An empty change list is dropped rather than enqueued: the kernel can
    /// complete a read carrying no records, and forwarding that would make a
    /// client's "I was woken, so something changed" reasoning false.
    ///
    /// De-multiplexes across every current route (D-6): a batch is filtered to
    /// each route's own scope, and a route whose filtered subset is empty gets
    /// nothing, for the same reason an empty completion gets nothing. A desync
    /// is never filtered -- it means "you may have missed something in this
    /// directory", which is equally true for every subscription within it.
    fn publish(&self, batch: DecodedBatch) {
        let routes = lock(&self.routes);
        let case_sensitive = self.case_sensitive.load(Ordering::Relaxed);
        match batch {
            DecodedBatch::Changes(changes) if changes.is_empty() => {}
            DecodedBatch::Changes(changes) => {
                for route in routes.values() {
                    let matched = route.select(&changes, case_sensitive);
                    if matched.is_empty() {
                        continue;
                    }
                    // Observation reserves nothing, so this may be latched rather
                    // than queued (D-33); M3.7 responds by not re-arming while
                    // every route is full, turning the loss into a grace period.
                    let _ = route.sink.send(Notification::Batch {
                        watch: route.watch,
                        changes: matched,
                    });
                }
            }
            DecodedBatch::Desync(cause) => {
                for route in routes.values() {
                    let _ = route.sink.send(Notification::Desync {
                        watch: route.watch,
                        cause,
                    });
                }
            }
        }
    }

    /// Whether at least one current route's sink has room for a best-effort
    /// send.
    fn any_route_has_room(&self) -> bool {
        lock(&self.routes)
            .values()
            .any(|route| route.sink.has_room())
    }

    /// Begin (or restart) fault recovery for this watcher (D-14/D-15/M5.1).
    ///
    /// Closes the gate, tells every route the watch is suspended (opt-in,
    /// D-13), and asks every interactive route (D-27) how long to wait --
    /// counting a non-interactive route at the operation's default from the
    /// start. Once every asked route has answered (immediately, if none are
    /// interactive), the resolved delay is scheduled on `retry_timer`.
    fn enter_fault(self: &Arc<Self>, detail: FaultDetail, operation: FaultOperation) {
        {
            let mut gate = lock(&self.gate);
            if *gate == ArmGate::TornDown {
                return;
            }
            *gate = ArmGate::Faulted;
        }

        log::warn!("windows-file-watcher: {operation:?} failed, recovering: {detail:?}");

        // `routes` stays locked across installing `self.fault` and sending
        // every `RetryQuestion`: an answer arriving between those two steps
        // would find `self.fault` not yet naming that watch as awaiting
        // (D-27), so `self.answer` would silently discard it and this
        // interactive watch would wait forever for a question that was
        // already asked and already answered.
        let routes = lock(&self.routes);
        let mut awaiting = HashSet::new();
        for route in routes.values() {
            if route.report_liveness {
                let _ = route
                    .sink
                    .send(Notification::Suspended { watch: route.watch });
            }
            if route.retry == RetryMode::Interactive && route.fault_slot.is_some() {
                awaiting.insert(route.watch);
            }
        }

        let nobody_asked = awaiting.is_empty();
        *lock(&self.fault) = Some(FaultState {
            operation,
            awaiting,
            earliest: operation.default_delay(),
            detail,
        });

        for route in routes.values() {
            if route.retry == RetryMode::Interactive
                && let Some(slot) = &route.fault_slot
            {
                slot.send(Notification::RetryQuestion {
                    watch: route.watch,
                    operation,
                    detail,
                });
            }
        }
        drop(routes);

        if nobody_asked {
            self.resolve_and_schedule(operation.default_delay());
        }
    }

    /// Record an interactive route's answer to the current fault's question
    /// (D-27), if there is one outstanding for it. A no-op otherwise: the fault
    /// may already have resolved, or `watch` may never have been asked.
    fn answer(&self, watch: WatchId, delay: Option<Duration>) {
        let resolved = {
            let mut fault = lock(&self.fault);
            let Some(state) = fault.as_mut() else {
                return;
            };
            if !state.awaiting.remove(&watch) {
                return;
            }
            let candidate = delay.unwrap_or_else(|| state.operation.default_delay());
            if candidate < state.earliest {
                state.earliest = candidate;
            }
            state.awaiting.is_empty().then_some(state.earliest)
        };
        if let Some(delay) = resolved {
            self.resolve_and_schedule(delay);
        }
    }

    /// Arm `retry_timer` for the resolved delay, clamped to the floor (D-27).
    fn resolve_and_schedule(&self, delay: Duration) {
        if let Some(timer) = self.retry_timer.get() {
            timer.set_after(clamp(delay));
        }
    }

    /// `retry_timer`'s callback: attempt one re-establishment.
    ///
    /// Always a path-based `DirectoryHandle::open`. A by-reference reopen was
    /// tried first here (M11.2/D-78) because it is structurally incapable of
    /// landing on a different filesystem object; D-80 removed it, because
    /// `ReadDirectoryChangesW` rejects a handle opened by file ID, so such a
    /// reopen could never produce a watchable handle. An open failure that is
    /// retryable (D-22) re-enters the fault loop as an open-class fault; a
    /// permanent one is the one edge that does not (`stopped`). An arm failure
    /// after a successful open re-enters the fault loop as an arm-class fault.
    fn retry_reestablish(self: &Arc<Self>) {
        if *lock(&self.gate) == ArmGate::TornDown {
            return;
        }
        match DirectoryHandle::open(&self.path) {
            Ok(handle) => self.on_path_based_reopen(handle),
            Err(open_error) => {
                if open_error.failure().is_retryable() {
                    self.enter_fault(open_error.detail(), FaultOperation::Open);
                } else {
                    self.record_stop(io::Error::other(open_error));
                }
            }
        }
    }

    /// Install `handle` and resolve the fault it was reopening for, entering
    /// a fresh arm-class fault if installing or arming itself fails.
    fn finish_reopen(self: &Arc<Self>, handle: DirectoryHandle) {
        match self.install(handle) {
            Ok(()) => self.resolve_fault_success(),
            Err(error) => self.enter_fault(classify_detail(&error), FaultOperation::Arm),
        }
    }

    /// A path-based reopen can legitimately land on a different directory or
    /// volume than before (M11.3/M11.4/M12), and since D-80 it is the only kind
    /// there is. Re-keys `Resident.directories` immediately if the
    /// directory changed (identity is never subject to confirmation), then
    /// either installs `handle` straight away (no volume change, or nobody
    /// asked) or asks every `Confirm`-opted route and defers installing until
    /// they have all answered (M12.2).
    fn on_path_based_reopen(self: &Arc<Self>, handle: DirectoryHandle) {
        let new_id = handle.identity();
        let old_id = std::mem::replace(&mut *lock(&self.directory_id), new_id);
        if new_id != old_id
            && let Some(resident) = self.resident.get().and_then(Weak::upgrade)
        {
            rekey(&resident, old_id, new_id);
        }

        let previous_volume = lock(&self.volume_identity).clone();
        let current_volume = handle.volume_identity().ok();
        let changed = matches!(
            (&previous_volume, &current_volume),
            (Some(previous), Some(current)) if previous != current
        );
        if !changed {
            self.finish_reopen(handle);
            return;
        }
        // Both are `Some` whenever `changed` is true.
        let previous_volume = previous_volume.expect("checked above");
        let current_volume = current_volume.expect("checked above");

        let routes = lock(&self.routes);
        let awaiting: HashSet<WatchId> = routes
            .values()
            .filter(|route| {
                route.on_volume_change == VolumeChangePolicy::Confirm && route.fault_slot.is_some()
            })
            .map(|route| route.watch)
            .collect();
        if awaiting.is_empty() {
            drop(routes);
            // The path the handle *resolves to*, not `self.path`: a volume
            // change is precisely the case where the client's own string names
            // something that no longer leads where it used to, so echoing that
            // string back says nothing about what actually happened. `None`
            // here is itself informative -- the new handle would not report a
            // path at all.
            log::warn!(
                "windows-file-watcher: {:?} reopened on a different volume than before, and now \
                 resolves to {:?}",
                self.path,
                handle.canonical_path().ok()
            );
            self.finish_reopen(handle);
            return;
        }

        {
            let mut gate = lock(&self.gate);
            if *gate == ArmGate::TornDown {
                return;
            }
            *gate = ArmGate::VolumeChangePending;
        }
        // Installed *before* any `VolumeChanged` is sent (PR #20 review
        // response): a fast client can receive the notification and answer
        // before this call returns, and `answer_volume_change` treats a
        // still-`None` `volume_change` as "not currently asking" and silently
        // discards the answer -- leaving this watcher gated forever, waiting
        // for a question whose answer already arrived.
        *lock(&self.volume_change) = Some(VolumeChangeState {
            handle,
            awaiting: awaiting.clone(),
            decisions: HashMap::new(),
        });
        for route in routes.values() {
            if awaiting.contains(&route.watch)
                && let Some(slot) = &route.fault_slot
            {
                slot.send(Notification::VolumeChanged {
                    watch: route.watch,
                    previous: previous_volume.clone(),
                    current: current_volume.clone(),
                });
            }
        }
        drop(routes);
    }

    /// Record a route's answer to the current volume-change question
    /// (D-78/M12.3), if there is one outstanding for it. `None` otherwise: the
    /// question may already have resolved, or `watch` may never have been
    /// asked. `Some((remaining route count, watches that decided Stop))` once
    /// every asked route has answered and the resolution below has run --
    /// the caller must remove each stopped watch's own `Resident.subscriptions`
    /// entry (PR #20 review response), since this only removes the route from
    /// `self.routes` and has no access to that resident-level table.
    fn answer_volume_change(
        self: &Arc<Self>,
        watch: WatchId,
        decision: VolumeChangeDecision,
    ) -> Option<(usize, Vec<WatchId>)> {
        let ready = {
            let mut state = lock(&self.volume_change);
            let pending = state.as_mut()?;
            if !pending.awaiting.remove(&watch) {
                return None;
            }
            pending.decisions.insert(watch, decision);
            pending.awaiting.is_empty()
        };
        ready.then(|| self.resolve_volume_change())
    }

    /// M12.5: a route removed while its volume-change question is
    /// outstanding resolves as if it had left without answering -- it is
    /// simply no longer counted, mirroring D-27/M5.5's "leaving counts as
    /// declining" treatment of a fault question. `Some((remaining route
    /// count, watches that decided Stop))` if this was the last needed
    /// answer (the caller's own, already-computed remaining count is now
    /// stale and must be replaced with this one, and the stopped watches'
    /// `Resident.subscriptions` entries must be removed -- PR #20 review
    /// response); `None` otherwise.
    fn remove_route_from_volume_change(
        self: &Arc<Self>,
        watch: WatchId,
    ) -> Option<(usize, Vec<WatchId>)> {
        let ready = {
            let mut state = lock(&self.volume_change);
            let pending = state.as_mut()?;
            if !pending.awaiting.remove(&watch) {
                return None;
            }
            pending.awaiting.is_empty()
        };
        ready.then(|| self.resolve_volume_change())
    }

    /// Apply every collected decision (`Stop` removes that route, `Continue`
    /// leaves it running, M12.4), then either install the pending candidate
    /// handle -- updating the recorded volume identity, since `install`
    /// itself does that from whatever handle it is given -- or, if this left
    /// no routes, drop it and report zero so the caller tears this watcher
    /// down through the ordinary zero-routes path. Also returns every watch
    /// that decided `Stop`, so the caller can remove its now-stale
    /// `Resident.subscriptions` entry (PR #20 review response): this method
    /// only ever touches `self.routes`, which is not the table a stopped
    /// watch's subscription is otherwise still recorded, registered, and
    /// routable-looking in.
    fn resolve_volume_change(self: &Arc<Self>) -> (usize, Vec<WatchId>) {
        let pending = lock(&self.volume_change)
            .take()
            .expect("called only once awaiting has just emptied, with state present");
        let stopped: Vec<WatchId> = pending
            .decisions
            .iter()
            .filter(|(_, decision)| **decision == VolumeChangeDecision::Stop)
            .map(|(watch, _)| *watch)
            .collect();
        {
            let mut routes = lock(&self.routes);
            for watch in &stopped {
                routes.remove(watch);
            }
        }
        let remaining = lock(&self.routes).len();
        if remaining == 0 {
            drop(pending.handle);
            return (0, stopped);
        }
        self.finish_reopen(pending.handle);
        (remaining, stopped)
    }

    /// Clear fault state after a successful re-establishment and tell every
    /// route: the gap may have hidden changes (unconditional, like any other
    /// desync, D-12), and -- opt-in (D-13) -- that the watch resumed and which
    /// tier it resumed in.
    fn resolve_fault_success(&self) {
        *lock(&self.fault) = None;
        log::info!("windows-file-watcher: recovery succeeded, re-established");
        let mode = self.mode();
        // The desync is published *before* Resumed/Established: their own
        // documented contract ("a Desync always precedes or accompanies
        // this") means a client must be told to re-scan the gap before being
        // told it can trust incremental changes again, never the reverse.
        self.publish(DecodedBatch::Desync(DesyncCause::Reestablished));
        let routes = lock(&self.routes);
        for route in routes.values() {
            if route.report_liveness {
                let _ = route
                    .sink
                    .send(Notification::Resumed { watch: route.watch });
                let _ = route.sink.send(Notification::Established {
                    watch: route.watch,
                    mode,
                });
            }
        }
    }

    /// Which tier is currently servicing this directory (D-13/D-17). Detailed
    /// until an endpoint is installed, matching a not-yet-armed watcher's
    /// eventual default.
    fn mode(&self) -> WatchMode {
        match lock(&self.endpoint).as_ref() {
            Some(Endpoint::Coarse(_)) => WatchMode::Coarse,
            _ => WatchMode::Detailed,
        }
    }

    /// Tear down whichever endpoint is currently installed, fully -- cancelled
    /// or disarmed, then no operation outstanding and no callback executing --
    /// before anything touches a new one, the same ordering `stop()` relies on
    /// (D-23). Not held under the gate lock: both `run_down` and
    /// `stop_and_drain` can block.
    fn teardown_endpoint(&self) {
        // Taken and dropped *before* the match: a `match lock(...).take() {
        // ... }` scrutinee is a temporary whose lifetime extends across the
        // whole match, keeping the mutex held while `run_down`/`stop_and_drain`
        // block below -- exactly what the comment above says must not happen.
        let endpoint = lock(&self.endpoint).take();
        match endpoint {
            Some(Endpoint::Detailed(old)) => {
                let _ = old.cancel_all();
                old.run_down();
            }
            Some(Endpoint::Coarse(old)) => old.stop_and_drain(),
            None => {}
        }
    }

    /// Build a detailed endpoint over `handle` and install it. Does not arm it
    /// -- call [`WatcherInner::arm`] afterward, which is what actually reveals
    /// an unsupported-class failure (D-17/M6.3): `CreateThreadpoolIo` succeeding
    /// says nothing about whether `ReadDirectoryChangesW` itself is supported.
    ///
    /// # Errors
    ///
    /// Returns the error from binding the handle to the pool.
    fn establish_detailed(self: &Arc<Self>, handle: DirectoryHandle) -> io::Result<()> {
        // The callback holds a `Weak`, never a strong reference, for the same
        // cycle-avoidance reason as every other callback this watcher installs.
        let weak = Arc::downgrade(self);
        // SAFETY: `handle` was opened the same way every `DirectoryHandle` is
        // (see its module), which is the association this endpoint requires,
        // and ownership transfers here exclusively.
        let endpoint = unsafe { UnassociatedEndpoint::assume_overlapped(handle.into_handle()) };
        let io = ThreadpoolIo::new(
            endpoint,
            move |completion: &IoCompletion| {
                let Some(inner) = weak.upgrade() else {
                    // SAFETY: this object only ever carries
                    // `Operation<ReadBuffer>`, claimed exactly once here.
                    drop(unsafe { completion.claim::<ReadBuffer>() });
                    return;
                };
                inner.on_completion(completion);
            },
            None,
        )?;
        *lock(&self.endpoint) = Some(Endpoint::Detailed(io));
        Ok(())
    }

    /// Open a coarse handle over `self.path` and install it. Does not arm it --
    /// call [`WatcherInner::arm`] afterward. The universal floor (D-17):
    /// reached only after a detailed arm reports an unsupported-class failure,
    /// or when `force_coarse` (M6.4's test seam) says to skip detailed
    /// entirely.
    ///
    /// # Errors
    ///
    /// Returns the error from opening the coarse handle or binding it to the
    /// pool.
    fn establish_coarse(self: &Arc<Self>) -> io::Result<()> {
        let subtree = lock(&self.routes)
            .values()
            .any(|route| route.scope.needs_kernel_subtree());
        let coarse =
            CoarseHandle::open(&self.path, subtree, self.filter).map_err(io::Error::other)?;
        let weak = Arc::downgrade(self);
        // SAFETY: `coarse` is a live `FindFirstChangeNotification` handle,
        // transferred exclusively, and is never touched again except through
        // the returned `WaitableHandle`.
        let waitable = unsafe { coarse.into_waitable() };
        let wait = ThreadpoolWait::new(
            waitable,
            move |activation: &WaitActivation<'_>| {
                let Some(inner) = weak.upgrade() else {
                    return;
                };
                inner.on_activation(activation);
            },
            None,
        )?;
        *lock(&self.endpoint) = Some(Endpoint::Coarse(wait));
        Ok(())
    }

    /// (Re-)establish, choosing between detailed and coarse (D-17/M6.3).
    ///
    /// Installs `handle` rather than cancelling and resubmitting on the same
    /// one already there -- widening (M4.4) was the first thing this served,
    /// and re-establishment (M5.1) and a tier downgrade (M6.3) reuse the same
    /// mechanism: tear down whatever is installed, install something new.
    /// Detailed reads on the same handle were measured not to pick up a
    /// widened `bWatchSubtree`; a fresh handle does not have that problem, and
    /// a coarse handle cannot be reconfigured at all (its `bWatchSubtree` is
    /// fixed at open) so it needs exactly the same treatment. `handle`'s
    /// volume identity (M11.3) is recorded before it is consumed, for the
    /// next path-based reopen fallback to compare against.
    ///
    /// Mode is re-resolved on every call: detailed is attempted first (unless
    /// `force_coarse`, M6.4's test seam, says to skip it), and only an
    /// unsupported-class failure (`ERROR_INVALID_FUNCTION`/`ERROR_NOT_SUPPORTED`,
    /// D-17) falls back to coarse; every other failure is rearm-and-retry
    /// (D-15) and propagates to the caller unchanged.
    ///
    /// A no-op when there is nothing live to (re-)establish: [`ArmGate::TornDown`]
    /// has nothing left to reopen. Called both from [`ArmGate::Open`] (widening
    /// or downgrading for a new route, see [`DirectoryWatcher::add_route`]) and
    /// from [`ArmGate::Faulted`] (a re-establish attempt, see
    /// [`WatcherInner::retry_reestablish`]); either way it takes over the gate
    /// unconditionally except for `TornDown`.
    ///
    /// # Errors
    ///
    /// Returns the error from establishing or arming whichever tier was
    /// settled on.
    fn install(self: &Arc<Self>, handle: DirectoryHandle) -> io::Result<()> {
        // Held for the whole transaction (PR #20 review response): see the
        // field's own doc for why marking `ArmGate::Reopening` alone is not
        // enough to keep a second concurrent caller from interleaving with
        // this one.
        let _reopen_guard = self
            .reopen_lock
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        {
            let mut gate = lock(&self.gate);
            if *gate == ArmGate::TornDown {
                return Ok(());
            }
            // Transient and self-resolving: cleared by the eventual `arm()`
            // call below, or left as `TornDown` if teardown wins the race.
            *gate = ArmGate::Reopening;
        }

        self.teardown_endpoint();

        if self.force_coarse.load(Ordering::Relaxed) {
            drop(handle);
        } else {
            if let Ok(identity) = handle.volume_identity() {
                *lock(&self.volume_identity) = Some(identity);
            }
            self.case_sensitive
                .store(handle.is_case_sensitive(), Ordering::Relaxed);
            self.establish_detailed(handle)?;
            match self.arm_after_install() {
                Ok(()) => return Ok(()),
                Err(error) if classify(&error) == OpenFailure::Unsupported => {
                    log::warn!(
                        "windows-file-watcher: detailed watching unsupported, downgrading to coarse: {error}"
                    );
                    self.teardown_endpoint();
                }
                Err(error) => return Err(error),
            }
        }

        self.establish_coarse()?;
        self.arm_after_install()
    }

    /// Record the *permanent* failure that stopped this watcher for good, and
    /// tell every route the change stream has a hole in it.
    ///
    /// Reached only from [`WatcherInner::retry_reestablish`], when a
    /// re-establish attempt's own open fails in a way D-22 classifies as
    /// permanent -- the one edge D-14's "no terminal state" does not cover,
    /// because retrying would spin forever against a target that can never
    /// become watchable again. Every other failure goes through
    /// [`WatcherInner::enter_fault`] instead.
    fn record_stop(&self, error: io::Error) {
        let mut stopped = lock(&self.stopped);
        if stopped.is_none() {
            *stopped = Some(error);
            drop(stopped);
            *lock(&self.fault) = None;
            self.publish(DecodedBatch::Desync(DesyncCause::Stopped));
        }
    }
}

/// `ERROR_OPERATION_ABORTED`, the completion status a cancelled read reports.
const OPERATION_ABORTED: i32 = windows_sys::Win32::Foundation::ERROR_OPERATION_ABORTED as i32;

impl Resume for WatcherInner {
    /// Queue the re-arm rather than performing it here.
    ///
    /// This runs on whichever thread drained the client's queue, which may be the
    /// client's own. Arming takes the gate lock and issues a read, and teardown
    /// waits on that same lock -- so doing it here would put our critical section
    /// on a thread we do not control. Submitting work is a single non-blocking
    /// call that touches nothing of ours, and the re-arm then happens on this
    /// crate's own pool.
    fn resume(&self) {
        if let Some(work) = self.resume_work.get() {
            work.submit();
        }
    }
}

/// A detailed watcher over one directory.
///
/// Owns the directory handle (through the thread pool's I/O object) and keeps a
/// read outstanding, re-arming after each completion.
pub struct DirectoryWatcher {
    inner: Arc<WatcherInner>,
}

impl DirectoryWatcher {
    /// Open `directory` and arm the first read, with one initial route.
    ///
    /// `path` is kept for re-establishment (M5.1): a live handle cannot be
    /// recovered once its target is gone, but the path can still be retried.
    ///
    /// # Errors
    ///
    /// Returns the error from establishing or arming whichever tier the
    /// directory settles on (D-17), together with `route` handed back so a
    /// caller whose open just succeeded does not also lose the route's
    /// standing fault-question reservation (D-27/D-28) to a same-moment arm
    /// failure.
    pub(crate) fn start(
        directory: DirectoryHandle,
        path: PathBuf,
        route: Route,
    ) -> Result<Self, (io::Error, Route)> {
        Self::start_with(directory, path, DEFAULT_BUFFER_BYTES, route)
    }

    /// As [`start`](Self::start), with an explicit completion-buffer size.
    ///
    /// A small buffer is how a test forces the kernel's overflow signal.
    ///
    /// # Errors
    ///
    /// As [`start`](Self::start).
    pub(crate) fn start_with(
        directory: DirectoryHandle,
        path: PathBuf,
        buffer_bytes: usize,
        route: Route,
    ) -> Result<Self, (io::Error, Route)> {
        Self::start_inner(directory, path, buffer_bytes, route, false)
    }

    /// As [`start`](Self::start), but skipping the detailed attempt entirely
    /// and establishing coarse from the start (M6.4's test seam), regardless of
    /// what the underlying volume actually supports.
    ///
    /// # Errors
    ///
    /// As [`start`](Self::start).
    #[cfg(test)]
    pub(crate) fn start_forcing_coarse(
        directory: DirectoryHandle,
        path: PathBuf,
        route: Route,
    ) -> Result<Self, (io::Error, Route)> {
        Self::start_inner(directory, path, DEFAULT_BUFFER_BYTES, route, true)
    }

    /// Shared constructor body: build the resident state and its callback
    /// machinery, then establish the first read or wait through
    /// [`WatcherInner::reopen`] -- the same tier-choosing path used for every
    /// later widen, re-establish, or downgrade.
    ///
    /// On any failure, `route` is reclaimed from `inner.routes` (it is still
    /// the map's only entry) and returned alongside the error rather than
    /// dropped with the rest of `inner` -- see [`start`](Self::start)'s docs.
    fn start_inner(
        directory: DirectoryHandle,
        path: PathBuf,
        buffer_bytes: usize,
        route: Route,
        force_coarse: bool,
    ) -> Result<Self, (io::Error, Route)> {
        let watch = route.watch;
        let initial_sink = route.sink.clone();
        let mut routes = HashMap::new();
        routes.insert(watch, route);
        let initial_id = directory.identity();

        let inner = Arc::new(WatcherInner {
            path,
            endpoint: Mutex::new(None),
            resume_work: OnceLock::new(),
            retry_timer: OnceLock::new(),
            filter: ALL_NOTIFY_FILTERS,
            buffer_bytes,
            routes: Mutex::new(routes),
            gate: Mutex::new(ArmGate::Open),
            fault: Mutex::new(None),
            stopped: Mutex::new(None),
            force_coarse: AtomicBool::new(force_coarse),
            directory_id: Mutex::new(initial_id),
            volume_identity: Mutex::new(None),
            resident: OnceLock::new(),
            volume_change: Mutex::new(None),
            // Overwritten by `install` below, from the real handle, before
            // this watcher ever arms; the initial value is never observed.
            case_sensitive: AtomicBool::new(false),
            reopen_lock: Mutex::new(()),
        });

        // Pulls this constructor's one route back out of `inner.routes` so a
        // caller can recover it (and the standing reservation it may carry)
        // instead of losing it to `inner`'s drop.
        let reclaim_route = |inner: &Arc<WatcherInner>| -> Route {
            lock(&inner.routes)
                .remove(&watch)
                .expect("the route inserted above is still the map's only entry")
        };

        // As with the completion callback below, a `Weak` rather than a strong
        // reference: the work object lives in `inner`, so a strong one would be
        // a cycle, and a failed upgrade during teardown is exactly the
        // suppression that lets rundown converge.
        let resuming = Arc::downgrade(&inner);
        let resume_work = match ThreadpoolWork::new(
            move || {
                if let Some(inner) = resuming.upgrade() {
                    inner.resume_arm();
                }
            },
            None,
        ) {
            Ok(work) => work,
            Err(error) => return Err((error, reclaim_route(&inner))),
        };
        inner
            .resume_work
            .set(resume_work)
            .unwrap_or_else(|_| unreachable!("the resume work is set exactly once, here"));

        // Mirrors `resume_work`: a `Weak`, so a failed upgrade during teardown
        // suppresses a retry that fires after the watcher is gone. Set once here
        // and re-armed (never recreated) across however many faults this
        // watcher lives through (M5.1).
        let retrying = Arc::downgrade(&inner);
        let retry_timer = match ThreadpoolTimer::new(
            move |_firing| {
                if let Some(inner) = retrying.upgrade() {
                    inner.retry_reestablish();
                }
            },
            None,
        ) {
            Ok(timer) => timer,
            Err(error) => return Err((error, reclaim_route(&inner))),
        };
        inner
            .retry_timer
            .set(retry_timer)
            .unwrap_or_else(|_| unreachable!("the retry timer is set exactly once, here"));

        // Registered before the first arm, so a watcher that is backpressured
        // from the outset is still prodded when the client drains.
        initial_sink.register_resume(&inner);

        if let Err(error) = inner.install(directory) {
            return Err((error, reclaim_route(&inner)));
        }
        Ok(Self { inner })
    }

    /// Add a subscription to this directory (D-6), reopening to widen the
    /// kernel's own reach if this is the first route that needs recursion.
    ///
    /// `fresh_handle` is a handle already opened onto this same directory --
    /// the caller had to open one anyway to discover the directory's identity
    /// and find this watcher to coalesce onto (D-6) -- reused here rather than
    /// opening a second one, and simply dropped if it turns out not to be
    /// needed.
    ///
    /// The other direction -- a recursive route leaving -- never needs the
    /// mirror-image contraction: an over-broad read is filtered back down to
    /// what each remaining route asked for by [`Route::select`], so it costs
    /// nothing but a few extra bytes to decode, where a read that is too
    /// *narrow* would silently under-report.
    ///
    /// A reopen failure enters the fault loop (D-15's rearm-and-retry
    /// classification) rather than stopping the watcher, reported to every
    /// route it currently serves rather than only the one that triggered it,
    /// since they now share one endpoint.
    pub(crate) fn add_route(&self, route: Route, fresh_handle: DirectoryHandle) {
        let widen = route.scope.needs_kernel_subtree();
        let watch = route.watch;
        let sink = route.sink.clone();
        let already_recursive = {
            let mut routes = lock(&self.inner.routes);
            let already = routes
                .values()
                .any(|existing| existing.scope.needs_kernel_subtree());
            routes.insert(watch, route);
            already
        };
        // Registered even when this route does not widen anything: it may still
        // need the resume prod later, on its own account, if its sink saturates
        // while this watcher is paused for some other route.
        sink.register_resume(&self.inner);
        // Only attempted while the gate is `Open`: reopen()/enter_fault() are
        // otherwise reached exclusively through the fault/backoff protocol
        // (`retry_reestablish`/`resolve_fault_success`), and calling them here
        // while already `Faulted`/`Reopening`/etc. would bypass and corrupt
        // that single-owner state machine -- clobbering `self.fault`'s
        // `awaiting` set, orphaning routes still awaiting an answer to the
        // current fault, or leaving a stale, already-armed retry timer racing
        // a reopen this call performed outside its knowledge. Skipping it here
        // costs nothing: the route was already inserted above, so whichever
        // transition is in flight recomputes the reach union fresh from the
        // live route set the next time it arms (D-51), picking up the widened
        // reach on its own.
        if widen
            && !already_recursive
            && self.gate() == ArmGate::Open
            && let Err(error) = self.inner.install(fresh_handle)
        {
            self.inner
                .enter_fault(classify_detail(&error), FaultOperation::Arm);
        }
    }

    /// Remove a subscription, returning how many routes remain, and every
    /// *other* watch a volume-change resolution triggered by this removal
    /// decided to `Stop` (PR #20 review response) -- the caller must remove
    /// each returned watch's own `Resident.subscriptions` entry, in addition
    /// to `watch`'s own, which it is already expected to remove itself.
    ///
    /// The caller tears this watcher down entirely once the remaining count
    /// reaches zero; removing the route itself never requires re-arming (see
    /// [`DirectoryWatcher::add_route`]).
    ///
    /// Cancellation from mid-fault (M5.5): a route awaiting an answer to the
    /// current fault's question that is removed here is treated as if it had
    /// just answered with a decline (it counts at the operation's default,
    /// then is simply not asked again) -- it is leaving, not answering, but the
    /// effect on the remaining reduction is identical, and if it was the last
    /// one still awaited this resolves and schedules the retry immediately
    /// rather than leaving the watcher waiting on an answer that can now never
    /// arrive.
    pub(crate) fn remove_route(&self, watch: WatchId) -> (usize, Vec<WatchId>) {
        let remaining = {
            let mut routes = lock(&self.inner.routes);
            routes.remove(&watch);
            routes.len()
        };
        let resolved = {
            let mut fault = lock(&self.inner.fault);
            match fault.as_mut() {
                Some(state) => {
                    if state.awaiting.remove(&watch) && state.awaiting.is_empty() {
                        Some(state.earliest)
                    } else {
                        None
                    }
                }
                None => None,
            }
        };
        if let Some(delay) = resolved {
            self.inner.resolve_and_schedule(delay);
        }
        if let Some((remaining, stopped)) = self.inner.remove_route_from_volume_change(watch) {
            return (remaining, stopped);
        }
        (remaining, Vec::new())
    }

    /// Answer this watcher's current fault question on behalf of `watch`
    /// (D-27/M5.3), if one is outstanding. A no-op otherwise.
    pub(crate) fn answer(&self, watch: WatchId, delay: Option<Duration>) {
        self.inner.answer(watch, delay);
    }

    /// Answer this watcher's current volume-change question on behalf of
    /// `watch` (D-78/M12.3), if one is outstanding. `None` if not (already
    /// resolved, or never asked); `Some(remaining route count)` if this
    /// answer was the one that resolved it, in which case the caller (M12.4)
    /// must tear the watcher down if that count is zero.
    /// Answer this watcher's current volume-change question on behalf of
    /// `watch` (D-78/M12.3), if one is outstanding. `None` if not (already
    /// resolved, or never asked); `Some((remaining route count, watches that
    /// decided Stop))` if this answer was the one that resolved it, in which
    /// case the caller (M12.4) must tear the watcher down if that count is
    /// zero, and must remove each stopped watch's own `Resident.subscriptions`
    /// entry (PR #20 review response) -- this layer only ever touches
    /// `self.routes`, never the resident-level table those entries live in.
    pub(crate) fn answer_volume_change(
        &self,
        watch: WatchId,
        decision: VolumeChangeDecision,
    ) -> Option<(usize, Vec<WatchId>)> {
        self.inner.answer_volume_change(watch, decision)
    }

    /// The failure that stopped this watcher re-arming, if any. Only ever set
    /// by a *permanent* re-establish failure (D-22); a watcher that is merely
    /// recovering (`is_faulted`) reports nothing here.
    pub fn stop_reason(&self) -> Option<io::Error> {
        lock(&self.inner.stopped).as_ref().map(|error| {
            error.raw_os_error().map_or_else(
                || io::Error::other("watcher stopped"),
                io::Error::from_raw_os_error,
            )
        })
    }

    /// Whether the watcher is still re-arming.
    ///
    /// A backpressured, reopening, or faulted watcher counts: each is paused,
    /// not stopped, and resumes on its own (D-14/D-29). D-31 is why the
    /// distinction is observable at all -- a paused watcher is otherwise
    /// indistinguishable from a quiet directory.
    pub fn is_watching(&self) -> bool {
        lock(&self.inner.stopped).is_none() && self.gate() != ArmGate::TornDown
    }

    /// Whether this watcher is currently working to re-establish itself
    /// (D-31/M5.6): asking, awaiting an answer, or backed off. Distinct from a
    /// permanent stop ([`DirectoryWatcher::stop_reason`]) and from a mere
    /// backpressure pause.
    #[must_use]
    pub fn is_faulted(&self) -> bool {
        lock(&self.inner.fault).is_some()
    }

    /// The classification and raw code behind the current fault, if any
    /// (D-79) -- the same detail an interactive route was, or would have
    /// been, asked about.
    #[must_use]
    pub fn fault_detail(&self) -> Option<FaultDetail> {
        lock(&self.inner.fault).as_ref().map(|state| state.detail)
    }

    #[cfg(test)]
    pub(crate) fn enter_fault_for_test(&self, detail: FaultDetail, operation: FaultOperation) {
        self.inner.enter_fault(detail, operation);
    }

    #[cfg(test)]
    pub(crate) fn record_stop_for_test(&self, error: io::Error) {
        self.inner.record_stop(error);
    }

    #[cfg(test)]
    pub(crate) fn simulate_volume_change_for_test(&self, previous: VolumeIdentity) {
        *lock(&self.inner.volume_identity) = Some(previous);
        self.inner.retry_reestablish();
    }

    /// Which tier is currently servicing this directory (D-13/D-17).
    #[must_use]
    pub(crate) fn mode(&self) -> WatchMode {
        self.inner.mode()
    }

    /// Bind the resident-state map this watcher's directory entry lives in
    /// (M11.4), so a background path-based reopen fallback that lands on a
    /// different `DirectoryId` can re-key its own entry. Called exactly once,
    /// by `route_established`, immediately after construction; a watcher
    /// built directly (as every unit test in this module does) is simply
    /// never bound, and skips re-keying for lack of a real `Resident`.
    pub(crate) fn bind_resident(&self, resident: Weak<Mutex<Resident>>) {
        let _ = self.inner.resident.set(resident);
    }

    /// The path this watcher was opened from (PR #20 review response): what
    /// `monitor::rekey`'s identity-collision handling reopens a fresh handle
    /// from to migrate a redundant watcher's routes onto this one.
    pub(crate) fn path(&self) -> &Path {
        &self.inner.path
    }

    /// Remove and return every route this watcher currently serves, without
    /// tearing the watcher down itself (PR #20 review response): used only
    /// when this watcher has just been found redundant -- coalesced onto by
    /// `monitor::rekey` after a path-based reopen landed on an identity
    /// another watcher already owns -- so its routes can be migrated onto the
    /// survivor before this watcher is dropped.
    pub(crate) fn take_routes(&self) -> Vec<Route> {
        std::mem::take(&mut *lock(&self.inner.routes))
            .into_values()
            .collect()
    }

    /// The current arm gate.
    pub fn gate(&self) -> ArmGate {
        *lock(&self.inner.gate)
    }

    /// Stop watching: refuse further reads, cancel the outstanding one, and wait
    /// for every completion callback to finish (D-20).
    ///
    /// Idempotent, so a caller may stop explicitly and still let `Drop` run.
    /// After it returns, no callback for this watcher is executing or can start,
    /// so nothing further is ever *enqueued*.
    ///
    /// That guarantee covers the sending side only. Notifications already
    /// enqueued are still queued, and a receiver has yet to drain them -- D-38's
    /// split, where the crate owns when watching stops and the client owns when
    /// reading stops. So "teardown returned" must not be read as "my side has
    /// seen everything it will ever see": the two differ by however long the
    /// receiving thread takes to catch up, which is unbounded and is not this
    /// crate's to schedule. Teardown does release the last sender, so draining
    /// until the receiver reports disconnection is what makes a delivered set
    /// complete.
    ///
    /// Must not be called from inside this watcher's own completion callback: it
    /// waits for that callback to finish, so it would wait on itself. Nothing in
    /// this crate does, because the only caller is teardown on an owning thread.
    pub fn stop(&self) {
        // Close the gate *before* cancelling. The other order leaves a window in
        // which a completion callback already running submits a fresh read after
        // the cancellation, and rundown then waits forever for a completion only
        // a future directory change could produce (D-23).
        {
            let mut gate = lock(&self.inner.gate);
            *gate = ArmGate::TornDown;
        }

        // Stops any further retry attempt and, if one is in flight, blocks until
        // it has fully returned -- so by the time this returns, `self.inner`'s
        // endpoint is whatever a completed `reopen` last left it as, and is
        // safe for teardown to act on directly (see `reopen`'s own
        // teardown-race handling).
        if let Some(timer) = self.inner.retry_timer.get() {
            timer.stop_and_drain();
        }

        // With the gate closed, nothing new can be submitted, so tearing down
        // whichever endpoint is installed retires everything outstanding and
        // rundown converges (D-20). Safe to repeat: `teardown_endpoint` takes
        // the endpoint, so a second call finds nothing there.
        self.inner.teardown_endpoint();
    }
}

impl std::fmt::Debug for DirectoryWatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DirectoryWatcher")
            .field("watching", &self.is_watching())
            .finish_non_exhaustive()
    }
}

impl Drop for DirectoryWatcher {
    fn drop(&mut self) {
        // Teardown is the same operation whether it was asked for or implied, so
        // there is one implementation and `Drop` is only the implicit trigger.
        // It is idempotent, so an explicit `stop()` beforehand costs nothing.
        self.stop();

        // The queue sender lives in `inner`, which drops after this: with every
        // callback finished and no strong reference left, the sender is released
        // and the client's receiver observes the disconnect rather than blocking
        // forever on a queue nothing can fill again.
    }
}

/// What `ReadDirectoryChangesW` reported, as the submission seam's answer to
/// "will a completion packet arrive?".
///
/// Takes the raw `BOOL` rather than a `bool` on purpose: the `!= 0` convention is
/// part of the contract being tested, and leaving it at the call site would put
/// the most dangerous comparison in this crate back outside the reach of a test.
///
/// A free function rather than inline in the submission closure, so this crate's
/// most dangerous misreading is observable by a test rather than only by its
/// wreckage. Getting either half wrong tells the thread pool to reclaim an I/O
/// the kernel is still going to complete, and the completion then lands in a
/// freed buffer -- a heap corruption whose visibility depends on allocator
/// behaviour, not a test result. That is not hypothetical: with the comparison
/// still at the call site, inverting it was "caught" only by the process dying
/// with `STATUS_HEAP_CORRUPTION`, and the same class of mutation was recorded
/// `MISSED` in one sweep and a crash in another. A crash is not a test (M15.5).
///
/// Both of the native call's success shapes mean the same thing here, for the
/// reason [`Issued::Pending`] spells out: a packet is coming either way. A
/// non-zero return says the I/O is already done, not that the packet is not
/// coming, and `ERROR_IO_PENDING` says it has not finished yet. Only a genuine
/// failure means no packet will arrive, and only then may the caller reclaim the
/// buffer.
///
/// `last_error` is taken lazily and must not be consulted after a success:
/// `GetLastError` is not meaningful when the call succeeded, so reading it there
/// would classify on a stale value left by some earlier, unrelated call.
fn classify_submission<F>(returned: i32, last_error: F) -> Result<Issued, io::Error>
where
    F: FnOnce() -> io::Error,
{
    if returned != 0 {
        return Ok(Issued::Pending);
    }
    let error = last_error();
    if error.raw_os_error() == Some(ERROR_IO_PENDING as i32) {
        return Ok(Issued::Pending);
    }
    Err(error)
}

/// Lock, recovering the guard if a previous holder panicked.
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(|poison| poison.into_inner())
}

#[cfg(test)]
mod tests;