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
// Copyright (c) 2026 Mike Grier
//! Unit tests for the monitor.
//!
//! The servicing path's own guarantees are tested in `src/servicing/tests.rs`;
//! what is here is the monitor's ownership of watchers -- now reached the way a
//! client reaches it, through a session's subscribe -- and the blocking teardown
//! of D-20.

use std::time::{Duration, Instant};

use windows_sys::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED};

use super::{
    Monitor, Opened, Request, Subscription, awaits_open_answer, lock, open_file_target,
    should_report_established,
};
use crate::directory::{DirectoryHandle, FaultDetail, OpenFailure, VolumeIdentity};
use crate::queue::{Notification, Receiver, WatchId};
use crate::retry::FaultOperation;
use crate::session::Session;
use crate::testing::TempDir;
use crate::watch::{RetryMode, VolumeChangeDecision, VolumeChangePolicy, Watch, WatchOptions};

/// What teardown is allowed to take. Cancellation retires an outstanding read at
/// once, so this only fires if teardown waited for a change instead.
const TEARDOWN_BUDGET: Duration = Duration::from_secs(5);

/// A monitor watching `dir` through one session, with registration already
/// serviced.
fn watching(dir: &std::path::Path) -> (Monitor, Session, Receiver, Watch) {
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(dir, WatchOptions::new())
        .expect("register the subscription");
    monitor.quiesce();
    (monitor, session, receiver, watch)
}

#[test]
fn a_new_monitor_is_running_and_owns_nothing() {
    let monitor = Monitor::new().expect("create the monitor");
    assert!(monitor.is_running());
    assert_eq!(monitor.watcher_count(), 0);
}

#[test]
fn shutdown_stops_the_servicing_path() {
    let monitor = Monitor::new().expect("create the monitor");
    monitor.shut_down();
    assert!(!monitor.is_running());
}

#[test]
fn shutdown_is_idempotent_and_drop_after_it_is_safe() {
    let monitor = Monitor::new().expect("create the monitor");
    monitor.shut_down();
    monitor.shut_down();
    monitor.shut_down();
    assert!(!monitor.is_running());
    drop(monitor);
}

#[test]
fn dropping_an_idle_monitor_is_prompt() {
    let monitor = Monitor::new().expect("create the monitor");
    let started = Instant::now();
    drop(monitor);
    assert!(started.elapsed() < TEARDOWN_BUDGET);
}

