windows-file-watcher 0.2.2

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
// Copyright (c) 2026 Mike Grier
//! Unit tests for the affine subscription handle.
//!
//! What is under test is the lifetime contract -- registration begins a watch,
//! and both ways of ending one end it -- plus the binding between a subscription
//! and the receiver its notifications reach.

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

use windows_sys::Win32::Foundation::ERROR_INVALID_NAME;

use super::{RetryMode, WatchOptions};
use crate::directory::{FailureCode, FaultDetail, OpenFailure};
use crate::monitor::Monitor;
use crate::notify::ChangeKind;
use crate::queue::{Notification, Outcome, Receiver, WatchId};
use crate::testing::TempDir;

/// Upper bound for waiting on a change the kernel really should report.
///
/// **5s, matching the measured bound in `watcher/tests.rs`.** That module states
/// the evidence -- on a mutant that breaks delivery, 93.6s at 30s (killed by
/// cargo-mutants' deadline, and so filed as `timeout` rather than `caught`)
/// against 31.8s at 5s (a clean red test) -- and this copy was left at 30s when
/// the others were lowered, which put this module back in the case that
/// measurement exists to avoid.
///
/// It matters more here than the count of waits suggests: [`Drain::wait_for`]
/// spends this budget *per notification it is still looking for*, so a broken
/// delivery path pays it repeatedly on the way to failing.
///
/// The same residual risk applies as there: 5s is ~10x the structural outlier
/// measured on one 12-core developer machine, and a much slower runner is
/// unmeasured. If this flakes, that is the reason, and the answer is to raise
/// it -- in both places, together -- rather than to conclude the tests are wrong.
const NOTIFY_TIMEOUT: Duration = Duration::from_secs(5);

/// The subscription this notification tagged, if it reports `name` as added.
fn added_by(item: &Notification, name: &str) -> Option<WatchId> {
    match item {
        Notification::Batch { watch, changes }
            if changes.iter().any(|change| {
                change.kind == ChangeKind::Added
                    && change.name.to_os_string().to_string_lossy() == name
            }) =>
        {
            Some(*watch)
        }
        _ => None,
    }
}

/// A receiver being drained, holding on to whatever has not been asked for yet.
///
/// # Waiting for one name must not discard the others
///
/// **A receiver carries every subscription's stream, and two watches deliver
/// independently.** The obvious helper -- loop until the wanted name shows up,
/// dropping whatever else arrives -- silently destroys notifications the test
/// has not asked for *yet*. A second wait then blocks for the full timeout on
/// something that already arrived and was thrown away.
///
/// That is not hypothetical: it is what
/// [`two_subscriptions_on_one_session_are_distinguishable`] hit in CI. Its two
/// directories are watched separately, nothing orders one against the other,
/// and when the second arrived first the wait for `in-first.txt` consumed and
/// discarded it. Reproduced deterministically by writing the second file first
/// -- the failure is a property of the helper, not of the watcher, which had
/// delivered both.
///
/// Holding the unmatched items makes the order irrelevant, so a test states
/// what it expects to see rather than what order it must arrive in.
struct Drain<'a> {
    receiver: &'a Receiver,
    held: Vec<Notification>,
}

impl<'a> Drain<'a> {
    fn new(receiver: &'a Receiver) -> Self {
        Self {
            receiver,
            held: Vec::new(),
        }
    }

    /// Wait for a change to `name`, returning the subscription it was tagged
    /// with. Fails rather than hanging.
    fn wait_for(&mut self, name: &str) -> WatchId {
        // Anything already taken off the receiver is checked first, which is
        // the whole point of holding it.
        if let Some(index) = self
            .held
            .iter()
            .position(|item| added_by(item, name).is_some())
        {
            let item = self.held.remove(index);
            return added_by(&item, name).expect("just matched");
        }

        let deadline = Instant::now() + NOTIFY_TIMEOUT;
        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_default();
            assert!(
                !remaining.is_zero(),
                "timed out waiting for a change to {name}"
            );
            let Some(item) = self.receiver.recv_timeout(remaining) else {
                continue;
            };
            if let Some(watch) = added_by(&item, name) {
                return watch;
            }
            self.held.push(item);
        }
    }
}

