Skip to main content

storage_kit/ns/
conformance.rs

1//! The conformance suite: the **same cases against every backend**.
2//!
3//! A case says which capabilities it needs ([`Requirement`]). If the backend's [`Caps`] says it lacks one, the case is
4//! **skipped and reported with the reason**, never silently dropped and never failed. The mirror image is a case that runs
5//! only when a capability is *missing* and proves the backend then returns `Unsupported` for it: declaring a capability
6//! false is a promise the suite checks.
7//!
8//! ```
9//! # #[cfg(feature = "conformance")] {
10//! use storage_kit::ns::{conformance, Memory};
11//! let report = conformance::run("memory", &Memory::new());
12//! report.assert_ok();
13//! # }
14//! ```
15//!
16//! To check a new backend, call [`run`] on it from a test. A report lists what passed, what was skipped and why, and what
17//! failed and why. The suite writes only inside a scratch directory it creates and removes (`/conf-...`); on a backend
18//! that is not writable it runs the read-only cases against `/` and writes nothing.
19//!
20//! What it does *not* cover: `HostDir`'s symlink, hard-link, FIFO and race behaviour (a `Memory` has none to test), which
21//! live in that backend's own tests.
22
23use std::fmt::Debug;
24use std::panic::{catch_unwind, AssertUnwindSafe};
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::sync::Barrier;
27use std::time::{Duration, Instant};
28
29use super::backend::{Backend, Caps, Entry, Kind, Stat, Version, WatchKind, WriteOp};
30use super::error::{InputReason, NsError, NsErrorKind, NsResult};
31use super::namespace::Namespace;
32use super::path::{validate_name, NsPath};
33use super::watch::{Watch, WatchBatch, WatchCursor, WatchOpts};
34
35/// A capability a case can depend on.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Cap {
38    /// [`Caps::writable`]
39    Writable,
40    /// [`Caps::atomic_replace`]
41    AtomicReplace,
42    /// [`Caps::exact_if_version`]
43    ExactIfVersion,
44    /// `Caps::watch` is not [`WatchKind::None`]
45    Watch,
46    /// [`Caps::owner_mode`]
47    OwnerMode,
48}
49
50impl Cap {
51    fn present(self, caps: &Caps) -> bool {
52        match self {
53            Cap::Writable => caps.writable,
54            Cap::AtomicReplace => caps.atomic_replace,
55            Cap::ExactIfVersion => caps.exact_if_version,
56            Cap::Watch => caps.watch != WatchKind::None,
57            Cap::OwnerMode => caps.owner_mode,
58        }
59    }
60
61    fn name(self) -> &'static str {
62        match self {
63            Cap::Writable => "writable",
64            Cap::AtomicReplace => "atomic_replace",
65            Cap::ExactIfVersion => "exact_if_version",
66            Cap::Watch => "watch",
67            Cap::OwnerMode => "owner_mode",
68        }
69    }
70}
71
72/// What a case needs from the backend to be meaningful.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Requirement {
75    /// The backend declares this capability.
76    Has(Cap),
77    /// The backend declares this capability **false**: the case then proves it answers `Unsupported`.
78    Lacks(Cap),
79}
80
81/// One conformance case.
82#[derive(Clone, Copy)]
83pub struct Case {
84    /// A stable name, used in reports.
85    pub name: &'static str,
86    /// Capabilities required (all of them).
87    pub requires: &'static [Requirement],
88    run: fn(&Ctx<'_>) -> Outcome,
89}
90
91impl Debug for Case {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.debug_struct("Case")
94            .field("name", &self.name)
95            .field("requires", &self.requires)
96            .finish()
97    }
98}
99
100/// The result of running the suite on one backend.
101#[derive(Debug, Clone, Default)]
102pub struct Report {
103    /// The label given to [`run`].
104    pub backend: String,
105    /// Names of the cases that passed.
106    pub passed: Vec<String>,
107    /// `(case, reason)` for each case skipped because of a declared capability.
108    pub skipped: Vec<(String, String)>,
109    /// `(case, reason)` for each failure.
110    pub failed: Vec<(String, String)>,
111}
112
113impl Report {
114    /// True if nothing failed. Skips are not failures: they are declared differences.
115    pub fn is_ok(&self) -> bool {
116        self.failed.is_empty()
117    }
118
119    /// Panic with the full report if anything failed. For use in tests.
120    pub fn assert_ok(&self) {
121        assert!(self.is_ok(), "conformance failed:\n{self}");
122    }
123}
124
125impl std::fmt::Display for Report {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        writeln!(
128            f,
129            "conformance[{}]: {} passed, {} skipped, {} failed",
130            self.backend,
131            self.passed.len(),
132            self.skipped.len(),
133            self.failed.len()
134        )?;
135        for (case, why) in &self.skipped {
136            writeln!(f, "  skipped {case}: {why}")?;
137        }
138        for (case, why) in &self.failed {
139            writeln!(f, "  FAILED  {case}: {why}")?;
140        }
141        Ok(())
142    }
143}
144
145/// Options for a run.
146#[derive(Debug, Clone)]
147#[non_exhaustive]
148pub struct Options {
149    /// Poll interval the watch cases ask for. Default 20 ms.
150    pub watch_interval: Duration,
151    /// How long a watch case waits for an expected batch before failing. Default 10 s.
152    pub watch_timeout: Duration,
153}
154
155impl Default for Options {
156    fn default() -> Self {
157        Options {
158            watch_interval: Duration::from_millis(20),
159            watch_timeout: Duration::from_secs(10),
160        }
161    }
162}
163
164type Outcome = Result<(), String>;
165
166/// Run every case against `backend`. `label` names it in the report.
167pub fn run(label: &str, backend: &dyn Backend) -> Report {
168    run_with(label, backend, &Options::default())
169}
170
171/// [`run`] with options.
172pub fn run_with(label: &str, backend: &dyn Backend, options: &Options) -> Report {
173    static NONCE: AtomicU64 = AtomicU64::new(0);
174    let caps = backend.caps();
175    let mut report = Report {
176        backend: label.to_string(),
177        ..Report::default()
178    };
179    for case in CASES {
180        if let Some(reason) = unmet(&caps, case.requires) {
181            report.skipped.push((case.name.to_string(), reason));
182            continue;
183        }
184        let base = if caps.writable {
185            let name = format!(
186                "conf-{:x}-{:x}",
187                std::process::id(),
188                NONCE.fetch_add(1, Ordering::Relaxed)
189            );
190            let base = NsPath::root()
191                .join(&name)
192                .expect("scratch name is inside the grammar");
193            if let Err(e) = backend.write(&base, WriteOp::MakeDir, &[], None) {
194                report.failed.push((
195                    case.name.to_string(),
196                    format!("could not create the scratch directory: {e}"),
197                ));
198                continue;
199            }
200            base
201        } else {
202            NsPath::root()
203        };
204        let ctx = Ctx {
205            backend,
206            base: base.clone(),
207            options: options.clone(),
208        };
209        let outcome = catch_unwind(AssertUnwindSafe(|| (case.run)(&ctx)))
210            .unwrap_or_else(|p| Err(format!("panicked: {}", panic_text(&p))));
211        if caps.writable {
212            remove_tree(backend, &base);
213        }
214        match outcome {
215            Ok(()) => report.passed.push(case.name.to_string()),
216            Err(why) => report.failed.push((case.name.to_string(), why)),
217        }
218    }
219    report
220}
221
222fn panic_text(p: &Box<dyn std::any::Any + Send>) -> String {
223    p.downcast_ref::<&str>()
224        .map(|s| (*s).to_string())
225        .or_else(|| p.downcast_ref::<String>().cloned())
226        .unwrap_or_else(|| "a panic".to_string())
227}
228
229fn unmet(caps: &Caps, requires: &[Requirement]) -> Option<String> {
230    for r in requires {
231        match r {
232            Requirement::Has(c) if !c.present(caps) => {
233                return Some(format!("backend does not declare `{}`", c.name()));
234            }
235            Requirement::Lacks(c) if c.present(caps) => {
236                return Some(format!(
237                    "backend declares `{}`, so there is no missing capability to check",
238                    c.name()
239                ));
240            }
241            _ => {}
242        }
243    }
244    None
245}
246
247/// Best-effort removal of a scratch tree.
248fn remove_tree(backend: &dyn Backend, path: &NsPath) {
249    if let Ok(entries) = backend.walk(path) {
250        for e in entries {
251            if let Some(child) = path.child(&e.name) {
252                if e.kind == Kind::Dir {
253                    remove_tree(backend, &child);
254                } else {
255                    let _ = backend.write(&child, WriteOp::Remove, &[], None);
256                }
257            }
258        }
259    }
260    let _ = backend.write(path, WriteOp::Remove, &[], None);
261}
262
263// ---------------------------------------------------------------------------------------------------------------
264// A mount seen through a Namespace, so the same cases can run through the mount table.
265// ---------------------------------------------------------------------------------------------------------------
266
267/// Presents the subtree of a [`Namespace`] at `base` as a [`Backend`], so [`run`] can exercise the mount table (longest
268/// prefix, error rebasing, path mapping in watches) with exactly the cases a bare backend gets.
269///
270/// Its capabilities are those of the mount covering `base`. Use `ReadWrite` mounts: a `ReadOnly` mount answers
271/// `PermissionDenied` to writes (the namespace's grant), not `Unsupported` (the backend's declaration).
272pub struct ViaNamespace {
273    ns: Namespace,
274    base: NsPath,
275    caps: Caps,
276}
277
278impl ViaNamespace {
279    /// View `ns` at `base`, which must lie under a mount.
280    pub fn new(ns: Namespace, base: NsPath) -> NsResult<Self> {
281        let caps = ns
282            .mounts()
283            .filter(|(point, _, _)| base.starts_with(point))
284            .max_by_key(|(point, _, _)| point.depth())
285            .map(|(_, access, caps)| Caps {
286                writable: caps.writable && access == super::Access::ReadWrite,
287                ..caps
288            })
289            .ok_or_else(|| NsError::at(NsErrorKind::NotFound, &base))?;
290        Ok(ViaNamespace { ns, base, caps })
291    }
292
293    fn up(&self, rel: &NsPath) -> NsResult<NsPath> {
294        rel.rebase(&self.base)
295    }
296
297    fn down(&self, e: NsError) -> NsError {
298        match e.path().and_then(|p| p.strip_prefix(&self.base)) {
299            Some(rel) => NsError::at(e.kind(), &rel),
300            None => NsError::new(e.kind()),
301        }
302    }
303}
304
305impl Backend for ViaNamespace {
306    fn caps(&self) -> Caps {
307        self.caps
308    }
309
310    fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
311        self.ns.walk(&self.up(path)?).map_err(|e| self.down(e))
312    }
313
314    fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
315        self.ns.read(&self.up(path)?, max).map_err(|e| self.down(e))
316    }
317
318    fn stat(&self, path: &NsPath) -> NsResult<Stat> {
319        self.ns.stat(&self.up(path)?).map_err(|e| self.down(e))
320    }
321
322    fn write(
323        &self,
324        path: &NsPath,
325        op: WriteOp,
326        data: &[u8],
327        if_version: Option<&Version>,
328    ) -> NsResult<Version> {
329        let op = match op {
330            WriteOp::RenameWithinMount { to } => WriteOp::RenameWithinMount { to: self.up(&to)? },
331            other => other,
332        };
333        self.ns
334            .write(&self.up(path)?, op, data, if_version)
335            .map_err(|e| self.down(e))
336    }
337
338    fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
339        let base = self.base.clone();
340        let w = self
341            .ns
342            .watch(&self.up(path)?, opts)
343            .map_err(|e| self.down(e))?;
344        Ok(w.map_paths(move |p| p.strip_prefix(&base)))
345    }
346}
347
348// ---------------------------------------------------------------------------------------------------------------
349// Case plumbing
350// ---------------------------------------------------------------------------------------------------------------
351
352struct Ctx<'a> {
353    backend: &'a dyn Backend,
354    base: NsPath,
355    options: Options,
356}
357
358impl Ctx<'_> {
359    fn p(&self, rel: &str) -> NsPath {
360        self.base
361            .join(rel)
362            .expect("case paths are inside the grammar")
363    }
364
365    fn put(&self, rel: &str, data: &[u8]) -> Result<Version, String> {
366        expect(
367            self.backend
368                .write(&self.p(rel), WriteOp::CreateExclusive, data, None),
369            &format!("create {rel}"),
370        )
371    }
372
373    fn mkdir(&self, rel: &str) -> Result<Version, String> {
374        expect(
375            self.backend
376                .write(&self.p(rel), WriteOp::MakeDir, &[], None),
377            &format!("mkdir {rel}"),
378        )
379    }
380
381    fn replace(&self, rel: &str, data: &[u8], v: Option<&Version>) -> NsResult<Version> {
382        self.backend.write(&self.p(rel), WriteOp::Replace, data, v)
383    }
384
385    fn get(&self, rel: &str) -> Result<(Vec<u8>, Version), String> {
386        expect(
387            self.backend.read(&self.p(rel), 1 << 20),
388            &format!("read {rel}"),
389        )
390    }
391
392    fn names(&self, rel: &str) -> Result<Vec<(String, Kind)>, String> {
393        let path = if rel.is_empty() {
394            self.base.clone()
395        } else {
396            self.p(rel)
397        };
398        let entries = expect(self.backend.walk(&path), &format!("walk {rel:?}"))?;
399        Ok(entries.into_iter().map(|e| (e.name, e.kind)).collect())
400    }
401
402    fn watch_opts(&self, recursive: bool) -> WatchOpts {
403        WatchOpts::default()
404            .recursive(recursive)
405            .interval(self.options.watch_interval)
406    }
407}
408
409macro_rules! ensure {
410    ($cond:expr, $($arg:tt)+) => {
411        if !$cond {
412            return Err(format!($($arg)+));
413        }
414    };
415}
416
417fn expect<T>(r: NsResult<T>, what: &str) -> Result<T, String> {
418    r.map_err(|e| format!("{what}: unexpected error: {e}"))
419}
420
421fn refuse<T: Debug>(r: NsResult<T>, kind: NsErrorKind, what: &str) -> Outcome {
422    match r {
423        Ok(v) => Err(format!("{what}: expected {kind:?}, got Ok({v:?})")),
424        Err(e) if e.kind() == kind => Ok(()),
425        Err(e) => Err(format!("{what}: expected {kind:?}, got {:?}", e.kind())),
426    }
427}
428
429fn unsupported<T: Debug>(r: NsResult<T>, what: &str) -> Outcome {
430    match r {
431        Ok(v) => Err(format!(
432            "{what}: backend declares this capability false but returned Ok({v:?})"
433        )),
434        Err(e) if matches!(e.kind(), NsErrorKind::Unsupported(_)) => Ok(()),
435        Err(e) => Err(format!("{what}: expected Unsupported, got {:?}", e.kind())),
436    }
437}
438
439// ---------------------------------------------------------------------------------------------------------------
440// The cases
441// ---------------------------------------------------------------------------------------------------------------
442
443use Cap::{AtomicReplace, ExactIfVersion, OwnerMode, Watch as WatchCap, Writable};
444use Requirement::{Has, Lacks};
445
446const W: &[Requirement] = &[Has(Writable)];
447/// Cases that call `Replace` (to modify a file) need it declared.
448const WR: &[Requirement] = &[Has(Writable), Has(AtomicReplace)];
449const WATCHED: &[Requirement] = &[Has(Writable), Has(WatchCap)];
450const WATCHED_R: &[Requirement] = &[Has(Writable), Has(WatchCap), Has(AtomicReplace)];
451
452macro_rules! case {
453    ($name:literal, $requires:expr, $f:expr) => {
454        Case {
455            name: $name,
456            requires: $requires,
457            run: $f,
458        }
459    };
460}
461
462/// Every case, in the order they run.
463pub const CASES: &[Case] = &[
464    case!("read_missing_is_not_found", &[], read_missing_is_not_found),
465    case!(
466        "read_directory_is_a_directory",
467        &[],
468        read_directory_is_a_directory
469    ),
470    case!("walk_missing_is_not_found", &[], walk_missing_is_not_found),
471    case!("stat_directory", &[], stat_directory),
472    case!(
473        "owner_and_mode_reported",
474        &[Has(OwnerMode)],
475        owner_and_mode_reported
476    ),
477    case!(
478        "owner_and_mode_absent",
479        &[Lacks(OwnerMode)],
480        owner_and_mode_absent
481    ),
482    case!("write_roundtrip", WR, write_roundtrip),
483    case!("read_over_max_is_too_large", W, read_over_max_is_too_large),
484    case!("create_exclusive", W, create_exclusive),
485    case!(
486        "create_needs_a_directory_parent",
487        W,
488        create_needs_a_directory_parent
489    ),
490    case!("make_dir_and_walk", W, make_dir_and_walk),
491    case!(
492        "walk_is_sorted_in_utf8_byte_order",
493        W,
494        walk_is_sorted_in_utf8_byte_order
495    ),
496    case!(
497        "case_collisions_are_refused",
498        WR,
499        case_collisions_are_refused
500    ),
501    case!("replace_semantics", WR, replace_semantics),
502    case!("remove_semantics", W, remove_semantics),
503    case!("rename_within_mount", W, rename_within_mount),
504    case!("if_version_sequence", WR, if_version_sequence),
505    case!(
506        "if_version_is_exact_under_contention",
507        &[Has(Writable), Has(AtomicReplace), Has(ExactIfVersion)],
508        if_version_is_exact_under_contention
509    ),
510    case!(
511        "data_refused_where_none_is_taken",
512        W,
513        data_refused_where_none_is_taken
514    ),
515    case!(
516        "writes_are_unsupported_when_not_writable",
517        &[Lacks(Writable)],
518        writes_are_unsupported
519    ),
520    case!(
521        "replace_is_unsupported_without_atomic_replace",
522        &[Has(Writable), Lacks(AtomicReplace)],
523        replace_unsupported
524    ),
525    case!(
526        "watch_is_unsupported_without_watch",
527        &[Lacks(WatchCap)],
528        watch_unsupported
529    ),
530    case!(
531        "watch_reports_create_modify_remove",
532        WATCHED_R,
533        watch_create_modify_remove
534    ),
535    case!(
536        "watch_reports_replace_and_rename",
537        WATCHED_R,
538        watch_replace_and_rename
539    ),
540    case!(
541        "watch_recursive_and_not",
542        WATCHED_R,
543        watch_recursive_and_not
544    ),
545    case!(
546        "watch_target_must_be_a_directory",
547        WATCHED,
548        watch_target_must_be_a_directory
549    ),
550    case!(
551        "watch_vanished_directory_rescans_and_recovers",
552        WATCHED,
553        watch_vanished_rescans
554    ),
555    case!(
556        "watch_batches_are_sorted_unique_and_numbered",
557        WATCHED,
558        watch_batches_well_formed
559    ),
560    case!("watch_over_cap_becomes_rescan", WATCHED, watch_over_cap),
561    case!("watch_drop_stops_it", WATCHED, watch_drop),
562];
563
564fn read_missing_is_not_found(c: &Ctx<'_>) -> Outcome {
565    refuse(
566        c.backend.read(&c.p("no-such-file"), 10),
567        NsErrorKind::NotFound,
568        "read missing",
569    )?;
570    refuse(
571        c.backend.stat(&c.p("no-such-file")),
572        NsErrorKind::NotFound,
573        "stat missing",
574    )
575}
576
577fn read_directory_is_a_directory(c: &Ctx<'_>) -> Outcome {
578    refuse(
579        c.backend.read(&c.base, 10),
580        NsErrorKind::IsADirectory,
581        "read of a directory",
582    )
583}
584
585fn walk_missing_is_not_found(c: &Ctx<'_>) -> Outcome {
586    refuse(
587        c.backend.walk(&c.p("no-such-dir")),
588        NsErrorKind::NotFound,
589        "walk missing",
590    )
591}
592
593fn stat_directory(c: &Ctx<'_>) -> Outcome {
594    let a = expect(c.backend.stat(&c.base), "stat base")?;
595    ensure!(
596        a.kind == Kind::Dir,
597        "a directory must stat as Dir, got {:?}",
598        a.kind
599    );
600    ensure!(
601        a.size == 0,
602        "a directory's size must be reported as 0, got {}",
603        a.size
604    );
605    let b = expect(c.backend.stat(&c.base), "stat base again")?;
606    ensure!(
607        a.version == b.version,
608        "an unchanged directory must keep its version"
609    );
610    let root = expect(c.backend.stat(&NsPath::root()), "stat root")?;
611    ensure!(root.kind == Kind::Dir, "the root must stat as Dir");
612    Ok(())
613}
614
615fn owner_and_mode_reported(c: &Ctx<'_>) -> Outcome {
616    let s = expect(c.backend.stat(&c.base), "stat base")?;
617    ensure!(
618        s.owner.is_some() && s.mode.is_some(),
619        "owner_mode is declared but owner/mode are missing: {s:?}"
620    );
621    Ok(())
622}
623
624fn owner_and_mode_absent(c: &Ctx<'_>) -> Outcome {
625    let s = expect(c.backend.stat(&c.base), "stat base")?;
626    ensure!(
627        s.owner.is_none() && s.mode.is_none(),
628        "owner_mode is not declared but owner/mode are present: {s:?}"
629    );
630    Ok(())
631}
632
633fn write_roundtrip(c: &Ctx<'_>) -> Outcome {
634    let v = expect(
635        c.replace("a.txt", b"hello", None),
636        "replace creates a missing file",
637    )?;
638    let (bytes, rv) = c.get("a.txt")?;
639    ensure!(bytes == b"hello", "read back {bytes:?}");
640    ensure!(
641        v == rv,
642        "write's version {v:?} must equal the next read's {rv:?}"
643    );
644    let st = expect(c.backend.stat(&c.p("a.txt")), "stat")?;
645    ensure!(st.kind == Kind::File && st.size == 5, "stat says {st:?}");
646    ensure!(st.version == rv, "stat's version must equal read's");
647    let empty = expect(c.replace("empty", b"", None), "replace with nothing")?;
648    let (bytes, rv) = c.get("empty")?;
649    ensure!(bytes.is_empty() && rv == empty, "an empty file round-trips");
650    Ok(())
651}
652
653fn read_over_max_is_too_large(c: &Ctx<'_>) -> Outcome {
654    c.put("ten", b"0123456789")?;
655    let (bytes, _) = expect(c.backend.read(&c.p("ten"), 10), "read at exactly max")?;
656    ensure!(
657        bytes.len() == 10,
658        "reading at exactly max returns the whole file"
659    );
660    refuse(
661        c.backend.read(&c.p("ten"), 9),
662        NsErrorKind::TooLarge,
663        "read over max",
664    )?;
665    refuse(
666        c.backend.read(&c.p("ten"), 0),
667        NsErrorKind::TooLarge,
668        "read with max 0",
669    )
670}
671
672fn create_exclusive(c: &Ctx<'_>) -> Outcome {
673    let v = c.put("x", b"one")?;
674    let st = expect(c.backend.stat(&c.p("x")), "stat")?;
675    ensure!(st.version == v, "create's version must equal stat's");
676    refuse(
677        c.backend
678            .write(&c.p("x"), WriteOp::CreateExclusive, b"two", None),
679        NsErrorKind::AlreadyExists,
680        "second create",
681    )?;
682    let (bytes, _) = c.get("x")?;
683    ensure!(bytes == b"one", "a refused create must not change the file");
684    Ok(())
685}
686
687fn create_needs_a_directory_parent(c: &Ctx<'_>) -> Outcome {
688    refuse(
689        c.backend
690            .write(&c.p("nodir/f"), WriteOp::CreateExclusive, b"x", None),
691        NsErrorKind::NotFound,
692        "create in a missing directory",
693    )?;
694    c.put("file", b"x")?;
695    refuse(
696        c.backend
697            .write(&c.p("file/f"), WriteOp::CreateExclusive, b"x", None),
698        NsErrorKind::NotADirectory,
699        "create under a file",
700    )?;
701    refuse(
702        c.backend.walk(&c.p("file")),
703        NsErrorKind::NotADirectory,
704        "walk of a file",
705    )
706}
707
708fn make_dir_and_walk(c: &Ctx<'_>) -> Outcome {
709    c.mkdir("d")?;
710    c.put("d/inner", b"i")?;
711    c.put("b.txt", b"b")?;
712    c.put("a.txt", b"a")?;
713    let got = c.names("")?;
714    let want = vec![
715        ("a.txt".to_string(), Kind::File),
716        ("b.txt".to_string(), Kind::File),
717        ("d".to_string(), Kind::Dir),
718    ];
719    ensure!(
720        got == want,
721        "walk must be sorted by name with kinds: got {got:?}"
722    );
723    let inner = c.names("d")?;
724    ensure!(
725        inner == vec![("inner".to_string(), Kind::File)],
726        "walk d: {inner:?}"
727    );
728    refuse(
729        c.backend.write(&c.p("d"), WriteOp::MakeDir, &[], None),
730        NsErrorKind::AlreadyExists,
731        "mkdir over a directory",
732    )?;
733    refuse(
734        c.backend.write(&c.p("x/y"), WriteOp::MakeDir, &[], None),
735        NsErrorKind::NotFound,
736        "mkdir without its parent",
737    )
738}
739
740fn walk_is_sorted_in_utf8_byte_order(c: &Ctx<'_>) -> Outcome {
741    // Chosen so that byte order differs from every "friendly" order: upper case before lower, an accented letter after
742    // `z`, a CJK name after that, an astral character last. None of them fold-collides with another.
743    let names = [
744        "zebra",
745        "Zulu",
746        "alpha",
747        "\u{e9}clair",
748        "\u{4e2d}\u{6587}",
749        "\u{1f600}smile",
750        "Beta",
751        "10",
752        "9",
753    ];
754    for n in names {
755        c.put(n, b"x")?;
756    }
757    let got: Vec<String> = c.names("")?.into_iter().map(|(n, _)| n).collect();
758    let mut want: Vec<String> = names.iter().map(|s| (*s).to_string()).collect();
759    want.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
760    ensure!(
761        got == want,
762        "walk must be sorted by name in UTF-8 byte order: got {got:?}, want {want:?}"
763    );
764    Ok(())
765}
766
767fn case_collisions_are_refused(c: &Ctx<'_>) -> Outcome {
768    c.put("Readme.txt", b"1")?;
769    refuse(
770        c.backend
771            .write(&c.p("README.TXT"), WriteOp::CreateExclusive, b"2", None),
772        NsErrorKind::CaseCollision,
773        "create of a case-colliding name",
774    )?;
775    refuse(
776        c.backend
777            .write(&c.p("readme.txt"), WriteOp::Replace, b"2", None),
778        NsErrorKind::CaseCollision,
779        "replace creating a case-colliding name",
780    )?;
781    refuse(
782        c.backend
783            .write(&c.p("ReadMe.Txt"), WriteOp::MakeDir, &[], None),
784        NsErrorKind::CaseCollision,
785        "mkdir of a case-colliding name",
786    )?;
787    c.put("other", b"3")?;
788    refuse(
789        c.backend.write(
790            &c.p("other"),
791            WriteOp::RenameWithinMount {
792                to: c.p("README.txt"),
793            },
794            &[],
795            None,
796        ),
797        NsErrorKind::CaseCollision,
798        "rename onto a case-colliding name",
799    )?;
800    // The exact name is still fine to replace, and `ß` meets `SS` (the fold is Unicode, not ASCII).
801    expect(
802        c.replace("Readme.txt", b"3", None),
803        "replace of the exact existing name",
804    )?;
805    c.put("stra\u{df}e", b"x")?;
806    refuse(
807        c.backend
808            .write(&c.p("STRASSE"), WriteOp::CreateExclusive, b"y", None),
809        NsErrorKind::CaseCollision,
810        "create of a name that folds to an existing one only under Unicode folding",
811    )?;
812    let names = c.names("")?;
813    ensure!(
814        names
815            .iter()
816            .filter(|(n, _)| n.eq_ignore_ascii_case("readme.txt"))
817            .count()
818            == 1,
819        "exactly one readme must exist: {names:?}"
820    );
821    Ok(())
822}
823
824fn replace_semantics(c: &Ctx<'_>) -> Outcome {
825    let v1 = expect(c.replace("f", b"one", None), "first replace")?;
826    let v2 = expect(c.replace("f", b"two!", None), "second replace")?;
827    ensure!(v1 != v2, "a replace must change the version");
828    let (bytes, v) = c.get("f")?;
829    ensure!(
830        bytes == b"two!" && v == v2,
831        "replace content/version: {bytes:?}"
832    );
833    c.mkdir("dir")?;
834    refuse(
835        c.replace("dir", b"x", None),
836        NsErrorKind::IsADirectory,
837        "replace of a directory",
838    )?;
839    refuse(
840        c.replace("nodir/f", b"x", None),
841        NsErrorKind::NotFound,
842        "replace in a missing directory",
843    )?;
844    // Temporary files used to make the replace atomic must never be visible, and every listed name must be addressable.
845    for (name, _) in c.names("")? {
846        ensure!(
847            validate_name(&name).is_ok(),
848            "listing contains a name outside the grammar: {name:?}"
849        );
850    }
851    Ok(())
852}
853
854fn remove_semantics(c: &Ctx<'_>) -> Outcome {
855    let v = c.put("f", b"x")?;
856    let removed = expect(
857        c.backend.write(&c.p("f"), WriteOp::Remove, &[], None),
858        "remove a file",
859    )?;
860    ensure!(removed == v, "remove returns the version the entry had");
861    refuse(
862        c.backend.read(&c.p("f"), 10),
863        NsErrorKind::NotFound,
864        "read after remove",
865    )?;
866    refuse(
867        c.backend.write(&c.p("f"), WriteOp::Remove, &[], None),
868        NsErrorKind::NotFound,
869        "remove of a missing file",
870    )?;
871    c.mkdir("d")?;
872    c.put("d/x", b"x")?;
873    refuse(
874        c.backend.write(&c.p("d"), WriteOp::Remove, &[], None),
875        NsErrorKind::NotEmpty,
876        "remove of a non-empty directory",
877    )?;
878    expect(
879        c.backend.write(&c.p("d/x"), WriteOp::Remove, &[], None),
880        "remove d/x",
881    )?;
882    expect(
883        c.backend.write(&c.p("d"), WriteOp::Remove, &[], None),
884        "remove empty d",
885    )?;
886    // The root cannot be removed (the exact kind is the backend's: a mount root is InvalidInput, a view of a
887    // non-empty subtree is NotEmpty), and it must still be there afterwards.
888    ensure!(
889        c.backend
890            .write(&NsPath::root(), WriteOp::Remove, &[], None)
891            .is_err(),
892        "removing the root must be refused"
893    );
894    expect(
895        c.backend.stat(&NsPath::root()),
896        "stat of the root after a refused remove",
897    )?;
898    Ok(())
899}
900
901fn rename_within_mount(c: &Ctx<'_>) -> Outcome {
902    c.put("a", b"AAA")?;
903    c.put("b", b"BBB")?;
904    expect(
905        c.backend.write(
906            &c.p("a"),
907            WriteOp::RenameWithinMount { to: c.p("c") },
908            &[],
909            None,
910        ),
911        "rename a to c",
912    )?;
913    refuse(
914        c.backend.read(&c.p("a"), 10),
915        NsErrorKind::NotFound,
916        "old name after rename",
917    )?;
918    ensure!(c.get("c")?.0 == b"AAA", "renamed content");
919    refuse(
920        c.backend.write(
921            &c.p("c"),
922            WriteOp::RenameWithinMount { to: c.p("b") },
923            &[],
924            None,
925        ),
926        NsErrorKind::AlreadyExists,
927        "rename onto an existing name",
928    )?;
929    ensure!(
930        c.get("b")?.0 == b"BBB",
931        "a refused rename must not touch the destination"
932    );
933    refuse(
934        c.backend.write(
935            &c.p("zz"),
936            WriteOp::RenameWithinMount { to: c.p("yy") },
937            &[],
938            None,
939        ),
940        NsErrorKind::NotFound,
941        "rename of a missing source",
942    )?;
943    refuse(
944        c.backend.write(
945            &c.p("c"),
946            WriteOp::RenameWithinMount { to: c.p("nodir/c") },
947            &[],
948            None,
949        ),
950        NsErrorKind::NotFound,
951        "rename into a missing directory",
952    )?;
953    // Directories move with their contents, across directories.
954    c.mkdir("d1")?;
955    c.mkdir("d2")?;
956    c.put("d1/f", b"F")?;
957    expect(
958        c.backend.write(
959            &c.p("d1"),
960            WriteOp::RenameWithinMount {
961                to: c.p("d2/moved"),
962            },
963            &[],
964            None,
965        ),
966        "rename a directory",
967    )?;
968    ensure!(
969        c.get("d2/moved/f")?.0 == b"F",
970        "directory contents moved with it"
971    );
972    refuse(
973        c.backend.write(
974            &c.p("d2"),
975            WriteOp::RenameWithinMount {
976                to: c.p("d2/moved/inside"),
977            },
978            &[],
979            None,
980        ),
981        NsErrorKind::InvalidInput(InputReason::MoveIntoSelf),
982        "rename of a directory into itself",
983    )?;
984    // Onto itself is not a no-op: the name is taken.
985    refuse(
986        c.backend.write(
987            &c.p("c"),
988            WriteOp::RenameWithinMount { to: c.p("c") },
989            &[],
990            None,
991        ),
992        NsErrorKind::AlreadyExists,
993        "rename of an entry onto itself",
994    )?;
995    // A rename that changes only the case of one's own name is allowed.
996    expect(
997        c.backend.write(
998            &c.p("c"),
999            WriteOp::RenameWithinMount { to: c.p("C") },
1000            &[],
1001            None,
1002        ),
1003        "case-only rename of one's own name",
1004    )?;
1005    ensure!(c.get("C")?.0 == b"AAA", "case-only rename keeps content");
1006    Ok(())
1007}
1008
1009fn if_version_sequence(c: &Ctx<'_>) -> Outcome {
1010    let v1 = c.put("f", b"1")?;
1011    let v2 = expect(
1012        c.replace("f", b"2", Some(&v1)),
1013        "replace with the current version",
1014    )?;
1015    ensure!(v1 != v2, "a replace changes the version");
1016    refuse(
1017        c.replace("f", b"3", Some(&v1)),
1018        NsErrorKind::VersionMismatch,
1019        "replace with a stale version",
1020    )?;
1021    ensure!(
1022        c.get("f")?.0 == b"2",
1023        "a refused replace must not change the file"
1024    );
1025    refuse(
1026        c.backend.write(&c.p("f"), WriteOp::Remove, &[], Some(&v1)),
1027        NsErrorKind::VersionMismatch,
1028        "remove with a stale version",
1029    )?;
1030    refuse(
1031        c.backend.write(
1032            &c.p("f"),
1033            WriteOp::RenameWithinMount { to: c.p("g") },
1034            &[],
1035            Some(&v1),
1036        ),
1037        NsErrorKind::VersionMismatch,
1038        "rename with a stale version",
1039    )?;
1040    refuse(
1041        c.replace("missing", b"x", Some(&v1)),
1042        NsErrorKind::NotFound,
1043        "versioned replace of a missing file",
1044    )?;
1045    refuse(
1046        c.backend
1047            .write(&c.p("new"), WriteOp::CreateExclusive, b"x", Some(&v1)),
1048        NsErrorKind::InvalidInput(InputReason::VersionOnCreate),
1049        "versioned create",
1050    )?;
1051    expect(
1052        c.backend.write(&c.p("f"), WriteOp::Remove, &[], Some(&v2)),
1053        "remove with the current version",
1054    )?;
1055    Ok(())
1056}
1057
1058fn if_version_is_exact_under_contention(c: &Ctx<'_>) -> Outcome {
1059    const RACERS: usize = 8;
1060    let v0 = c.put("f", b"start")?;
1061    let barrier = Barrier::new(RACERS);
1062    let results: Vec<NsResult<Version>> = std::thread::scope(|s| {
1063        let handles: Vec<_> = (0..RACERS)
1064            .map(|i| {
1065                let (barrier, v0) = (&barrier, &v0);
1066                s.spawn(move || {
1067                    barrier.wait();
1068                    c.replace("f", format!("racer {i}").as_bytes(), Some(v0))
1069                })
1070            })
1071            .collect();
1072        handles
1073            .into_iter()
1074            .map(|h| h.join().expect("racer panicked"))
1075            .collect()
1076    });
1077    let winners = results.iter().filter(|r| r.is_ok()).count();
1078    ensure!(
1079        winners == 1,
1080        "exact_if_version is declared, so exactly one racer may win; {winners} did"
1081    );
1082    for r in results.iter().filter_map(|r| r.as_ref().err()) {
1083        ensure!(
1084            r.kind() == NsErrorKind::VersionMismatch,
1085            "a loser must see VersionMismatch, saw {:?}",
1086            r.kind()
1087        );
1088    }
1089    Ok(())
1090}
1091
1092fn data_refused_where_none_is_taken(c: &Ctx<'_>) -> Outcome {
1093    c.put("f", b"x")?;
1094    let is_invalid = |r: NsResult<Version>, what: &str| match r {
1095        Err(e) if matches!(e.kind(), NsErrorKind::InvalidInput(_)) => Ok(()),
1096        other => Err(format!("{what}: expected InvalidInput, got {other:?}")),
1097    };
1098    is_invalid(
1099        c.backend.write(&c.p("f"), WriteOp::Remove, b"data", None),
1100        "remove with data",
1101    )?;
1102    is_invalid(
1103        c.backend.write(&c.p("d"), WriteOp::MakeDir, b"data", None),
1104        "mkdir with data",
1105    )?;
1106    is_invalid(
1107        c.backend.write(
1108            &c.p("f"),
1109            WriteOp::RenameWithinMount { to: c.p("g") },
1110            b"data",
1111            None,
1112        ),
1113        "rename with data",
1114    )?;
1115    ensure!(
1116        c.get("f")?.0 == b"x",
1117        "a refused operation must not change anything"
1118    );
1119    Ok(())
1120}
1121
1122fn writes_are_unsupported(c: &Ctx<'_>) -> Outcome {
1123    let p = c.p("f");
1124    unsupported(
1125        c.backend.write(&p, WriteOp::CreateExclusive, b"x", None),
1126        "create",
1127    )?;
1128    unsupported(c.backend.write(&p, WriteOp::Replace, b"x", None), "replace")?;
1129    unsupported(c.backend.write(&p, WriteOp::Remove, &[], None), "remove")?;
1130    unsupported(c.backend.write(&p, WriteOp::MakeDir, &[], None), "mkdir")?;
1131    unsupported(
1132        c.backend
1133            .write(&p, WriteOp::RenameWithinMount { to: c.p("g") }, &[], None),
1134        "rename",
1135    )?;
1136    // Reads must still work.
1137    expect(c.backend.walk(&NsPath::root()), "walk of a read-only mount")?;
1138    Ok(())
1139}
1140
1141fn replace_unsupported(c: &Ctx<'_>) -> Outcome {
1142    unsupported(c.replace("f", b"x", None), "replace")?;
1143    c.put("g", b"x")?;
1144    Ok(())
1145}
1146
1147fn watch_unsupported(c: &Ctx<'_>) -> Outcome {
1148    unsupported(c.backend.watch(&c.base, WatchOpts::default()), "watch")
1149}
1150
1151// --- watch helpers ---------------------------------------------------------------------------------------------
1152
1153struct Watching {
1154    watch: Watch,
1155    cursor: WatchCursor,
1156    seen: Vec<WatchBatch>,
1157    unexpected_rescan: bool,
1158    timeout: Duration,
1159}
1160
1161impl Watching {
1162    fn start(c: &Ctx<'_>, rel: &str, recursive: bool) -> Result<Self, String> {
1163        let path = if rel.is_empty() {
1164            c.base.clone()
1165        } else {
1166            c.p(rel)
1167        };
1168        let watch = expect(c.backend.watch(&path, c.watch_opts(recursive)), "watch")?;
1169        Ok(Watching {
1170            watch,
1171            cursor: WatchCursor::new(),
1172            seen: Vec::new(),
1173            unexpected_rescan: false,
1174            timeout: c.options.watch_timeout,
1175        })
1176    }
1177
1178    /// Receive batches until one satisfies `pred`; returns an error on timeout.
1179    fn wait_for(
1180        &mut self,
1181        what: &str,
1182        pred: impl Fn(&WatchBatch) -> bool,
1183    ) -> Result<WatchBatch, String> {
1184        let deadline = Instant::now() + self.timeout;
1185        loop {
1186            let left = deadline.saturating_duration_since(Instant::now());
1187            if left.is_zero() {
1188                return Err(format!("timed out waiting for {what}; saw {:?}", self.seen));
1189            }
1190            match self.watch.recv_timeout(left) {
1191                Ok(b) => {
1192                    if self.cursor.observe(&b) {
1193                        self.unexpected_rescan |= !pred(&b);
1194                    }
1195                    self.seen.push(b.clone());
1196                    if pred(&b) {
1197                        return Ok(b);
1198                    }
1199                }
1200                Err(_) => return Err(format!("timed out waiting for {what}; saw {:?}", self.seen)),
1201            }
1202        }
1203    }
1204
1205    fn wait_for_path(&mut self, path: &NsPath) -> Result<WatchBatch, String> {
1206        let want = path.clone();
1207        self.wait_for(&format!("a change to {path}"), move |b| {
1208            !b.rescan && b.changed.contains(&want)
1209        })
1210    }
1211
1212    fn ever_reported(&self, path: &NsPath) -> bool {
1213        self.seen.iter().any(|b| b.changed.contains(path))
1214    }
1215}
1216
1217fn watch_create_modify_remove(c: &Ctx<'_>) -> Outcome {
1218    let mut w = Watching::start(c, "", false)?;
1219    let f = c.p("f");
1220    c.put("f", b"1")?;
1221    w.wait_for_path(&f).map_err(|e| format!("create: {e}"))?;
1222    expect(c.replace("f", b"22", None), "modify")?;
1223    w.wait_for_path(&f).map_err(|e| format!("modify: {e}"))?;
1224    expect(c.backend.write(&f, WriteOp::Remove, &[], None), "remove")?;
1225    w.wait_for_path(&f).map_err(|e| format!("remove: {e}"))?;
1226    ensure!(
1227        !w.unexpected_rescan,
1228        "an ordinary run of changes must not look like lost events: {:?}",
1229        w.seen
1230    );
1231    Ok(())
1232}
1233
1234fn watch_replace_and_rename(c: &Ctx<'_>) -> Outcome {
1235    c.put("doc", b"v1")?;
1236    let mut w = Watching::start(c, "", false)?;
1237    // The editor pattern: the file is replaced atomically, its identity changes under the same name.
1238    let doc = c.p("doc");
1239    expect(c.replace("doc", b"v2 (replaced)", None), "replace")?;
1240    w.wait_for_path(&doc)
1241        .map_err(|e| format!("replace of an existing file: {e}"))?;
1242    expect(
1243        c.backend.write(
1244            &doc,
1245            WriteOp::RenameWithinMount { to: c.p("moved") },
1246            &[],
1247            None,
1248        ),
1249        "rename",
1250    )?;
1251    let (from, to) = (doc, c.p("moved"));
1252    w.wait_for(&format!("both {from} and {to}"), |b| {
1253        b.changed.contains(&from) && b.changed.contains(&to)
1254    })
1255    .or_else(|first| {
1256        // A polling backend might split the two sides across polls only if the rename straddled one; accept both
1257        // arriving, in either order, across batches.
1258        if w.ever_reported(&from) && w.ever_reported(&to) {
1259            Ok(WatchBatch::new(0, 0, vec![], false))
1260        } else {
1261            Err(first)
1262        }
1263    })
1264    .map_err(|e| format!("rename: {e}"))?;
1265    Ok(())
1266}
1267
1268fn watch_recursive_and_not(c: &Ctx<'_>) -> Outcome {
1269    c.mkdir("sub")?;
1270    let deep = c.p("sub/deep");
1271    {
1272        let mut shallow = Watching::start(c, "", false)?;
1273        c.put("sub/deep", b"x")?;
1274        let sentinel = c.p("sentinel");
1275        c.put("sentinel", b"x")?;
1276        shallow.wait_for_path(&sentinel)?;
1277        ensure!(
1278            !shallow.ever_reported(&deep),
1279            "a non-recursive watch must not report grandchildren: {:?}",
1280            shallow.seen
1281        );
1282    }
1283    let mut deep_watch = Watching::start(c, "", true)?;
1284    expect(c.replace("sub/deep", b"changed", None), "modify deep")?;
1285    deep_watch
1286        .wait_for_path(&deep)
1287        .map_err(|e| format!("a recursive watch must report a nested change: {e}"))?;
1288    Ok(())
1289}
1290
1291fn watch_target_must_be_a_directory(c: &Ctx<'_>) -> Outcome {
1292    c.put("file", b"x")?;
1293    refuse(
1294        c.backend.watch(&c.p("file"), c.watch_opts(false)),
1295        NsErrorKind::NotADirectory,
1296        "watch of a file",
1297    )?;
1298    refuse(
1299        c.backend.watch(&c.p("nothing"), c.watch_opts(false)),
1300        NsErrorKind::NotFound,
1301        "watch of a missing path",
1302    )
1303}
1304
1305fn watch_vanished_rescans(c: &Ctx<'_>) -> Outcome {
1306    c.mkdir("d")?;
1307    let d = c.p("d");
1308    let mut w = Watching::start(c, "d", false)?;
1309    expect(
1310        c.backend.write(&d, WriteOp::Remove, &[], None),
1311        "remove the watched directory",
1312    )?;
1313    let gone = w.wait_for("a rescan after the directory vanished", |b| b.rescan)?;
1314    ensure!(gone.changed.is_empty(), "a rescan batch carries no paths");
1315    c.mkdir("d")?;
1316    w.wait_for("a rescan when the directory returned", |b| b.rescan)?;
1317    c.put("d/back", b"x")?;
1318    w.wait_for_path(&c.p("d/back"))
1319        .map_err(|e| format!("the watch must keep working after the directory returns: {e}"))?;
1320    Ok(())
1321}
1322
1323fn watch_batches_well_formed(c: &Ctx<'_>) -> Outcome {
1324    let mut w = Watching::start(c, "", false)?;
1325    for name in ["z", "m", "a", "k"] {
1326        c.put(name, b"x")?;
1327    }
1328    let last = c.p("k");
1329    w.wait_for_path(&last)?;
1330    let mut paths_seen = 0;
1331    for b in &w.seen {
1332        let mut sorted = b.changed.clone();
1333        sorted.sort();
1334        sorted.dedup();
1335        ensure!(
1336            sorted == b.changed,
1337            "changed must be sorted and unique: {:?}",
1338            b.changed
1339        );
1340        ensure!(
1341            b.changed.iter().all(|p| p.starts_with(&c.base)),
1342            "paths must be in the backend's namespace: {:?}",
1343            b.changed
1344        );
1345        paths_seen += b.changed.len();
1346    }
1347    ensure!(
1348        paths_seen >= 4,
1349        "all four creates must be reported, saw {paths_seen}"
1350    );
1351    let epoch = w.seen[0].epoch;
1352    ensure!(
1353        w.seen.iter().all(|b| b.epoch == epoch),
1354        "one watch has one epoch"
1355    );
1356    ensure!(
1357        w.seen
1358            .iter()
1359            .enumerate()
1360            .all(|(i, b)| b.generation == i as u64 + 1),
1361        "generation must start at 1 and rise by one: {:?}",
1362        w.seen.iter().map(|b| b.generation).collect::<Vec<_>>()
1363    );
1364    let other = Watching::start(c, "", false)?;
1365    c.put("again", b"x")?;
1366    let mut other = other;
1367    let first_of_other = other.wait_for_path(&c.p("again"))?;
1368    ensure!(
1369        first_of_other.epoch != epoch,
1370        "two watches must not share an epoch"
1371    );
1372    Ok(())
1373}
1374
1375fn watch_over_cap(c: &Ctx<'_>) -> Outcome {
1376    c.put("one", b"x")?;
1377    let opts = c.watch_opts(false).max_entries(1);
1378    let watch = expect(c.backend.watch(&c.base, opts), "watch with a cap of 1")?;
1379    // A rename changes two paths at once, which is over a cap of 1.
1380    expect(
1381        c.backend.write(
1382            &c.p("one"),
1383            WriteOp::RenameWithinMount { to: c.p("two") },
1384            &[],
1385            None,
1386        ),
1387        "rename",
1388    )?;
1389    let deadline = Instant::now() + c.options.watch_timeout;
1390    loop {
1391        let left = deadline.saturating_duration_since(Instant::now());
1392        let b = watch
1393            .recv_timeout(left)
1394            .map_err(|_| "timed out waiting for the over-cap rescan".to_string())?;
1395        if b.rescan {
1396            ensure!(
1397                b.changed.is_empty(),
1398                "past the cap the batch must be rescan with no paths, got {:?}",
1399                b.changed
1400            );
1401            return Ok(());
1402        }
1403        ensure!(
1404            b.changed.len() <= 1,
1405            "a batch exceeded max_entries without becoming a rescan: {:?}",
1406            b.changed
1407        );
1408    }
1409}
1410
1411fn watch_drop(c: &Ctx<'_>) -> Outcome {
1412    let opts = c.watch_opts(false).interval(Duration::from_secs(30));
1413    let watch = expect(c.backend.watch(&c.base, opts), "watch with a long interval")?;
1414    // Drop on its own thread under a deadline: a watch that never signals its producer to stop would make `Drop` wait
1415    // forever, and a regression must FAIL here, not hang the run.
1416    let started = Instant::now();
1417    let (done_tx, done_rx) = std::sync::mpsc::channel();
1418    std::thread::spawn(move || {
1419        drop(watch);
1420        let _ = done_tx.send(());
1421    });
1422    ensure!(
1423        done_rx.recv_timeout(Duration::from_secs(5)).is_ok(),
1424        "dropping a watch must stop it at once, not wait out its interval or hang (gave up after {:?})",
1425        started.elapsed()
1426    );
1427    // The backend must carry on normally after a watch is gone.
1428    c.put("after", b"x")?;
1429    Ok(())
1430}
1431
1432#[cfg(test)]
1433mod tests {
1434    use std::sync::Arc;
1435
1436    use super::*;
1437    use crate::ns::{Access, HostDir, Memory, MemoryOptions};
1438
1439    fn summary(r: &Report) -> String {
1440        format!("{r}")
1441    }
1442
1443    #[test]
1444    fn memory_passes_every_case() {
1445        let r = run("memory", &Memory::new());
1446        r.assert_ok();
1447        let skipped: Vec<_> = r.skipped.iter().map(|(c, _)| c.as_str()).collect();
1448        assert_eq!(
1449            skipped,
1450            [
1451                "owner_and_mode_reported",
1452                "writes_are_unsupported_when_not_writable",
1453                "replace_is_unsupported_without_atomic_replace",
1454                "watch_is_unsupported_without_watch"
1455            ],
1456            "{}",
1457            summary(&r)
1458        );
1459    }
1460
1461    #[test]
1462    fn host_dir_passes_every_case() {
1463        let tmp = tempfile::tempdir().unwrap();
1464        let hd = HostDir::open_ambient(tmp.path()).unwrap();
1465        let r = run("host-dir", &hd);
1466        r.assert_ok();
1467        // HostDir declares inexact versions, so the contention case is reported as skipped, not silently absent.
1468        assert!(r
1469            .skipped
1470            .iter()
1471            .any(|(c, why)| c == "if_version_is_exact_under_contention"
1472                && why.contains("exact_if_version")));
1473        assert!(r.passed.len() >= 24, "{}", summary(&r));
1474    }
1475
1476    #[test]
1477    fn read_only_memory_proves_unsupported() {
1478        let m = Memory::with_options(MemoryOptions {
1479            writable: false,
1480            ..MemoryOptions::default()
1481        });
1482        m.preload(&NsPath::parse("/seed/file").unwrap(), b"x")
1483            .unwrap();
1484        let r = run("memory-read-only", &m);
1485        r.assert_ok();
1486        assert!(
1487            r.passed
1488                .iter()
1489                .any(|c| c == "writes_are_unsupported_when_not_writable"),
1490            "{}",
1491            summary(&r)
1492        );
1493        assert!(r.skipped.iter().any(|(c, _)| c == "write_roundtrip"));
1494    }
1495
1496    #[test]
1497    fn memory_without_atomic_replace_or_watch_proves_unsupported() {
1498        let m = Memory::with_options(MemoryOptions {
1499            atomic_replace: false,
1500            watch: false,
1501            ..MemoryOptions::default()
1502        });
1503        let r = run("memory-restricted", &m);
1504        r.assert_ok();
1505        for case in [
1506            "replace_is_unsupported_without_atomic_replace",
1507            "watch_is_unsupported_without_watch",
1508        ] {
1509            assert!(
1510                r.passed.iter().any(|c| c == case),
1511                "{case} must run and pass: {}",
1512                summary(&r)
1513            );
1514        }
1515        assert!(r
1516            .skipped
1517            .iter()
1518            .any(|(c, _)| c == "watch_reports_create_modify_remove"));
1519        assert!(r.skipped.iter().any(|(c, _)| c == "replace_semantics"));
1520    }
1521
1522    #[test]
1523    fn two_mount_namespace_passes_every_case_on_both_mounts() {
1524        let tmp = tempfile::tempdir().unwrap();
1525        let ns = Namespace::builder()
1526            .mount(
1527                NsPath::parse("/mem").unwrap(),
1528                Arc::new(Memory::new()),
1529                Access::ReadWrite,
1530            )
1531            .mount(
1532                NsPath::parse("/host").unwrap(),
1533                Arc::new(HostDir::open_ambient(tmp.path()).unwrap()),
1534                Access::ReadWrite,
1535            )
1536            .build()
1537            .unwrap();
1538        for at in ["/mem", "/host"] {
1539            // View the mount root itself, and a subdirectory of it (so the prefix mapping is exercised).
1540            let root_view = ViaNamespace::new(ns.clone(), NsPath::parse(at).unwrap()).unwrap();
1541            run(&format!("namespace:{at}"), &root_view).assert_ok();
1542            let sub = NsPath::parse(at).unwrap().join("view").unwrap();
1543            ns.write(&sub, WriteOp::MakeDir, &[], None).unwrap();
1544            let sub_view = ViaNamespace::new(ns.clone(), sub).unwrap();
1545            run(&format!("namespace:{at}/view"), &sub_view).assert_ok();
1546        }
1547    }
1548}