#[test]
fn a_subscription_becomes_a_watcher() {
    let dir = TempDir::new("monitor-subscribe");
    let (monitor, _session, _receiver, watch) = watching(dir.path());

    assert_eq!(monitor.watcher_count(), 1);
    assert!(monitor.is_watching(watch.id()));

    drop(watch);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn several_subscriptions_become_several_watchers() {
    let dir = TempDir::new("monitor-several");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let watches: Vec<_> = (0..8)
        .map(|_| {
            session
                .subscribe(dir.path(), WatchOptions::new())
                .expect("register")
        })
        .collect();
    monitor.quiesce();
    assert_eq!(monitor.watcher_count(), 8);

    // Each identifier is distinct, which is what lets a client demultiplex one
    // receiver back into its subscriptions.
    let mut ids: Vec<u64> = watches.iter().map(|watch| watch.id().get()).collect();
    ids.sort_unstable();
    ids.dedup();
    assert_eq!(ids.len(), 8);

    drop(watches);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn teardown_with_watchers_outstanding_converges_promptly() {
    let dir = TempDir::new("monitor-outstanding");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let _watches: Vec<_> = (0..8)
        .map(|_| {
            session
                .subscribe(dir.path(), WatchOptions::new())
                .expect("register")
        })
        .collect();
    monitor.quiesce();

    // Nothing will change this directory again, so only cancellation can retire
    // the eight outstanding reads. A teardown that waited would sit here until
    // the budget expired.
    let started = Instant::now();
    monitor.shut_down();
    let elapsed = started.elapsed();
    assert!(
        elapsed < TEARDOWN_BUDGET,
        "teardown took {elapsed:?}, which means it waited rather than cancelled"
    );
    assert_eq!(monitor.watcher_count(), 0);

    dir.cleanup();
}

#[test]
fn teardown_releases_every_watcher_so_the_receiver_disconnects() {
    let dir = TempDir::new("monitor-release");
    let (monitor, session, receiver, watch) = watching(dir.path());

    // Every holder of a sender must go: the session, the watch that clones it,
    // and the watcher the monitor owns.
    drop(watch);
    drop(session);
    monitor.shut_down();

    assert!(
        receiver.is_disconnected(),
        "teardown must release the watcher's sender, not just forget the table entry"
    );

    dir.cleanup();
}

#[test]
fn dropping_a_monitor_tears_down_its_watchers() {
    let dir = TempDir::new("monitor-drop");
    let (monitor, session, receiver, watch) = watching(dir.path());

    drop(watch);
    drop(session);
    drop(monitor);

    assert!(
        receiver.is_disconnected(),
        "`Drop` must run the same teardown as an explicit shutdown"
    );

    dir.cleanup();
}

#[test]
fn teardown_from_a_thread_other_than_the_creator_is_safe() {
    let dir = TempDir::new("monitor-thread");
    let (monitor, session, receiver, watch) = watching(dir.path());
    drop(watch);
    drop(session);

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

    assert!(receiver.is_disconnected());
    dir.cleanup();
}

#[test]
fn many_monitors_tear_down_concurrently_without_wedging() {
    let dir = TempDir::new("monitor-concurrent");
    let root = dir.path().to_path_buf();

    let workers: Vec<_> = (0..8)
        .map(|_| {
            let root = root.clone();
            std::thread::spawn(move || {
                let (monitor, session, receiver, watch) = watching(&root);
                drop(watch);
                drop(session);
                drop(monitor);
                assert!(receiver.is_disconnected());
            })
        })
        .collect();

    let started = Instant::now();
    for worker in workers {
        worker.join().expect("worker");
    }
    assert!(
        started.elapsed() < Duration::from_secs(30),
        "concurrent teardown wedged"
    );

    dir.cleanup();
}

#[test]
fn debug_reports_the_monitors_state() {
    let dir = TempDir::new("monitor-debug");
    let (monitor, _session, _receiver, watch) = watching(dir.path());

    let rendered = format!("{monitor:?}");
    assert!(rendered.contains("running: true"), "{rendered}");
    assert!(rendered.contains("watchers: 1"), "{rendered}");

    drop(watch);
    drop(monitor);
    dir.cleanup();
}

// --- coalescing by directory (D-6) ---

#[test]
fn two_subscriptions_on_the_same_directory_share_one_watcher() {
    let dir = TempDir::new("coalesce-same");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let a = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let b = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    assert_eq!(monitor.watcher_count(), 2, "two subscriptions");
    assert_eq!(
        monitor.directory_count(),
        1,
        "one directory, one coalesced watcher"
    );

    drop((a, b));
    drop(monitor);
    dir.cleanup();
}

#[test]
fn subscriptions_on_different_directories_get_different_watchers() {
    let first = TempDir::new("coalesce-a");
    let second = TempDir::new("coalesce-b");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let a = session
        .subscribe(first.path(), WatchOptions::new())
        .expect("register");
    let b = session
        .subscribe(second.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    assert_eq!(monitor.directory_count(), 2);

    drop((a, b));
    drop(monitor);
    first.cleanup();
    second.cleanup();
}

#[test]
fn the_same_directory_reached_through_a_different_spelling_still_coalesces() {
    // Coalescing is by identity (D-6), not by string comparison: a trailing
    // separator names the same directory.
    let dir = TempDir::new("coalesce-spelling");
    let mut with_separator = dir.path().to_path_buf();
    with_separator.push(""); // appends the trailing separator

    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();
    let a = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let b = session
        .subscribe(&with_separator, WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    assert_eq!(monitor.directory_count(), 1);

    drop((a, b));
    drop(monitor);
    dir.cleanup();
}

#[test]
fn cancelling_one_of_two_coalesced_subscriptions_keeps_the_watcher_alive() {
    let dir = TempDir::new("coalesce-cancel-one");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let a = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let b = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    a.cancel();
    monitor.quiesce();

    assert_eq!(monitor.watcher_count(), 1, "only b remains");
    assert_eq!(
        monitor.directory_count(),
        1,
        "the watcher survives while a subscriber remains"
    );
    assert!(monitor.is_watching(b.id()));

    drop(b);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn cancelling_the_last_coalesced_subscription_tears_down_the_watcher() {
    let dir = TempDir::new("coalesce-cancel-last");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let a = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let b = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    let a_id = a.id();
    let b_id = b.id();
    a.cancel();
    b.cancel();
    monitor.quiesce();

    assert!(!monitor.is_registered(a_id));
    assert!(!monitor.is_registered(b_id));
    assert_eq!(monitor.watcher_count(), 0);
    assert_eq!(monitor.directory_count(), 0, "the watcher is torn down");

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

#[test]
fn many_subscriptions_on_one_directory_all_coalesce() {
    let dir = TempDir::new("coalesce-many");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let watches: Vec<Watch> = (0..16)
        .map(|_| {
            session
                .subscribe(dir.path(), WatchOptions::new())
                .expect("register")
        })
        .collect();
    monitor.quiesce();

    assert_eq!(monitor.watcher_count(), 16);
    assert_eq!(monitor.directory_count(), 1);

    drop(watches);
    drop(monitor);
    dir.cleanup();
}

// --- open-fault re-establishment (D-14/D-15/D-27, M5.1/M5.3) ---

#[test]
fn a_target_that_does_not_exist_yet_establishes_once_it_appears() {
    let dir = TempDir::new("monitor-retry-appears");
    let target = dir.path().join("not-yet");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(&target, WatchOptions::new())
        .expect("register the subscription");
    monitor.quiesce();

    assert_eq!(monitor.is_faulted(watch.id()), Some(true));
    assert!(!monitor.is_watching(watch.id()));

    std::fs::create_dir(&target).expect("create the target directory");

    let deadline = Instant::now() + Duration::from_secs(10);
    while !monitor.is_watching(watch.id()) {
        assert!(
            Instant::now() < deadline,
            "the subscription never established once its target appeared"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
    assert_eq!(monitor.is_faulted(watch.id()), Some(false));

    drop(receiver);
    drop(watch);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn an_interactive_subscription_is_asked_and_its_answer_speeds_up_establishment() {
    let dir = TempDir::new("monitor-retry-interactive");
    let target = dir.path().join("not-yet");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(
            &target,
            WatchOptions::new().retry(crate::watch::RetryMode::Interactive),
        )
        .expect("register the subscription");
    monitor.quiesce();

    let deadline = Instant::now() + Duration::from_secs(10);
    let mut asked = false;
    while !asked {
        assert!(
            Instant::now() < deadline,
            "the interactive subscription was never asked"
        );
        if let Some(notification) = receiver.try_recv()
            && matches!(notification, Notification::RetryQuestion { watch: id, .. } if id == watch.id())
        {
            asked = true;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    std::fs::create_dir(&target).expect("create the target directory");
    session.answer(watch.id(), Some(Duration::from_millis(1)));

    let deadline = Instant::now() + Duration::from_secs(10);
    while !monitor.is_watching(watch.id()) {
        assert!(
            Instant::now() < deadline,
            "the subscription never established after answering"
        );
        std::thread::sleep(Duration::from_millis(5));
    }

    drop(receiver);
    drop(watch);
    drop(monitor);
    dir.cleanup();
}

// --- reopen identity and re-keying (D-78/M11) ---

#[test]
fn a_path_based_reopen_that_lands_on_a_new_directory_rekeys_so_a_later_subscription_still_coalesces()
 {
    let dir = TempDir::new("coalesce-rekey");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(dir.path(), WatchOptions::new().report_liveness(true))
        .expect("register");
    monitor.quiesce();
    assert_eq!(monitor.directory_count(), 1);

    // Delete and recreate the watched directory: every reopen is a path-based
    // open (D-80 removed the file-reference fast path), so re-establishment
    // lands on a genuinely different `DirectoryId` than the one this watcher
    // started under.
    std::fs::remove_dir_all(dir.path()).expect("delete the watched directory");
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        assert!(Instant::now() < deadline, "the outage was never observed");
        if let Some(notification) = receiver.try_recv()
            && matches!(notification, Notification::Suspended { watch: tag } if tag == watch.id())
        {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    std::fs::create_dir_all(dir.path()).expect("recreate the watched directory");

    // `is_watching` alone would not do here: it only tracks a *permanent*
    // stop, not a transient fault, so it would already read `true` throughout
    // the recovery above. `Resumed` (opt-in, sent only after re-establishment
    // actually succeeds) is the real signal this watcher is done reopening.
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        assert!(
            Instant::now() < deadline,
            "the watcher never reestablished against the recreated directory"
        );
        if let Some(notification) = receiver.try_recv()
            && matches!(notification, Notification::Resumed { watch: tag } if tag == watch.id())
        {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    // If the reopen fallback's new `DirectoryId` was never re-keyed into
    // `Resident.directories` (M11.4), this second subscription to the same,
    // now-recreated path would fail to find the existing watcher -- still
    // keyed under the old, gone identity -- and spin up a redundant second
    // one.
    let second = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register a second subscription to the same, recreated path");
    monitor.quiesce();

    assert_eq!(
        monitor.directory_count(),
        1,
        "the recreated directory's watcher must be re-keyed, not duplicated"
    );

    watch.cancel();
    second.cancel();
    monitor.quiesce();
    assert_eq!(
        monitor.directory_count(),
        0,
        "cancelling re-keyed routes must retire their shared watcher"
    );

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

#[test]
fn a_path_based_reopen_that_collides_with_another_watched_directory_migrates_routes_instead_of_dropping_them()
 {
    // PR #20 review response: a path-based reopen can land on a `DirectoryId`
    // another watcher already owns -- here, by replacing the reopened path
    // with a junction into the other watched directory. Before the fix,
    // `rekey` silently `insert`-ed over that entry, dropping the pre-existing
    // watcher (and every route it served) with nothing to migrate them.
    let dir_a = TempDir::new("collide-rekey-a");
    let dir_b = TempDir::new("collide-rekey-b");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    // Two independently-watched, genuinely distinct directories.
    let watch_a = session
        .subscribe(dir_a.path(), WatchOptions::new().report_liveness(true))
        .expect("register the first subscription");
    let watch_b = session
        .subscribe(dir_b.path(), WatchOptions::new().report_liveness(true))
        .expect("register the second subscription");
    monitor.quiesce();
    assert_eq!(monitor.directory_count(), 2);

    // Replace dir_b's path with a junction into dir_a, so re-opening dir_b's
    // original path resolves to dir_a's identity -- the same collision a
    // real "reopened path was replaced by a junction" scenario produces.
    std::fs::remove_dir_all(dir_b.path()).expect("delete dir_b");
    // The paths go as `OsStr`s rather than through `display()`, which is
    // documented to replace invalid sequences with U+FFFD -- so a formatted
    // path could point `mklink` at a different directory than the one this test
    // then watches, and the junction would be built somewhere else entirely.
    let status = std::process::Command::new("cmd")
        .arg("/C")
        .arg("mklink")
        .arg("/J")
        .arg(dir_b.path())
        .arg(dir_a.path())
        .status()
        .expect("run mklink");
    assert!(status.success(), "mklink /J failed to create the junction");

    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        assert!(
            Instant::now() < deadline,
            "watch_b never reestablished against the junctioned path"
        );
        if let Some(notification) = receiver.try_recv()
            && matches!(notification, Notification::Resumed { watch: tag } if tag == watch_b.id())
        {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    assert_eq!(
        monitor.directory_count(),
        1,
        "the two watchers must have coalesced onto one, not left as two \
         (which would mean the collision was never detected) and not zero \
         (which would mean one was dropped without migrating its route)"
    );

    // The proof that watch_b's route was migrated, not dropped: a change
    // under dir_a's real path (which is also now watch_b's own, junctioned
    // path) must still reach watch_b's sink.
    std::fs::write(dir_a.path().join("after-collision.txt"), b"x").expect("create a file");
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        assert!(
            Instant::now() < deadline,
            "watch_b's route was not migrated onto the surviving watcher"
        );
        if let Some(Notification::Batch { watch: tag, .. }) = receiver.try_recv()
            && tag == watch_b.id()
        {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    drop((watch_a, watch_b));
    drop(monitor);
    dir_a.cleanup();
    // `dir_b` is now a junction (a reparse point), not a real directory with
    // its own content; removing the junction point itself is enough, and
    // `TempDir::cleanup`'s `remove_dir_all` does exactly that without
    // following it into `dir_a`.
    dir_b.cleanup();
}

fn with_only_directory_watcher<T>(
    monitor: &Monitor,
    inspect: impl FnOnce(&crate::watcher::DirectoryWatcher) -> T,
) -> T {
    let resident = lock(&monitor.resident);
    assert_eq!(resident.directories.len(), 1);
    inspect(
        resident
            .directories
            .values()
            .next()
            .expect("the directory watcher exists"),
    )
}

#[test]
fn request_debug_reports_the_variant_and_fields() {
    let request = Request::Retry {
        watch: WatchId::from_raw(17),
    };

    assert_eq!(format!("{request:?}"), "Retry { watch: WatchId(17) }");
}

#[test]
fn only_interactive_routes_with_a_standing_slot_await_an_open_answer() {
    let cases = [
        (RetryMode::Defaults, false, false),
        (RetryMode::Defaults, true, false),
        (RetryMode::Interactive, false, false),
        (RetryMode::Interactive, true, true),
    ];

    for (retry, has_fault_slot, expected) in cases {
        assert_eq!(
            awaits_open_answer(retry, has_fault_slot),
            expected,
            "retry={retry:?}, has_fault_slot={has_fault_slot}"
        );
    }
}

#[test]
fn established_is_reported_only_for_a_live_opted_in_route() {
    let cases = [
        (false, false, false),
        (false, true, false),
        (true, false, true),
        (true, true, false),
    ];

    for (report_liveness, is_faulted, expected) in cases {
        assert_eq!(
            should_report_established(report_liveness, is_faulted),
            expected,
            "report_liveness={report_liveness}, is_faulted={is_faulted}"
        );
    }
}

#[test]
fn file_target_parent_failures_retain_their_retry_classification() {
    let dir = TempDir::new("monitor-file-parent-failures");

    let missing_parent = dir.path().join("missing-parent").join("leaf.txt");
    match open_file_target(&missing_parent) {
        Opened::Pending(detail) => assert!(detail.failure.is_retryable()),
        Opened::Handle { .. } | Opened::Failed(_) => {
            panic!("a missing parent must remain retryable")
        }
    }

    let file_parent = dir.path().join("not-a-directory");
    std::fs::write(&file_parent, b"x").expect("create the non-directory parent");
    match open_file_target(&file_parent.join("leaf.txt")) {
        Opened::Failed(detail) => assert_eq!(detail.failure, OpenFailure::NotADirectory),
        Opened::Handle { .. } | Opened::Pending(_) => {
            panic!("a file used as the parent must fail permanently")
        }
    }

    dir.cleanup();
}

#[test]
fn monitor_projects_a_routed_watchers_fault_and_permanent_stop() {
    let dir = TempDir::new("monitor-project-watcher-state");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();
    let watch = session
        .subscribe(
            dir.path(),
            WatchOptions::new().retry(RetryMode::Interactive),
        )
        .expect("register the subscription");
    monitor.quiesce();

    let detail = FaultDetail::synthetic(OpenFailure::Unsupported, ERROR_NOT_SUPPORTED);
    with_only_directory_watcher(&monitor, |watcher| {
        watcher.enter_fault_for_test(detail, FaultOperation::Arm);
    });
    assert_eq!(monitor.fault_detail(watch.id()), Some(detail));
    assert!(monitor.stop_reason(watch.id()).is_none());

    with_only_directory_watcher(&monitor, |watcher| {
        watcher.record_stop_for_test(std::io::Error::from_raw_os_error(
            i32::try_from(ERROR_ACCESS_DENIED).expect("Win32 errors fit in i32"),
        ));
    });
    assert_eq!(
        monitor
            .stop_reason(watch.id())
            .and_then(|error| error.raw_os_error()),
        Some(i32::try_from(ERROR_ACCESS_DENIED).expect("Win32 errors fit in i32"))
    );
    assert_eq!(monitor.fault_detail(watch.id()), None);

    drop(watch);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn a_volume_confirmation_slot_does_not_make_open_retries_interactive() {
    let dir = TempDir::new("monitor-volume-slot-open-retry");
    let target = dir.path().join("not-yet");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(
            &target,
            WatchOptions::new().on_volume_change(VolumeChangePolicy::Confirm),
        )
        .expect("register the subscription");
    monitor.quiesce();

    let resident = lock(&monitor.resident);
    let Some(Subscription::Pending {
        awaiting_answer, ..
    }) = resident.subscriptions.get(&watch.id())
    else {
        panic!("the missing target must be pending")
    };
    assert!(!awaiting_answer);
    drop(resident);

    while let Some(notification) = receiver.try_recv() {
        assert!(
            !matches!(notification, Notification::RetryQuestion { watch: id, .. } if id == watch.id()),
            "a volume-only standing slot must not receive an open-fault question"
        );
    }

    drop(watch);
    drop(monitor);
    dir.cleanup();
}

#[test]
fn coalescing_onto_a_faulted_watcher_suppresses_established() {
    let dir = TempDir::new("monitor-faulted-coalesce");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let first = session
        .subscribe(
            dir.path(),
            WatchOptions::new().retry(RetryMode::Interactive),
        )
        .expect("register the first subscription");
    monitor.quiesce();

    let detail = FaultDetail::synthetic(OpenFailure::Unsupported, ERROR_NOT_SUPPORTED);
    with_only_directory_watcher(&monitor, |watcher| {
        watcher.enter_fault_for_test(detail, FaultOperation::Arm);
    });

    let second = session
        .subscribe(dir.path(), WatchOptions::new().report_liveness(true))
        .expect("coalesce the second subscription");
    monitor.quiesce();

    while let Some(notification) = receiver.try_recv() {
        assert!(
            !matches!(notification, Notification::Established { watch, .. } if watch == second.id()),
            "a faulted watcher has no settled tier to report"
        );
    }

    drop((first, second));
    drop(monitor);
    dir.cleanup();
}

#[test]
fn stopping_the_only_route_after_a_volume_change_removes_its_resident_state() {
    let dir = TempDir::new("monitor-volume-stop-cleanup");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(
            dir.path(),
            WatchOptions::new().on_volume_change(VolumeChangePolicy::Confirm),
        )
        .expect("register the subscription");
    monitor.quiesce();

    let current = DirectoryHandle::open(dir.path())
        .expect("open the watched directory")
        .volume_identity()
        .expect("read its volume identity");
    let previous = [0, u32::MAX]
        .into_iter()
        .map(|serial| VolumeIdentity::synthetic(serial, "TEST-FS", "TEST-VOLUME"))
        .find(|candidate| *candidate != current)
        .expect("one synthetic serial differs from the real volume");
    with_only_directory_watcher(&monitor, |watcher| {
        watcher.simulate_volume_change_for_test(previous);
    });

    let mut asked = false;
    while let Some(notification) = receiver.try_recv() {
        if matches!(notification, Notification::VolumeChanged { watch: id, .. } if id == watch.id())
        {
            asked = true;
        }
    }
    assert!(
        asked,
        "the confirming route must receive the volume question"
    );

    session.answer_volume_change(watch.id(), VolumeChangeDecision::Stop);
    monitor.quiesce();

    assert!(!monitor.is_registered(watch.id()));
    assert_eq!(monitor.directory_count(), 0);

    drop(watch);
    drop(monitor);
    dir.cleanup();
}