#[test]
fn options_default_to_a_shallow_autonomous_watch() {
    let options = WatchOptions::new();
    assert!(!options.subtree);
    assert_eq!(options.retry, RetryMode::Defaults);
    assert_eq!(options, WatchOptions::default());
}

#[test]
fn options_carry_what_the_client_states() {
    let options = WatchOptions::new()
        .subtree(true)
        .retry(RetryMode::Interactive);
    assert!(options.subtree);
    assert_eq!(options.retry, RetryMode::Interactive);
}

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

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

    assert!(monitor.is_watching(watch.id()));

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

#[test]
fn every_subscription_gets_its_own_identifier() {
    let dir = TempDir::new("watch-ids");
    let monitor = Monitor::new().expect("create the monitor");
    let (first_session, _first) = monitor.session();
    let (second_session, _second) = monitor.session();

    // Identifiers are minted per monitor, not per session: they key resident
    // state, so two sessions must never mint the same one.
    let a = first_session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let b = second_session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    assert_ne!(a.id(), b.id());

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

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

    let watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();
    let id = watch.id();
    assert!(monitor.is_watching(id));

    watch.cancel();
    monitor.quiesce();
    assert!(!monitor.is_watching(id), "cancel must release the watcher");
    assert_eq!(monitor.watcher_count(), 0);

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

#[test]
fn dropping_a_watch_ends_it_too() {
    // The affine half of D-5: `Drop` is cancellation, which is what makes the
    // handle's `#[must_use]` load-bearing rather than decorative.
    let dir = TempDir::new("watch-drop");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

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

    drop(watch);
    monitor.quiesce();
    assert!(!monitor.is_watching(id));

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

#[test]
fn a_cancelled_watch_does_not_cancel_twice_when_dropped() {
    // `cancel` consumes the handle, so `Drop` still runs; enqueueing a second
    // cancellation would be a request for a subscription that no longer exists.
    let dir = TempDir::new("watch-twice");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

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

    // A second subscription must be unaffected by the first's teardown.
    let next = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    monitor.quiesce();
    assert!(monitor.is_watching(next.id()));
    assert_eq!(monitor.watcher_count(), 1);

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

#[test]
fn a_watch_delivers_to_its_sessions_receiver_tagged_with_its_own_id() {
    let dir = TempDir::new("watch-deliver");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

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

    std::fs::write(dir.path().join("alpha.txt"), b"a").expect("create");
    assert_eq!(
        Drain::new(&receiver).wait_for("alpha.txt"),
        watch.id(),
        "a notification carries the subscription that produced it"
    );

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

#[test]
fn two_subscriptions_on_one_session_are_distinguishable() {
    let first = TempDir::new("watch-first");
    let second = TempDir::new("watch-second");
    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();

    std::fs::write(first.path().join("in-first.txt"), b"a").expect("create");
    std::fs::write(second.path().join("in-second.txt"), b"b").expect("create");

    // One receiver, two streams: the tag is what lets a client tell them apart.
    //
    // One `Drain` for both waits, deliberately. The two directories are watched
    // independently and nothing orders their notifications, so either may
    // arrive first; a helper that dropped the one it was not asked for would
    // make this test fail whenever the second beat the first.
    let mut changes = Drain::new(&receiver);
    assert_eq!(changes.wait_for("in-first.txt"), a.id());
    assert_eq!(changes.wait_for("in-second.txt"), b.id());

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

#[test]
fn a_subtree_subscription_reports_below_itself() {
    let dir = TempDir::new("watch-subtree");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watch = session
        .subscribe(dir.path(), WatchOptions::new().subtree(true))
        .expect("register");
    monitor.quiesce();

    let nested = dir.path().join("nested");
    std::fs::create_dir(&nested).expect("create the subdirectory");
    std::fs::write(nested.join("deep.txt"), b"deep").expect("create the nested file");

    assert_eq!(
        Drain::new(&receiver).wait_for("nested\\deep.txt"),
        watch.id()
    );

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

#[test]
fn the_retry_mode_stated_at_registration_is_recorded() {
    // M5.3 is what acts on this, but registration is the only place a client can
    // state it (D-27), so it is carried and observable from the start.
    let dir = TempDir::new("watch-retry");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session();

    let defaults = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let interactive = session
        .subscribe(
            dir.path(),
            WatchOptions::new().retry(RetryMode::Interactive),
        )
        .expect("register");
    monitor.quiesce();

    assert_eq!(monitor.retry_mode(defaults.id()), Some(RetryMode::Defaults));
    assert_eq!(
        monitor.retry_mode(interactive.id()),
        Some(RetryMode::Interactive)
    );

    drop((defaults, interactive));
    drop(monitor);
    dir.cleanup();
}

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

    let error = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect_err("a shut-down monitor cannot register anything");
    assert_eq!(error.kind(), std::io::ErrorKind::NotConnected);

    dir.cleanup();
}

#[test]
fn a_watch_outliving_its_monitor_drops_without_wedging() {
    // Cancellation is a request, and a shut-down monitor refuses requests -- so
    // `Drop` must treat that rejection as nothing to do rather than an error.
    let dir = TempDir::new("watch-outlives");
    let watch = {
        let monitor = Monitor::new().expect("create the monitor");
        let (session, _receiver) = monitor.session();
        let watch = session
            .subscribe(dir.path(), WatchOptions::new())
            .expect("register");
        monitor.quiesce();
        watch
    };

    let started = Instant::now();
    drop(watch);
    assert!(started.elapsed() < Duration::from_secs(5));

    dir.cleanup();
}

// --- request completions (D-30) ---

/// Drain until a completion for `watch` arrives, returning its outcome.
fn await_completion(receiver: &Receiver, watch: WatchId) -> Outcome {
    let deadline = Instant::now() + NOTIFY_TIMEOUT;
    loop {
        let remaining = deadline
            .checked_duration_since(Instant::now())
            .unwrap_or_default();
        assert!(
            !remaining.is_zero(),
            "timed out waiting for a completion for {watch:?}"
        );
        let Some(item) = receiver.recv_timeout(remaining) else {
            continue;
        };
        if let Notification::Completion {
            watch: reported,
            outcome,
        } = item
            && reported == watch
        {
            return outcome;
        }
    }
}

#[test]
fn a_successful_subscribe_reports_itself() {
    let dir = TempDir::new("completion-ok");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");

    assert_eq!(await_completion(&receiver, watch.id()), Outcome::Subscribed);

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

#[test]
fn a_path_through_a_file_is_reported_as_establishing_not_failed() {
    // A path that treats a *file* as if it were a directory with contents (an
    // intermediate component that is not itself a directory) does not exist as
    // far as `CreateFileW` is concerned -- Windows reports `ERROR_PATH_NOT_FOUND`
    // for the whole path rather than naming the file in the middle, so this
    // classifies as retryable (D-22) exactly like any other not-yet-existing
    // path, not as a permanent `NotADirectory`.
    let dir = TempDir::new("completion-file");
    let file = dir.path().join("a-file-not-a-directory.txt");
    std::fs::write(&file, b"x").expect("create the file");
    let impossible = file.join("nested");

    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(&impossible, WatchOptions::new())
        .expect("register");

    assert_eq!(
        await_completion(&receiver, watch.id()),
        Outcome::Establishing
    );

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

#[test]
fn an_interior_nul_is_reported_as_a_permanent_failure() {
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe("c:\\some\0path", WatchOptions::new())
        .expect("register");

    assert_eq!(
        await_completion(&receiver, watch.id()),
        Outcome::Failed {
            detail: FaultDetail {
                failure: OpenFailure::InvalidPath,
                code: FailureCode::Win32(ERROR_INVALID_NAME),
            }
        }
    );

    drop(watch);
    drop(monitor);
}

#[test]
fn a_target_that_does_not_exist_yet_is_establishing_rather_than_failed() {
    // D-14 has no terminal fault state, so a path that may appear later is a
    // state to recover from, not a failure to report. The subscription stays
    // registered; M5.1 is what drives the recovery.
    let dir = TempDir::new("completion-missing");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(dir.path().join("not-yet"), WatchOptions::new())
        .expect("register");

    assert_eq!(
        await_completion(&receiver, watch.id()),
        Outcome::Establishing
    );
    monitor.quiesce();
    assert!(monitor.is_registered(watch.id()), "still a subscription");
    assert!(!monitor.is_watching(watch.id()), "but not yet established");

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

#[test]
fn cancelling_reports_itself() {
    let dir = TempDir::new("completion-cancel");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let id = watch.id();
    assert_eq!(await_completion(&receiver, id), Outcome::Subscribed);

    watch.cancel();
    assert_eq!(await_completion(&receiver, id), Outcome::Cancelled);

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

#[test]
fn dropping_a_watch_reports_the_cancellation_too() {
    // `Drop` has nowhere to report a refused reservation, which is why the
    // cancellation's slot is taken at registration; this asserts the completion
    // that guarantee exists to make possible.
    let dir = TempDir::new("completion-drop");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let id = watch.id();
    assert_eq!(await_completion(&receiver, id), Outcome::Subscribed);

    drop(watch);
    assert_eq!(await_completion(&receiver, id), Outcome::Cancelled);

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

#[test]
fn nothing_follows_a_cancellation_in_the_stream() {
    // The structural ordering D-30 buys: because the completion is enqueued only
    // once the watcher is fully stopped, a client can treat `Cancelled` as a
    // boundary rather than having to reason about timing.
    let dir = TempDir::new("completion-order");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");
    let id = watch.id();
    assert_eq!(await_completion(&receiver, id), Outcome::Subscribed);

    // Generate real traffic right up to the cancellation, so the boundary is
    // being asserted against a stream that is actually moving.
    for index in 0..200 {
        std::fs::write(dir.path().join(format!("f-{index}.txt")), b"x").expect("create");
    }
    watch.cancel();

    let mut seen_cancelled = false;
    let deadline = Instant::now() + NOTIFY_TIMEOUT;
    loop {
        let remaining = deadline
            .checked_duration_since(Instant::now())
            .unwrap_or_default();
        assert!(!remaining.is_zero(), "timed out draining the stream");
        let Some(item) = receiver.recv_timeout(remaining) else {
            if seen_cancelled {
                break;
            }
            continue;
        };
        match item {
            Notification::Completion {
                watch: reported,
                outcome: Outcome::Cancelled,
            } if reported == id => seen_cancelled = true,
            other => assert!(
                !seen_cancelled || other.watch() != id,
                "nothing for a cancelled watch may follow its cancellation, saw {other:?}"
            ),
        }
        if seen_cancelled && receiver.is_empty() {
            break;
        }
    }
    assert!(seen_cancelled, "the cancellation must be reported");

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

#[test]
fn a_completion_is_delivered_even_when_the_queue_is_saturated() {
    // The point of reserving at submit (D-33): change traffic cannot crowd out a
    // completion, however far behind the client is.
    let dir = TempDir::new("completion-full");
    let monitor = Monitor::new().expect("create the monitor");
    // Four slots: two are this subscription's reservations, leaving almost
    // nothing for observation.
    let (session, receiver) = monitor.session_with_bound(NonZeroUsize::new(4).expect("non-zero"));

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

    // Saturate with real change traffic and never drain.
    for index in 0..500 {
        std::fs::write(dir.path().join(format!("f-{index}.txt")), b"x").expect("create");
    }
    std::thread::sleep(Duration::from_millis(100));

    watch.cancel();

    // Both completions must survive, however much change traffic was dropped or
    // latched around them: neither ever competed for the room they were promised.
    let mut outcomes = Vec::new();
    loop {
        let outcome = await_completion(&receiver, id);
        outcomes.push(outcome);
        if outcome == Outcome::Cancelled {
            break;
        }
    }
    assert!(
        outcomes.contains(&Outcome::Subscribed),
        "the registration completion was lost to saturation, saw {outcomes:?}"
    );

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

#[test]
fn registration_is_refused_when_no_completion_can_be_promised() {
    // Backpressure lands here, on the client's own thread at the call that asked
    // for the work, rather than at a delivery with no safe way to fail.
    let dir = TempDir::new("completion-backpressure");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, _receiver) = monitor.session_with_bound(NonZeroUsize::new(2).expect("non-zero"));

    // The first subscription takes both slots: one for its completion, one
    // standing for its cancellation.
    let first = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register");

    let error = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect_err("there is no room to promise a second subscription's completions");
    assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock);

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

#[test]
fn every_subscription_gets_exactly_one_completion_of_each_kind() {
    let dir = TempDir::new("completion-count");
    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();

    let watches: Vec<_> = (0..16)
        .map(|_| {
            session
                .subscribe(dir.path(), WatchOptions::new())
                .expect("register")
        })
        .collect();
    let ids: Vec<WatchId> = watches.iter().map(super::Watch::id).collect();
    for id in &ids {
        assert_eq!(await_completion(&receiver, *id), Outcome::Subscribed);
    }

    drop(watches);
    for id in &ids {
        assert_eq!(await_completion(&receiver, *id), Outcome::Cancelled);
    }

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

// --- file targets (D-7) ---

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

    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(&file, WatchOptions::new())
        .expect("register");

    assert_eq!(await_completion(&receiver, watch.id()), Outcome::Subscribed);
    assert!(monitor.is_watching(watch.id()));

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

#[test]
fn a_file_target_reports_changes_to_that_file_and_nothing_else() {
    let dir = TempDir::new("file-target-filter");
    let target = dir.path().join("target.txt");
    // The target must exist at subscribe time: resolving a not-yet-existing path
    // to a file target versus a directory target is left to M5's re-establish
    // loop (see the module docs), not attempted here.
    std::fs::write(&target, b"x").expect("create the target");

    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let watch = session
        .subscribe(&target, WatchOptions::new())
        .expect("register");
    monitor.quiesce();

    std::fs::write(dir.path().join("other.txt"), b"y").expect("create an unrelated sibling");
    std::fs::remove_file(&target).expect("remove the target");
    std::fs::write(&target, b"recreated").expect("recreate the target");

    assert_eq!(Drain::new(&receiver).wait_for("target.txt"), watch.id());

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

#[test]
fn a_file_target_and_a_directory_target_on_the_same_directory_coalesce() {
    let dir = TempDir::new("file-target-coalesce");
    let target = dir.path().join("target.txt");
    std::fs::write(&target, b"x").expect("create the target");

    let monitor = Monitor::new().expect("create the monitor");
    let (session, receiver) = monitor.session();
    let file_watch = session
        .subscribe(&target, WatchOptions::new())
        .expect("register the file target");
    let dir_watch = session
        .subscribe(dir.path(), WatchOptions::new())
        .expect("register the directory target");
    monitor.quiesce();

    assert_eq!(
        monitor.directory_count(),
        1,
        "one directory, one coalesced watcher, regardless of target kind"
    );

    std::fs::write(dir.path().join("fresh.txt"), b"x").expect("create a new file");
    let seen_by = Drain::new(&receiver).wait_for("fresh.txt");
    assert!(seen_by == file_watch.id() || seen_by == dir_watch.id());

    drop((file_watch, dir_watch));
    drop(monitor);
    dir.cleanup();
}

#[test]
fn a_wait_does_not_discard_another_subscriptions_notification() {
    // **The regression guard for a real CI failure.** Two directories are
    // watched independently and nothing orders their notifications, so the
    // second may be delivered first. A drain that dropped whatever it was not
    // currently asked for destroyed that notification, and the next wait then
    // blocked for the full timeout on something that had already arrived --
    // reported as "timed out waiting for a change to in-second.txt".
    //
    // Writing the second file first, with a gap, forces the order that made it
    // fail rather than waiting for chance to produce it: before the fix this
    // failed in 30s every run, and after it passes in well under one.
    let first = TempDir::new("watch-order-first");
    let second = TempDir::new("watch-order-second");
    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();

    std::fs::write(second.path().join("in-second.txt"), b"b").expect("create");
    std::thread::sleep(Duration::from_millis(300));
    std::fs::write(first.path().join("in-first.txt"), b"a").expect("create");

    // Asked for in the opposite order to the one they arrived in.
    let mut changes = Drain::new(&receiver);
    assert_eq!(changes.wait_for("in-first.txt"), a.id());
    assert_eq!(changes.wait_for("in-second.txt"), b.id());

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