Skip to main content

common/
cmp.rs

1use anyhow::{Context, Result};
2use async_recursion::async_recursion;
3use enum_map::{Enum, EnumMap};
4use tokio::io::AsyncWriteExt;
5use tracing::instrument;
6
7use crate::copy::is_file_type_same;
8use crate::filecmp;
9use crate::progress;
10
11#[derive(Copy, Clone, Debug, Enum)]
12pub enum CompareResult {
13    Same,
14    Different,
15    SrcMissing, // object missing in src but present in dst
16    DstMissing, // same as above but flipped
17}
18
19#[derive(Copy, Clone, Debug, Enum)]
20pub enum ObjType {
21    File,
22    Dir,
23    Symlink,
24    Other, // sockets, block devices, character devices, FIFOs, etc.
25}
26
27pub type ObjSettings = EnumMap<ObjType, filecmp::MetadataCmpSettings>;
28
29#[derive(Debug, Clone)]
30pub struct Settings {
31    pub compare: ObjSettings,
32    pub fail_early: bool,
33    pub exit_early: bool,
34    pub expand_missing: bool,
35    pub filter: Option<crate::filter::FilterSettings>,
36}
37
38pub type Mismatch = EnumMap<ObjType, EnumMap<CompareResult, u64>>;
39
40/// Count of skipped items per object type
41pub type Skipped = EnumMap<ObjType, u64>;
42
43/// Output format for comparison results and summary.
44#[derive(Copy, Clone, Debug, Default, clap::ValueEnum)]
45pub enum OutputFormat {
46    /// JSON output (NDJSON for differences, JSON object for summary)
47    #[default]
48    Json,
49    /// Human-readable text output (legacy format)
50    Text,
51}
52
53fn compare_result_name(cr: CompareResult) -> &'static str {
54    match cr {
55        CompareResult::Same => "same",
56        CompareResult::Different => "different",
57        CompareResult::SrcMissing => "src_missing",
58        CompareResult::DstMissing => "dst_missing",
59    }
60}
61
62fn obj_type_name(ot: ObjType) -> &'static str {
63    match ot {
64        ObjType::File => "file",
65        ObjType::Dir => "dir",
66        ObjType::Symlink => "symlink",
67        ObjType::Other => "other",
68    }
69}
70
71/// Encodes a path as a JSON-safe string that is round-trippable for arbitrary
72/// Unix paths. Literal backslashes are escaped as `\\`, and non-UTF-8 bytes
73/// are escaped as `\xHH`. To decode, first parse the JSON string, then scan
74/// left-to-right: `\\` → literal `\`, `\xHH` → raw byte, all other characters
75/// are literal UTF-8.
76fn path_to_json_string(path: &std::path::Path) -> String {
77    use std::os::unix::ffi::OsStrExt;
78    let bytes = path.as_os_str().as_bytes();
79    let mut out = String::with_capacity(bytes.len());
80    for chunk in bytes.utf8_chunks() {
81        for c in chunk.valid().chars() {
82            if c == '\\' {
83                out.push_str("\\\\");
84            } else {
85                out.push(c);
86            }
87        }
88        for &b in chunk.invalid() {
89            use std::fmt::Write;
90            write!(out, "\\x{b:02x}").unwrap();
91        }
92    }
93    out
94}
95
96#[derive(Default)]
97pub struct Summary {
98    pub mismatch: Mismatch,
99    pub skipped: Skipped,
100    /// Total size of regular files compared on the source side, in bytes.
101    pub src_bytes: u64,
102    /// Total size of regular files compared on the destination side, in bytes.
103    pub dst_bytes: u64,
104}
105
106impl std::ops::Add for Summary {
107    type Output = Self;
108    fn add(self, other: Self) -> Self {
109        let mut mismatch = self.mismatch;
110        for (obj_type, &cmp_res_map) in &other.mismatch {
111            for (cmp_res, &count) in &cmp_res_map {
112                mismatch[obj_type][cmp_res] += count;
113            }
114        }
115        let mut skipped = self.skipped;
116        for (obj_type, &count) in &other.skipped {
117            skipped[obj_type] += count;
118        }
119        Self {
120            mismatch,
121            skipped,
122            src_bytes: self.src_bytes + other.src_bytes,
123            dst_bytes: self.dst_bytes + other.dst_bytes,
124        }
125    }
126}
127
128impl std::fmt::Display for Summary {
129    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
130        writeln!(
131            f,
132            "src size (compared): {}",
133            bytesize::ByteSize(self.src_bytes)
134        )?;
135        writeln!(
136            f,
137            "dst size (compared): {}",
138            bytesize::ByteSize(self.dst_bytes)
139        )?;
140        for (obj_type, &cmp_res_map) in &self.mismatch {
141            for (cmp_res, &count) in &cmp_res_map {
142                writeln!(f, "{obj_type:?} {cmp_res:?}: {count}")?;
143            }
144        }
145        for (obj_type, &count) in &self.skipped {
146            if count > 0 {
147                writeln!(f, "{obj_type:?} Skipped: {count}")?;
148            }
149        }
150        Ok(())
151    }
152}
153
154/// Wraps a [`Summary`] with an [`OutputFormat`] so that [`Display`](std::fmt::Display)
155/// renders either human-readable text or JSON.
156pub struct FormattedSummary {
157    pub summary: Summary,
158    pub format: OutputFormat,
159}
160
161impl std::fmt::Display for FormattedSummary {
162    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
163        match self.format {
164            OutputFormat::Text => write!(f, "{}", self.summary),
165            OutputFormat::Json => {
166                let mut mismatch = serde_json::Map::new();
167                for (obj_type, &cmp_res_map) in &self.summary.mismatch {
168                    let mut counts = serde_json::Map::new();
169                    for (cmp_res, &count) in &cmp_res_map {
170                        counts.insert(
171                            compare_result_name(cmp_res).to_string(),
172                            serde_json::Value::Number(count.into()),
173                        );
174                    }
175                    mismatch.insert(
176                        obj_type_name(obj_type).to_string(),
177                        serde_json::Value::Object(counts),
178                    );
179                }
180                let mut skipped = serde_json::Map::new();
181                for (obj_type, &count) in &self.summary.skipped {
182                    if count > 0 {
183                        skipped.insert(
184                            obj_type_name(obj_type).to_string(),
185                            serde_json::Value::Number(count.into()),
186                        );
187                    }
188                }
189                let stats = crate::collect_runtime_stats();
190                let walltime = crate::get_progress().get_duration();
191                let obj = serde_json::json!({
192                    "src_bytes": self.summary.src_bytes,
193                    "dst_bytes": self.summary.dst_bytes,
194                    "mismatch": serde_json::Value::Object(mismatch),
195                    "skipped": serde_json::Value::Object(skipped),
196                    "walltime_ms": walltime.as_millis() as u64,
197                    "cpu_time_user_ms": stats.cpu_time_user_ms,
198                    "cpu_time_kernel_ms": stats.cpu_time_kernel_ms,
199                    "peak_rss_bytes": stats.peak_rss_bytes,
200                });
201                write!(f, "{obj}")
202            }
203        }
204    }
205}
206
207#[derive(Clone)]
208pub struct LogWriter {
209    file: Option<std::sync::Arc<tokio::sync::Mutex<tokio::io::BufWriter<tokio::fs::File>>>>,
210    stdout: Option<std::sync::Arc<tokio::sync::Mutex<tokio::io::BufWriter<tokio::io::Stdout>>>>,
211    format: OutputFormat,
212}
213
214impl std::fmt::Debug for LogWriter {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        f.debug_struct("LogWriter")
217            .field("file", &self.file.is_some())
218            .field("stdout", &self.stdout.is_some())
219            .field("format", &self.format)
220            .finish()
221    }
222}
223
224impl LogWriter {
225    /// Creates a new LogWriter.
226    ///
227    /// If `log_path_opt` is provided, output goes to that file.
228    /// Otherwise, if `use_stdout` is true, output goes to stdout.
229    /// If both are false/None, no output is produced.
230    pub async fn new(
231        log_path_opt: Option<&std::path::Path>,
232        use_stdout: bool,
233        format: OutputFormat,
234    ) -> Result<Self> {
235        if let Some(log_path) = log_path_opt {
236            let log_file = tokio::fs::OpenOptions::new()
237                .write(true)
238                .create_new(true)
239                .open(log_path)
240                .await
241                .with_context(|| format!("Failed to open log file: {log_path:?}"))?;
242            let log =
243                std::sync::Arc::new(tokio::sync::Mutex::new(tokio::io::BufWriter::new(log_file)));
244            Ok(Self {
245                file: Some(log),
246                stdout: None,
247                format,
248            })
249        } else if use_stdout {
250            Ok(Self {
251                file: None,
252                stdout: Some(std::sync::Arc::new(tokio::sync::Mutex::new(
253                    tokio::io::BufWriter::new(tokio::io::stdout()),
254                ))),
255                format,
256            })
257        } else {
258            Ok(Self {
259                file: None,
260                stdout: None,
261                format,
262            })
263        }
264    }
265    /// Creates a silent LogWriter that produces no output, using the default format.
266    /// Convenience constructor primarily for tests.
267    pub async fn silent() -> Result<Self> {
268        Self::new(None, false, OutputFormat::default()).await
269    }
270
271    pub async fn log_mismatch(
272        &self,
273        cmp_result: CompareResult,
274        src_obj_type: Option<ObjType>,
275        src: &std::path::Path,
276        dst_obj_type: Option<ObjType>,
277        dst: &std::path::Path,
278    ) -> Result<()> {
279        let msg = match self.format {
280            OutputFormat::Text => {
281                format!(
282                    "[{cmp_result:?}]\n\t[{src_obj_type:?}]\t{src:?}\n\t[{dst_obj_type:?}]\t{dst:?}\n"
283                )
284            }
285            OutputFormat::Json => {
286                let src_type_val = match src_obj_type {
287                    Some(ot) => serde_json::Value::String(obj_type_name(ot).to_string()),
288                    None => serde_json::Value::Null,
289                };
290                let dst_type_val = match dst_obj_type {
291                    Some(ot) => serde_json::Value::String(obj_type_name(ot).to_string()),
292                    None => serde_json::Value::Null,
293                };
294                let obj = serde_json::json!({
295                    "result": compare_result_name(cmp_result),
296                    "src_type": src_type_val,
297                    "src": path_to_json_string(src),
298                    "dst_type": dst_type_val,
299                    "dst": path_to_json_string(dst),
300                });
301                format!("{obj}\n")
302            }
303        };
304        self.write(&msg).await
305    }
306
307    async fn write(&self, msg: &str) -> Result<()> {
308        if let Some(log) = &self.file {
309            let mut log = log.lock().await;
310            log.write_all(msg.as_bytes())
311                .await
312                .context("Failed to write to log file")?;
313        }
314        if let Some(stdout) = &self.stdout {
315            let mut stdout = stdout.lock().await;
316            stdout
317                .write_all(msg.as_bytes())
318                .await
319                .context("Failed to write to stdout")?;
320        }
321        Ok(())
322    }
323
324    pub async fn flush(&self) -> Result<()> {
325        if let Some(log) = &self.file {
326            let mut log = log.lock().await;
327            log.flush().await.context("Failed to flush log file")?;
328        }
329        if let Some(stdout) = &self.stdout {
330            let mut stdout = stdout.lock().await;
331            stdout.flush().await.context("Failed to flush stdout")?;
332        }
333        Ok(())
334    }
335}
336
337fn obj_type(metadata: &std::fs::Metadata) -> ObjType {
338    if metadata.is_file() {
339        ObjType::File
340    } else if metadata.is_dir() {
341        ObjType::Dir
342    } else if metadata.is_symlink() {
343        ObjType::Symlink
344    } else {
345        // sockets, block devices, character devices, FIFOs, etc.
346        ObjType::Other
347    }
348}
349
350/// Public entry point for compare operations.
351/// Internally delegates to cmp_internal with source_root/dest_root tracking for proper filter matching.
352#[instrument(skip(prog_track))]
353pub async fn cmp(
354    prog_track: &'static progress::Progress,
355    src: &std::path::Path,
356    dst: &std::path::Path,
357    log: &LogWriter,
358    settings: &Settings,
359) -> Result<Summary> {
360    cmp_internal(prog_track, src, dst, src, dst, log, settings).await
361}
362
363/// Recursively walks a directory tree on the existing side and records every entry as missing
364/// on the other side.
365#[instrument(skip(prog_track))]
366#[async_recursion]
367async fn expand_missing_tree(
368    prog_track: &'static progress::Progress,
369    existing_path: &std::path::Path,
370    mirror_path: &std::path::Path,
371    existing_root: &std::path::Path,
372    result: CompareResult,
373    log: &LogWriter,
374    settings: &Settings,
375) -> Result<Summary> {
376    let _prog_guard = prog_track.ops.guard();
377    // The side we probe against is fully determined by which tree is
378    // missing: `DstMissing` means we're enumerating src, `SrcMissing`
379    // means we're enumerating dst. `Same` / `Different` are never
380    // passed in (the only two call sites pass the `*Missing` variants),
381    // but be defensive and default to source.
382    let side = match result {
383        CompareResult::DstMissing => congestion::Side::Source,
384        CompareResult::SrcMissing => congestion::Side::Destination,
385        CompareResult::Same | CompareResult::Different => congestion::Side::Source,
386    };
387    let metadata = crate::walk::run_metadata_probed(
388        side,
389        congestion::MetadataOp::Stat,
390        tokio::fs::symlink_metadata(existing_path),
391    )
392    .await
393    .with_context(|| format!("failed reading metadata from {:?}", &existing_path))?;
394    let existing_obj_type = obj_type(&metadata);
395    let mut summary = Summary::default();
396    summary.mismatch[existing_obj_type][result] += 1;
397    // track file sizes on the appropriate side
398    if metadata.is_file() {
399        match result {
400            CompareResult::DstMissing => summary.src_bytes += metadata.len(),
401            CompareResult::SrcMissing => summary.dst_bytes += metadata.len(),
402            _ => {}
403        }
404    }
405    match result {
406        CompareResult::DstMissing => {
407            log.log_mismatch(
408                result,
409                Some(existing_obj_type),
410                existing_path,
411                None,
412                mirror_path,
413            )
414            .await?;
415        }
416        CompareResult::SrcMissing => {
417            log.log_mismatch(
418                result,
419                None,
420                mirror_path,
421                Some(existing_obj_type),
422                existing_path,
423            )
424            .await?;
425        }
426        _ => {}
427    }
428    if settings.exit_early {
429        return Ok(summary);
430    }
431    if !metadata.is_dir() {
432        return Ok(summary);
433    }
434    let mut entries = tokio::fs::read_dir(existing_path)
435        .await
436        .with_context(|| format!("cannot open directory {:?} for reading", &existing_path))?;
437    let mut join_set = tokio::task::JoinSet::new();
438    let errors = crate::error_collector::ErrorCollector::default();
439    loop {
440        let Some((entry, entry_file_type)) =
441            crate::walk::next_entry_probed(&mut entries, side, || {
442                format!("failed traversing directory {:?}", &existing_path)
443            })
444            .await?
445        else {
446            break;
447        };
448        let entry_path = entry.path();
449        let entry_name = entry_path.file_name().unwrap();
450        // apply filter if configured
451        if let Some(ref filter) = settings.filter {
452            let relative_path = entry_path
453                .strip_prefix(existing_root)
454                .unwrap_or(&entry_path);
455            let is_dir = entry_file_type.map(|ft| ft.is_dir()).unwrap_or(false);
456            if !matches!(
457                filter.should_include(relative_path, is_dir),
458                crate::filter::FilterResult::Included
459            ) {
460                // increment skipped counter based on entry type
461                let entry_obj_type = if is_dir {
462                    ObjType::Dir
463                } else if entry_file_type.map(|ft| ft.is_symlink()).unwrap_or(false) {
464                    ObjType::Symlink
465                } else {
466                    ObjType::File
467                };
468                summary.skipped[entry_obj_type] += 1;
469                continue;
470            }
471        }
472        let child_mirror = mirror_path.join(entry_name);
473        let log = log.clone();
474        let settings = settings.clone();
475        let existing_root = existing_root.to_owned();
476        // for positively-known leaf entries (file/symlink/special), acquire
477        // the pending-meta permit BEFORE spawning so we don't create
478        // unbounded tasks. We deliberately skip pre-acquire when
479        // `entry_file_type` is None: the entry could actually be a directory,
480        // and chained unknown-typed directories holding permits while
481        // recursing would deadlock the pending-meta pool. Known directories
482        // also skip pre-acquire. We use the pending-meta semaphore (not
483        // OpenFile) because cmp retains no per-leaf data/classification fd; recursive `ReadDir`
484        // descriptors remain outside leaf admission. Decoupling avoids contention with concurrent
485        // copy paths that hold OpenFile permits
486        let known_leaf = entry_file_type.is_some_and(|ft| !ft.is_dir());
487        let pending_guard = if known_leaf {
488            Some(throttle::pending_meta_permit().await)
489        } else {
490            None
491        };
492        join_set.spawn(async move {
493            let _pending_guard = pending_guard;
494            expand_missing_tree(
495                prog_track,
496                &entry_path,
497                &child_mirror,
498                &existing_root,
499                result,
500                &log,
501                &settings,
502            )
503            .await
504        });
505    }
506    drop(entries);
507    while let Some(res) = join_set.join_next().await {
508        match res? {
509            Ok(child_summary) => summary = summary + child_summary,
510            Err(error) => {
511                tracing::error!(
512                    "expand_missing_tree: {:?} failed with: {:#}",
513                    existing_path,
514                    &error
515                );
516                errors.push(error);
517                if settings.fail_early {
518                    break;
519                }
520            }
521        }
522    }
523    if let Some(err) = errors.into_error() {
524        return Err(err);
525    }
526    Ok(summary)
527}
528
529#[instrument(skip(prog_track))]
530#[async_recursion]
531async fn cmp_internal(
532    prog_track: &'static progress::Progress,
533    src: &std::path::Path,
534    dst: &std::path::Path,
535    source_root: &std::path::Path,
536    dest_root: &std::path::Path,
537    log: &LogWriter,
538    settings: &Settings,
539) -> Result<Summary> {
540    let _prog_guard = prog_track.ops.guard();
541    tracing::debug!("reading source metadata");
542    // it is impossible for src not exist other than user passing invalid path (which is an error)
543    let src_metadata = crate::walk::run_metadata_probed(
544        congestion::Side::Source,
545        congestion::MetadataOp::Stat,
546        tokio::fs::symlink_metadata(src),
547    )
548    .await
549    .with_context(|| format!("failed reading metadata from {:?}", &src))?;
550    // apply filter to root item (when src == source_root, this is the initial call)
551    if src == source_root
552        && let Some(filter) = &settings.filter
553        && let Some(name) = src.file_name()
554    {
555        let is_dir = src_metadata.is_dir();
556        if !matches!(
557            filter.should_include_root_item(name.as_ref(), is_dir),
558            crate::filter::FilterResult::Included
559        ) {
560            // root item filtered out, return summary with skipped count
561            let src_obj_type = obj_type(&src_metadata);
562            let mut summary = Summary::default();
563            summary.skipped[src_obj_type] += 1;
564            return Ok(summary);
565        }
566    }
567    let mut cmp_summary = Summary::default();
568    let src_obj_type = obj_type(&src_metadata);
569    // track file sizes for the summary
570    if src_metadata.is_file() {
571        cmp_summary.src_bytes += src_metadata.len();
572    }
573    let dst_metadata = {
574        let probed = crate::walk::run_metadata_probed(
575            congestion::Side::Destination,
576            congestion::MetadataOp::Stat,
577            tokio::fs::symlink_metadata(dst),
578        )
579        .await;
580        match probed {
581            Ok(metadata) => metadata,
582            Err(err) => {
583                if err.kind() == std::io::ErrorKind::NotFound {
584                    if settings.expand_missing && src_metadata.is_dir() {
585                        let expanded = expand_missing_tree(
586                            prog_track,
587                            src,
588                            dst,
589                            source_root,
590                            CompareResult::DstMissing,
591                            log,
592                            settings,
593                        )
594                        .await?;
595                        cmp_summary = cmp_summary + expanded;
596                    } else {
597                        cmp_summary.mismatch[src_obj_type][CompareResult::DstMissing] += 1;
598                        log.log_mismatch(
599                            CompareResult::DstMissing,
600                            Some(src_obj_type),
601                            src,
602                            None,
603                            dst,
604                        )
605                        .await?;
606                    }
607                    return Ok(cmp_summary);
608                }
609                return Err(err).context(format!("failed reading metadata from {:?}", &dst));
610            }
611        }
612    };
613    if dst_metadata.is_file() {
614        cmp_summary.dst_bytes += dst_metadata.len();
615    }
616    if !is_file_type_same(&src_metadata, &dst_metadata)
617        || !filecmp::metadata_equal(
618            &settings.compare[src_obj_type],
619            &src_metadata,
620            &dst_metadata,
621        )
622    {
623        // we use the src type for the summary attribution
624        cmp_summary.mismatch[src_obj_type][CompareResult::Different] += 1;
625        let dst_obj_type = obj_type(&dst_metadata);
626        log.log_mismatch(
627            CompareResult::Different,
628            Some(src_obj_type),
629            src,
630            Some(dst_obj_type),
631            dst,
632        )
633        .await?;
634        if settings.exit_early {
635            return Ok(cmp_summary);
636        }
637    } else {
638        cmp_summary.mismatch[src_obj_type][CompareResult::Same] += 1;
639    }
640    if !src_metadata.is_dir() || !dst_metadata.is_dir() {
641        // nothing more to do
642        return Ok(cmp_summary);
643    }
644    tracing::debug!("process contents of 'src' directory");
645    let mut src_entries = tokio::fs::read_dir(src)
646        .await
647        .with_context(|| format!("cannot open directory {src:?} for reading"))?;
648    let mut join_set = tokio::task::JoinSet::new();
649    let errors = crate::error_collector::ErrorCollector::default();
650    // create a set of all the files we already processed
651    let mut processed_files = std::collections::HashSet::new();
652    // iterate through src entries and recursively call "cmp" on each one
653    loop {
654        let Some((src_entry, entry_file_type)) =
655            crate::walk::next_entry_probed(&mut src_entries, congestion::Side::Source, || {
656                format!("failed traversing directory {:?}", &src)
657            })
658            .await?
659        else {
660            break;
661        };
662        let entry_path = src_entry.path();
663        let entry_name = entry_path.file_name().unwrap();
664        // apply filter if configured
665        if let Some(ref filter) = settings.filter {
666            // compute relative path from source_root for filter matching
667            let relative_path = crate::walk::relative_to_root(&entry_path, source_root);
668            let is_dir = entry_file_type.map(|ft| ft.is_dir()).unwrap_or(false);
669            if !matches!(
670                filter.should_include(relative_path, is_dir),
671                crate::filter::FilterResult::Included
672            ) {
673                // increment skipped counter based on entry type
674                let entry_obj_type = if is_dir {
675                    ObjType::Dir
676                } else if entry_file_type.map(|ft| ft.is_symlink()).unwrap_or(false) {
677                    ObjType::Symlink
678                } else {
679                    ObjType::File
680                };
681                cmp_summary.skipped[entry_obj_type] += 1;
682                continue;
683            }
684        }
685        processed_files.insert(entry_name.to_owned());
686        let dst_path = dst.join(entry_name);
687        let log = log.clone();
688        let settings = settings.clone();
689        let source_root = source_root.to_owned();
690        let dest_root = dest_root.to_owned();
691        // for positively-known leaf entries (file/symlink/special), acquire
692        // the pending-meta permit BEFORE spawning so we don't create
693        // unbounded tasks. We deliberately skip pre-acquire when
694        // `entry_file_type` is None: the entry could actually be a directory,
695        // and chained unknown-typed directories holding permits while
696        // recursing would deadlock the pending-meta pool. Known directories
697        // also skip pre-acquire. We use the pending-meta semaphore (not
698        // OpenFile) because cmp retains no per-leaf data/classification fd; recursive `ReadDir`
699        // descriptors remain outside leaf admission. Decoupling avoids contention with concurrent
700        // copy paths that hold OpenFile permits
701        let known_leaf = entry_file_type.is_some_and(|ft| !ft.is_dir());
702        let pending_guard = if known_leaf {
703            Some(throttle::pending_meta_permit().await)
704        } else {
705            None
706        };
707        let do_cmp = || async move {
708            let _pending_guard = pending_guard;
709            cmp_internal(
710                prog_track,
711                &entry_path,
712                &dst_path,
713                &source_root,
714                &dest_root,
715                &log,
716                &settings,
717            )
718            .await
719        };
720        join_set.spawn(do_cmp());
721    }
722    // unfortunately ReadDir is opening file-descriptors and there's not a good way to limit this,
723    // one thing we CAN do however is to drop it as soon as we're done with it
724    drop(src_entries);
725    tracing::debug!("process contents of 'dst' directory");
726    let mut dst_entries = tokio::fs::read_dir(dst)
727        .await
728        .with_context(|| format!("cannot open directory {:?} for reading", &dst))?;
729    // iterate through update entries and log each one that's not present in src
730    loop {
731        let Some((dst_entry, entry_file_type)) =
732            crate::walk::next_entry_probed(&mut dst_entries, congestion::Side::Destination, || {
733                format!("failed traversing directory {:?}", &dst)
734            })
735            .await?
736        else {
737            break;
738        };
739        let entry_path = dst_entry.path();
740        let entry_name = entry_path.file_name().unwrap();
741        if processed_files.contains(entry_name) {
742            // we already must have considered this file, skip it
743            continue;
744        }
745        // apply filter if configured - if this entry would be filtered, don't report as missing
746        if let Some(ref filter) = settings.filter {
747            // compute relative path from dest_root for filter matching
748            let relative_path = crate::walk::relative_to_root(&entry_path, dest_root);
749            let is_dir = entry_file_type.map(|ft| ft.is_dir()).unwrap_or(false);
750            if !matches!(
751                filter.should_include(relative_path, is_dir),
752                crate::filter::FilterResult::Included
753            ) {
754                // increment skipped counter based on entry type
755                let entry_obj_type = if is_dir {
756                    ObjType::Dir
757                } else if entry_file_type.map(|ft| ft.is_symlink()).unwrap_or(false) {
758                    ObjType::Symlink
759                } else {
760                    ObjType::File
761                };
762                cmp_summary.skipped[entry_obj_type] += 1;
763                continue;
764            }
765        }
766        tracing::debug!("found a new entry in the 'dst' directory");
767        let dst_path = dst.join(entry_name);
768        let dst_entry_metadata = crate::walk::run_metadata_probed(
769            congestion::Side::Destination,
770            congestion::MetadataOp::Stat,
771            tokio::fs::symlink_metadata(&dst_path),
772        )
773        .await
774        .with_context(|| format!("failed reading metadata from {:?}", &dst_path))?;
775        let dst_obj_type = obj_type(&dst_entry_metadata);
776        if settings.expand_missing && dst_entry_metadata.is_dir() {
777            match expand_missing_tree(
778                prog_track,
779                &dst_path,
780                &src.join(entry_name),
781                dest_root,
782                CompareResult::SrcMissing,
783                log,
784                settings,
785            )
786            .await
787            {
788                Ok(expanded) => cmp_summary = cmp_summary + expanded,
789                Err(error) => {
790                    tracing::error!(
791                        "expand_missing_tree: {:?} failed with: {:#}",
792                        &dst_path,
793                        &error
794                    );
795                    errors.push(error);
796                    if settings.fail_early {
797                        // unwrap is safe: we just pushed an error
798                        return Err(errors.into_error().unwrap());
799                    }
800                }
801            }
802        } else {
803            if dst_entry_metadata.is_file() {
804                cmp_summary.dst_bytes += dst_entry_metadata.len();
805            }
806            cmp_summary.mismatch[dst_obj_type][CompareResult::SrcMissing] += 1;
807            log.log_mismatch(
808                CompareResult::SrcMissing,
809                None,
810                &src.join(entry_name),
811                Some(dst_obj_type),
812                &dst_path,
813            )
814            .await?;
815        }
816    }
817    // unfortunately ReadDir is opening file-descriptors and there's not a good way to limit this,
818    // one thing we CAN do however is to drop it as soon as we're done with it
819    drop(dst_entries);
820    while let Some(res) = join_set.join_next().await {
821        match res? {
822            Ok(summary) => cmp_summary = cmp_summary + summary,
823            Err(error) => {
824                tracing::error!("cmp: {:?} vs {:?} failed with: {:#}", src, dst, &error);
825                errors.push(error);
826                if settings.fail_early {
827                    break;
828                }
829            }
830        }
831    }
832    if let Some(err) = errors.into_error() {
833        return Err(err);
834    }
835    Ok(cmp_summary)
836}
837
838#[cfg(test)]
839mod cmp_tests {
840    use crate::copy;
841    use crate::preserve;
842    use crate::testutils;
843    use enum_map::enum_map;
844    use tracing_test::traced_test;
845
846    use super::*;
847
848    static PROGRESS: std::sync::LazyLock<progress::Progress> =
849        std::sync::LazyLock::new(progress::Progress::new);
850    static NO_PRESERVE_SETTINGS: std::sync::LazyLock<preserve::Settings> =
851        std::sync::LazyLock::new(preserve::preserve_none);
852    static DO_PRESERVE_SETTINGS: std::sync::LazyLock<preserve::Settings> =
853        std::sync::LazyLock::new(preserve::preserve_all);
854
855    async fn setup_test_dirs(preserve: bool) -> Result<std::path::PathBuf> {
856        let tmp_dir = testutils::setup_test_dir().await?;
857        let test_path = tmp_dir.as_path();
858        copy::copy(
859            &PROGRESS,
860            &test_path.join("foo"),
861            &test_path.join("bar"),
862            &copy::Settings {
863                reflink: Default::default(),
864                local_copy_handoff: Default::default(),
865                dereference: false,
866                fail_early: false,
867                overwrite: false,
868                overwrite_compare: filecmp::MetadataCmpSettings {
869                    size: true,
870                    mtime: true,
871                    ..Default::default()
872                },
873                overwrite_filter: None,
874                ignore_existing: false,
875                chunk_size: 0,
876                skip_specials: false,
877                remote_copy_buffer_size: 0,
878                filter: None,
879                dry_run: None,
880                delete: None,
881            },
882            if preserve {
883                &DO_PRESERVE_SETTINGS
884            } else {
885                &NO_PRESERVE_SETTINGS
886            },
887            false,
888        )
889        .await?;
890        Ok(tmp_dir)
891    }
892
893    async fn truncate_file(path: &str) -> Result<()> {
894        let file = tokio::fs::File::create(path).await?;
895        file.set_len(0).await?;
896        Ok(())
897    }
898
899    #[tokio::test]
900    #[traced_test]
901    async fn check_basic_cmp() -> Result<()> {
902        let tmp_dir = setup_test_dirs(true).await?;
903        // drop 1 file from src
904        tokio::fs::remove_file(&tmp_dir.join("foo").join("bar").join("1.txt")).await?;
905        // sleep to ensure mtime is different, this acts as a poor-mans barrier
906        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
907        // modify 1 file in dst
908        truncate_file(
909            tmp_dir
910                .join("bar")
911                .join("baz")
912                .join("4.txt")
913                .to_str()
914                .unwrap(),
915        )
916        .await?;
917        // drop 1 (other) file from dst
918        tokio::fs::remove_file(&tmp_dir.join("bar").join("bar").join("2.txt")).await?;
919        // create one more file in dst -- this will also modify the mtime of the directory
920        tokio::fs::File::create(&tmp_dir.join("bar").join("baz").join("7.txt")).await?;
921        let compare_settings = Settings {
922            fail_early: false,
923            exit_early: false,
924            expand_missing: false,
925            compare: enum_map! {
926                ObjType::File => filecmp::MetadataCmpSettings {
927                    size: true,
928                    mtime: true,
929                    ..Default::default()
930                },
931                ObjType::Dir => filecmp::MetadataCmpSettings {
932                    mtime: true,
933                    ..Default::default()
934                },
935                ObjType::Symlink => filecmp::MetadataCmpSettings {
936                    mtime: true,
937                    ..Default::default()
938                },
939                ObjType::Other => filecmp::MetadataCmpSettings {
940                    mtime: true,
941                    ..Default::default()
942                },
943            },
944            filter: None,
945        };
946        let summary = cmp(
947            &PROGRESS,
948            &tmp_dir.join("foo"),
949            &tmp_dir.join("bar"),
950            &LogWriter::new(
951                Some(tmp_dir.join("cmp.log").as_path()),
952                false,
953                OutputFormat::Text,
954            )
955            .await?,
956            &compare_settings,
957        )
958        .await?;
959        let mismatch: Mismatch = enum_map! {
960            ObjType::File => enum_map! {
961                CompareResult::Different => 1,
962                CompareResult::Same => 2,
963                CompareResult::SrcMissing => 2,
964                CompareResult::DstMissing => 1,
965            },
966            ObjType::Dir => enum_map! {
967                CompareResult::Different => 2,
968                CompareResult::Same => 1,
969                CompareResult::SrcMissing => 0,
970                CompareResult::DstMissing => 0,
971            },
972            ObjType::Symlink => enum_map! {
973                CompareResult::Different => 0,
974                CompareResult::Same => 2,
975                CompareResult::SrcMissing => 0,
976                CompareResult::DstMissing => 0,
977            },
978            ObjType::Other => enum_map! {
979                CompareResult::Different => 0,
980                CompareResult::Same => 0,
981                CompareResult::SrcMissing => 0,
982                CompareResult::DstMissing => 0,
983            },
984        };
985        assert_eq!(summary.mismatch, mismatch);
986        // src has 4 regular files of 1 byte each (0.txt, bar/2.txt, bar/3.txt, baz/4.txt)
987        assert_eq!(summary.src_bytes, 4);
988        // dst has: 0.txt(1B), bar/1.txt(1B, SrcMissing), bar/3.txt(1B), baz/4.txt(0B, truncated), baz/7.txt(0B, SrcMissing)
989        assert_eq!(summary.dst_bytes, 3);
990        Ok(())
991    }
992
993    #[tokio::test]
994    #[traced_test]
995    async fn cmp_with_filter_excludes_files() -> Result<()> {
996        let tmp_dir = setup_test_dirs(true).await?;
997        // setup: src=foo, dst=bar (identical at this point)
998        // add a file to dst that would be reported as SrcMissing
999        tokio::fs::write(&tmp_dir.join("bar").join("extra.txt"), "extra").await?;
1000        // without filter, should report extra.txt as SrcMissing
1001        let compare_settings_no_filter = Settings {
1002            fail_early: false,
1003            exit_early: false,
1004            expand_missing: false,
1005            compare: enum_map! {
1006                ObjType::File => filecmp::MetadataCmpSettings {
1007                    size: true,
1008                    mtime: true,
1009                    ..Default::default()
1010                },
1011                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1012                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1013                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1014            },
1015            filter: None,
1016        };
1017        let summary = cmp(
1018            &PROGRESS,
1019            &tmp_dir.join("foo"),
1020            &tmp_dir.join("bar"),
1021            &LogWriter::silent().await?,
1022            &compare_settings_no_filter,
1023        )
1024        .await?;
1025        assert_eq!(
1026            summary.mismatch[ObjType::File][CompareResult::SrcMissing],
1027            1
1028        );
1029        // with filter excluding extra.txt, should not report it
1030        let mut filter = crate::filter::FilterSettings::new();
1031        filter.add_exclude("extra.txt")?;
1032        let compare_settings_with_filter = Settings {
1033            fail_early: false,
1034            exit_early: false,
1035            expand_missing: false,
1036            compare: enum_map! {
1037                ObjType::File => filecmp::MetadataCmpSettings {
1038                    size: true,
1039                    mtime: true,
1040                    ..Default::default()
1041                },
1042                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1043                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1044                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1045            },
1046            filter: Some(filter),
1047        };
1048        let summary = cmp(
1049            &PROGRESS,
1050            &tmp_dir.join("foo"),
1051            &tmp_dir.join("bar"),
1052            &LogWriter::silent().await?,
1053            &compare_settings_with_filter,
1054        )
1055        .await?;
1056        assert_eq!(
1057            summary.mismatch[ObjType::File][CompareResult::SrcMissing],
1058            0
1059        );
1060        Ok(())
1061    }
1062
1063    #[tokio::test]
1064    #[traced_test]
1065    async fn cmp_with_include_only_compares_matching() -> Result<()> {
1066        let tmp_dir = setup_test_dirs(true).await?;
1067        // setup: src=foo, dst=bar (identical at this point)
1068        // modify a file that won't be included
1069        tokio::fs::write(&tmp_dir.join("bar").join("bar").join("1.txt"), "modified").await?;
1070        // with include pattern for only *.rs files, the .txt modification shouldn't appear
1071        let mut filter = crate::filter::FilterSettings::new();
1072        filter.add_include("*.rs")?;
1073        let compare_settings = Settings {
1074            fail_early: false,
1075            exit_early: false,
1076            expand_missing: false,
1077            compare: enum_map! {
1078                ObjType::File => filecmp::MetadataCmpSettings {
1079                    size: true,
1080                    mtime: true,
1081                    ..Default::default()
1082                },
1083                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1084                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1085                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1086            },
1087            filter: Some(filter),
1088        };
1089        let summary = cmp(
1090            &PROGRESS,
1091            &tmp_dir.join("foo"),
1092            &tmp_dir.join("bar"),
1093            &LogWriter::silent().await?,
1094            &compare_settings,
1095        )
1096        .await?;
1097        // no differences should be reported since all .txt files are excluded
1098        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Different], 0);
1099        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Same], 0);
1100        assert_eq!(
1101            summary.mismatch[ObjType::File][CompareResult::SrcMissing],
1102            0
1103        );
1104        assert_eq!(
1105            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1106            0
1107        );
1108        Ok(())
1109    }
1110
1111    #[tokio::test]
1112    #[traced_test]
1113    async fn cmp_with_path_pattern_filters_nested() -> Result<()> {
1114        // test that path-based patterns like "bar/*.txt" work correctly when recursing
1115        // this verifies source_root tracking is working properly
1116        let tmp_dir = setup_test_dirs(true).await?;
1117        // test structure:
1118        // foo/bar/1.txt, foo/bar/2.txt, foo/bar/3.txt
1119        // foo/baz/4.txt, foo/baz/5.txt (symlink), foo/baz/6.txt (symlink)
1120        // filter: only include bar/*.txt
1121        let mut filter = crate::filter::FilterSettings::new();
1122        filter.add_include("bar/*.txt")?;
1123        let compare_settings = Settings {
1124            fail_early: false,
1125            exit_early: false,
1126            expand_missing: false,
1127            compare: enum_map! {
1128                ObjType::File => filecmp::MetadataCmpSettings {
1129                    size: true,
1130                    ..Default::default()
1131                },
1132                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1133                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1134                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1135            },
1136            filter: Some(filter),
1137        };
1138        let summary = cmp(
1139            &PROGRESS,
1140            &tmp_dir.join("foo"),
1141            &tmp_dir.join("bar"),
1142            &LogWriter::silent().await?,
1143            &compare_settings,
1144        )
1145        .await?;
1146        // should only compare files in bar/ subdirectory (3 files: 1.txt, 2.txt, 3.txt)
1147        // all should be "Same" since we copied foo to bar earlier
1148        assert_eq!(
1149            summary.mismatch[ObjType::File][CompareResult::Same],
1150            3,
1151            "should have 3 same files from bar/*.txt pattern"
1152        );
1153        // files in baz/ should not be compared (filtered out)
1154        // 0.txt at root should not be compared
1155        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Different], 0);
1156        Ok(())
1157    }
1158
1159    #[tokio::test]
1160    #[traced_test]
1161    async fn cmp_filter_applies_to_root_file() -> Result<()> {
1162        // test that filters apply to the root item itself
1163        let tmp_dir = testutils::create_temp_dir().await?;
1164        // create two different files
1165        tokio::fs::write(tmp_dir.join("test.txt"), "content1").await?;
1166        tokio::fs::write(tmp_dir.join("test2.txt"), "content2").await?;
1167        // filter: only include *.rs files
1168        let mut filter = crate::filter::FilterSettings::new();
1169        filter.add_include("*.rs")?;
1170        let compare_settings = Settings {
1171            fail_early: false,
1172            exit_early: false,
1173            expand_missing: false,
1174            compare: enum_map! {
1175                ObjType::File => filecmp::MetadataCmpSettings {
1176                    size: true,
1177                    ..Default::default()
1178                },
1179                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1180                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1181                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1182            },
1183            filter: Some(filter),
1184        };
1185        // compare test.txt vs test2.txt - should be filtered out (not *.rs)
1186        let summary = cmp(
1187            &PROGRESS,
1188            &tmp_dir.join("test.txt"),
1189            &tmp_dir.join("test2.txt"),
1190            &LogWriter::silent().await?,
1191            &compare_settings,
1192        )
1193        .await?;
1194        // should return empty summary since root file is filtered
1195        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Same], 0);
1196        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Different], 0);
1197        Ok(())
1198    }
1199
1200    #[tokio::test]
1201    #[traced_test]
1202    async fn cmp_filter_excludes_root_directory() -> Result<()> {
1203        // test that filters apply to root directories
1204        let tmp_dir = testutils::setup_test_dir().await?;
1205        // filter: exclude directories named "foo"
1206        let mut filter = crate::filter::FilterSettings::new();
1207        filter.add_exclude("foo")?;
1208        let compare_settings = Settings {
1209            fail_early: false,
1210            exit_early: false,
1211            expand_missing: false,
1212            compare: enum_map! {
1213                ObjType::File => filecmp::MetadataCmpSettings::default(),
1214                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1215                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1216                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1217            },
1218            filter: Some(filter),
1219        };
1220        // compare foo vs bar - foo should be filtered out
1221        let summary = cmp(
1222            &PROGRESS,
1223            &tmp_dir.join("foo"),
1224            &tmp_dir.join("bar"),
1225            &LogWriter::silent().await?,
1226            &compare_settings,
1227        )
1228        .await?;
1229        // should return empty summary since root dir is excluded
1230        assert_eq!(summary.mismatch[ObjType::Dir][CompareResult::Same], 0);
1231        assert_eq!(summary.mismatch[ObjType::Dir][CompareResult::Different], 0);
1232        assert_eq!(summary.mismatch[ObjType::File][CompareResult::Same], 0);
1233        Ok(())
1234    }
1235
1236    #[tokio::test]
1237    #[traced_test]
1238    async fn cmp_combined_include_exclude_patterns() -> Result<()> {
1239        let tmp_dir = setup_test_dirs(true).await?;
1240        // include all .txt files, but exclude bar/2.txt specifically
1241        let mut filter = crate::filter::FilterSettings::new();
1242        filter.add_include("**/*.txt")?;
1243        filter.add_exclude("bar/2.txt")?;
1244        let compare_settings = Settings {
1245            fail_early: false,
1246            exit_early: false,
1247            expand_missing: false,
1248            compare: enum_map! {
1249                ObjType::File => filecmp::MetadataCmpSettings {
1250                    size: true,
1251                    ..Default::default()
1252                },
1253                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1254                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1255                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1256            },
1257            filter: Some(filter),
1258        };
1259        let summary = cmp(
1260            &PROGRESS,
1261            &tmp_dir.join("foo"),
1262            &tmp_dir.join("bar"),
1263            &LogWriter::silent().await?,
1264            &compare_settings,
1265        )
1266        .await?;
1267        // should compare: 0.txt, bar/1.txt, bar/3.txt, baz/4.txt = 4 files (same)
1268        // should skip: bar/2.txt (excluded by pattern), 5.txt and 6.txt (symlinks, no match for *.txt in src dir) = 1 file + 2 symlinks
1269        // note: the pattern **/*.txt only matches files with .txt extension, but 5.txt and 6.txt in baz are symlinks
1270        assert_eq!(
1271            summary.mismatch[ObjType::File][CompareResult::Same],
1272            4,
1273            "should compare 4 .txt files as same"
1274        );
1275        // bar/2.txt is skipped for both src and dst traversal = 2 skipped
1276        assert_eq!(
1277            summary.skipped[ObjType::File],
1278            2,
1279            "should skip 2 files (bar/2.txt on src and dst)"
1280        );
1281        Ok(())
1282    }
1283
1284    #[tokio::test]
1285    #[traced_test]
1286    async fn cmp_skipped_counts_comprehensive() -> Result<()> {
1287        let tmp_dir = setup_test_dirs(true).await?;
1288        // exclude bar/ directory entirely
1289        let mut filter = crate::filter::FilterSettings::new();
1290        filter.add_exclude("bar/")?;
1291        let compare_settings = Settings {
1292            fail_early: false,
1293            exit_early: false,
1294            expand_missing: false,
1295            compare: enum_map! {
1296                ObjType::File => filecmp::MetadataCmpSettings {
1297                    size: true,
1298                    ..Default::default()
1299                },
1300                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1301                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1302                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1303            },
1304            filter: Some(filter),
1305        };
1306        let summary = cmp(
1307            &PROGRESS,
1308            &tmp_dir.join("foo"),
1309            &tmp_dir.join("bar"),
1310            &LogWriter::silent().await?,
1311            &compare_settings,
1312        )
1313        .await?;
1314        // compared: 0.txt (same), baz/4.txt (same) = 2 files
1315        // compared: baz/5.txt symlink (same), baz/6.txt symlink (same) = 2 symlinks
1316        // skipped: bar directory in src and dst = 2 dirs (cmp traverses both)
1317        assert_eq!(
1318            summary.mismatch[ObjType::File][CompareResult::Same],
1319            2,
1320            "should compare 2 files as same"
1321        );
1322        assert_eq!(
1323            summary.mismatch[ObjType::Symlink][CompareResult::Same],
1324            2,
1325            "should compare 2 symlinks as same"
1326        );
1327        assert_eq!(
1328            summary.skipped[ObjType::Dir],
1329            2,
1330            "should skip 2 directories (bar in src + bar in dst)"
1331        );
1332        Ok(())
1333    }
1334
1335    #[tokio::test]
1336    #[traced_test]
1337    async fn expand_missing_dst_reports_all_entries() -> Result<()> {
1338        let tmp_dir = setup_test_dirs(true).await?;
1339        // remove bar/bar directory entirely from dst
1340        tokio::fs::remove_dir_all(&tmp_dir.join("bar").join("bar")).await?;
1341        let compare_settings = Settings {
1342            fail_early: false,
1343            exit_early: false,
1344            expand_missing: true,
1345            compare: enum_map! {
1346                ObjType::File => filecmp::MetadataCmpSettings::default(),
1347                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1348                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1349                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1350            },
1351            filter: None,
1352        };
1353        let summary = cmp(
1354            &PROGRESS,
1355            &tmp_dir.join("foo"),
1356            &tmp_dir.join("bar"),
1357            &LogWriter::silent().await?,
1358            &compare_settings,
1359        )
1360        .await?;
1361        // bar/bar dir has: bar/ (1 dir) + 1.txt, 2.txt, 3.txt (3 files)
1362        assert_eq!(
1363            summary.mismatch[ObjType::Dir][CompareResult::DstMissing],
1364            1,
1365            "should report 1 directory as DstMissing"
1366        );
1367        assert_eq!(
1368            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1369            3,
1370            "should report 3 files as DstMissing"
1371        );
1372        Ok(())
1373    }
1374
1375    #[tokio::test]
1376    #[traced_test]
1377    async fn expand_missing_src_reports_all_entries() -> Result<()> {
1378        let tmp_dir = setup_test_dirs(true).await?;
1379        // create a new subdir in dst with files
1380        let newdir = tmp_dir.join("bar").join("newdir");
1381        tokio::fs::create_dir(&newdir).await?;
1382        tokio::fs::write(newdir.join("a.txt"), "a").await?;
1383        tokio::fs::write(newdir.join("b.txt"), "b").await?;
1384        let compare_settings = Settings {
1385            fail_early: false,
1386            exit_early: false,
1387            expand_missing: true,
1388            compare: enum_map! {
1389                ObjType::File => filecmp::MetadataCmpSettings::default(),
1390                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1391                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1392                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1393            },
1394            filter: None,
1395        };
1396        let summary = cmp(
1397            &PROGRESS,
1398            &tmp_dir.join("foo"),
1399            &tmp_dir.join("bar"),
1400            &LogWriter::silent().await?,
1401            &compare_settings,
1402        )
1403        .await?;
1404        assert_eq!(
1405            summary.mismatch[ObjType::Dir][CompareResult::SrcMissing],
1406            1,
1407            "should report 1 directory as SrcMissing"
1408        );
1409        assert_eq!(
1410            summary.mismatch[ObjType::File][CompareResult::SrcMissing],
1411            2,
1412            "should report 2 files as SrcMissing"
1413        );
1414        Ok(())
1415    }
1416
1417    #[tokio::test]
1418    #[traced_test]
1419    async fn expand_missing_dst_deeply_nested() -> Result<()> {
1420        // verify expansion recurses through multiple directory levels
1421        let tmp_dir = testutils::create_temp_dir().await?;
1422        let src = tmp_dir.join("src");
1423        let dst = tmp_dir.join("dst");
1424        tokio::fs::create_dir(&src).await?;
1425        tokio::fs::create_dir(&dst).await?;
1426        // create src/a/b/c/d.txt -- 3 dirs deep
1427        let deep = src.join("a").join("b").join("c");
1428        tokio::fs::create_dir_all(&deep).await?;
1429        tokio::fs::write(deep.join("d.txt"), "d").await?;
1430        // also add a sibling file at an intermediate level
1431        tokio::fs::write(src.join("a").join("b").join("mid.txt"), "m").await?;
1432        // dst exists but is empty -- everything in src is DstMissing
1433        let compare_settings = Settings {
1434            fail_early: false,
1435            exit_early: false,
1436            expand_missing: true,
1437            compare: enum_map! {
1438                ObjType::File => filecmp::MetadataCmpSettings::default(),
1439                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1440                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1441                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1442            },
1443            filter: None,
1444        };
1445        let summary = cmp(
1446            &PROGRESS,
1447            &src,
1448            &dst,
1449            &LogWriter::silent().await?,
1450            &compare_settings,
1451        )
1452        .await?;
1453        // dirs: a, a/b, a/b/c = 3 DstMissing dirs
1454        assert_eq!(
1455            summary.mismatch[ObjType::Dir][CompareResult::DstMissing],
1456            3,
1457            "should report 3 nested directories as DstMissing"
1458        );
1459        // files: a/b/c/d.txt, a/b/mid.txt = 2 DstMissing files
1460        assert_eq!(
1461            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1462            2,
1463            "should report 2 files as DstMissing"
1464        );
1465        // src_bytes: d.txt(1) + mid.txt(1) = 2
1466        assert_eq!(
1467            summary.src_bytes, 2,
1468            "should track bytes for expanded files"
1469        );
1470        Ok(())
1471    }
1472
1473    #[tokio::test]
1474    #[traced_test]
1475    async fn expand_missing_src_deeply_nested() -> Result<()> {
1476        // verify expansion recurses for SrcMissing through multiple levels
1477        let tmp_dir = testutils::create_temp_dir().await?;
1478        let src = tmp_dir.join("src");
1479        let dst = tmp_dir.join("dst");
1480        tokio::fs::create_dir(&src).await?;
1481        tokio::fs::create_dir(&dst).await?;
1482        // create dst/x/y/z.txt -- dirs only in dst
1483        let deep = dst.join("x").join("y");
1484        tokio::fs::create_dir_all(&deep).await?;
1485        tokio::fs::write(deep.join("z.txt"), "zz").await?;
1486        let compare_settings = Settings {
1487            fail_early: false,
1488            exit_early: false,
1489            expand_missing: true,
1490            compare: enum_map! {
1491                ObjType::File => filecmp::MetadataCmpSettings::default(),
1492                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1493                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1494                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1495            },
1496            filter: None,
1497        };
1498        let summary = cmp(
1499            &PROGRESS,
1500            &src,
1501            &dst,
1502            &LogWriter::silent().await?,
1503            &compare_settings,
1504        )
1505        .await?;
1506        // dirs: x, x/y = 2 SrcMissing dirs
1507        assert_eq!(
1508            summary.mismatch[ObjType::Dir][CompareResult::SrcMissing],
1509            2,
1510            "should report 2 nested directories as SrcMissing"
1511        );
1512        // files: x/y/z.txt = 1 SrcMissing file
1513        assert_eq!(
1514            summary.mismatch[ObjType::File][CompareResult::SrcMissing],
1515            1,
1516            "should report 1 file as SrcMissing"
1517        );
1518        // dst_bytes: z.txt(2)
1519        assert_eq!(
1520            summary.dst_bytes, 2,
1521            "should track bytes for expanded files"
1522        );
1523        Ok(())
1524    }
1525
1526    #[tokio::test]
1527    #[traced_test]
1528    async fn expand_missing_with_exclude_filter() -> Result<()> {
1529        // verify that filters are applied during expansion. exclude *.log files
1530        // from the missing subtree
1531        let tmp_dir = testutils::create_temp_dir().await?;
1532        let src = tmp_dir.join("src");
1533        let dst = tmp_dir.join("dst");
1534        tokio::fs::create_dir(&src).await?;
1535        tokio::fs::create_dir(&dst).await?;
1536        // src/missing_dir/ has mixed files
1537        let missing = src.join("missing_dir");
1538        tokio::fs::create_dir(&missing).await?;
1539        tokio::fs::write(missing.join("keep.txt"), "k").await?;
1540        tokio::fs::write(missing.join("skip.log"), "s").await?;
1541        tokio::fs::write(missing.join("also_keep.txt"), "a").await?;
1542        let mut filter = crate::filter::FilterSettings::new();
1543        filter.add_exclude("*.log")?;
1544        let compare_settings = Settings {
1545            fail_early: false,
1546            exit_early: false,
1547            expand_missing: true,
1548            compare: enum_map! {
1549                ObjType::File => filecmp::MetadataCmpSettings::default(),
1550                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1551                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1552                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1553            },
1554            filter: Some(filter),
1555        };
1556        let summary = cmp(
1557            &PROGRESS,
1558            &src,
1559            &dst,
1560            &LogWriter::silent().await?,
1561            &compare_settings,
1562        )
1563        .await?;
1564        // missing_dir itself = 1 DstMissing dir
1565        assert_eq!(summary.mismatch[ObjType::Dir][CompareResult::DstMissing], 1,);
1566        // only keep.txt and also_keep.txt should be reported. skip.log is filtered
1567        assert_eq!(
1568            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1569            2,
1570            "should report only non-excluded files as DstMissing"
1571        );
1572        // skip.log should be counted as skipped
1573        assert_eq!(
1574            summary.skipped[ObjType::File],
1575            1,
1576            "should count excluded file as skipped"
1577        );
1578        Ok(())
1579    }
1580
1581    #[tokio::test]
1582    #[traced_test]
1583    async fn expand_missing_with_include_filter() -> Result<()> {
1584        // verify that include filters restrict which children are reported during expansion
1585        let tmp_dir = testutils::create_temp_dir().await?;
1586        let src = tmp_dir.join("src");
1587        let dst = tmp_dir.join("dst");
1588        tokio::fs::create_dir(&src).await?;
1589        tokio::fs::create_dir(&dst).await?;
1590        // src/data/ has a mix of file types
1591        let data = src.join("data");
1592        tokio::fs::create_dir(&data).await?;
1593        tokio::fs::write(data.join("a.rs"), "fn main() {}").await?;
1594        tokio::fs::write(data.join("b.txt"), "hello").await?;
1595        tokio::fs::write(data.join("c.rs"), "fn test() {}").await?;
1596        let mut filter = crate::filter::FilterSettings::new();
1597        filter.add_include("**/*.rs")?;
1598        let compare_settings = Settings {
1599            fail_early: false,
1600            exit_early: false,
1601            expand_missing: true,
1602            compare: enum_map! {
1603                ObjType::File => filecmp::MetadataCmpSettings::default(),
1604                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1605                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1606                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1607            },
1608            filter: Some(filter),
1609        };
1610        let summary = cmp(
1611            &PROGRESS,
1612            &src,
1613            &dst,
1614            &LogWriter::silent().await?,
1615            &compare_settings,
1616        )
1617        .await?;
1618        // data dir = 1 DstMissing dir
1619        assert_eq!(summary.mismatch[ObjType::Dir][CompareResult::DstMissing], 1,);
1620        // only a.rs and c.rs should be reported. b.txt is filtered out
1621        assert_eq!(
1622            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1623            2,
1624            "should report only included files as DstMissing"
1625        );
1626        Ok(())
1627    }
1628
1629    #[tokio::test]
1630    #[traced_test]
1631    async fn expand_missing_with_nested_path_filter() -> Result<()> {
1632        // verify path-based patterns work correctly during expansion.
1633        // only include files under a specific nested path
1634        let tmp_dir = testutils::create_temp_dir().await?;
1635        let src = tmp_dir.join("src");
1636        let dst = tmp_dir.join("dst");
1637        tokio::fs::create_dir(&src).await?;
1638        tokio::fs::create_dir(&dst).await?;
1639        // src/top/ has two subdirs: keep/ and skip/
1640        let top = src.join("top");
1641        let keep = top.join("keep");
1642        let skip = top.join("skip");
1643        tokio::fs::create_dir_all(&keep).await?;
1644        tokio::fs::create_dir_all(&skip).await?;
1645        tokio::fs::write(keep.join("1.txt"), "1").await?;
1646        tokio::fs::write(keep.join("2.txt"), "2").await?;
1647        tokio::fs::write(skip.join("3.txt"), "3").await?;
1648        let mut filter = crate::filter::FilterSettings::new();
1649        filter.add_include("top/keep/**")?;
1650        let compare_settings = Settings {
1651            fail_early: false,
1652            exit_early: false,
1653            expand_missing: true,
1654            compare: enum_map! {
1655                ObjType::File => filecmp::MetadataCmpSettings::default(),
1656                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1657                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1658                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1659            },
1660            filter: Some(filter),
1661        };
1662        let summary = cmp(
1663            &PROGRESS,
1664            &src,
1665            &dst,
1666            &LogWriter::silent().await?,
1667            &compare_settings,
1668        )
1669        .await?;
1670        // only keep/ subtree: keep dir(1) + top dir(1) = 2 dirs. skip dir is filtered
1671        assert_eq!(
1672            summary.mismatch[ObjType::Dir][CompareResult::DstMissing],
1673            2,
1674            "should report top and keep dirs as DstMissing"
1675        );
1676        // only 1.txt and 2.txt from keep/
1677        assert_eq!(
1678            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1679            2,
1680            "should report only files under keep/ as DstMissing"
1681        );
1682        Ok(())
1683    }
1684
1685    #[tokio::test]
1686    #[traced_test]
1687    async fn expand_missing_false_preserves_original_behavior() -> Result<()> {
1688        let tmp_dir = setup_test_dirs(true).await?;
1689        // remove bar/bar directory entirely from dst
1690        tokio::fs::remove_dir_all(&tmp_dir.join("bar").join("bar")).await?;
1691        let compare_settings = Settings {
1692            fail_early: false,
1693            exit_early: false,
1694            expand_missing: false,
1695            compare: enum_map! {
1696                ObjType::File => filecmp::MetadataCmpSettings::default(),
1697                ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1698                ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1699                ObjType::Other => filecmp::MetadataCmpSettings::default(),
1700            },
1701            filter: None,
1702        };
1703        let summary = cmp(
1704            &PROGRESS,
1705            &tmp_dir.join("foo"),
1706            &tmp_dir.join("bar"),
1707            &LogWriter::silent().await?,
1708            &compare_settings,
1709        )
1710        .await?;
1711        // without expand_missing, only the top-level dir is reported
1712        assert_eq!(
1713            summary.mismatch[ObjType::Dir][CompareResult::DstMissing],
1714            1,
1715            "should report only 1 directory as DstMissing"
1716        );
1717        assert_eq!(
1718            summary.mismatch[ObjType::File][CompareResult::DstMissing],
1719            0,
1720            "should not report individual files as DstMissing"
1721        );
1722        Ok(())
1723    }
1724
1725    #[test]
1726    fn path_to_json_string_utf8() {
1727        let path = std::path::Path::new("/foo/bar/baz.txt");
1728        assert_eq!(path_to_json_string(path), "/foo/bar/baz.txt");
1729    }
1730
1731    #[test]
1732    fn path_to_json_string_non_utf8() {
1733        use std::ffi::OsStr;
1734        use std::os::unix::ffi::OsStrExt;
1735        // embed 0xFF byte in the middle
1736        let os_str = OsStr::from_bytes(b"/tmp/bad\xffname.txt");
1737        let path = std::path::Path::new(os_str);
1738        assert_eq!(path_to_json_string(path), "/tmp/bad\\xffname.txt");
1739    }
1740
1741    #[test]
1742    fn path_to_json_string_multiple_bad_bytes() {
1743        use std::ffi::OsStr;
1744        use std::os::unix::ffi::OsStrExt;
1745        let os_str = OsStr::from_bytes(b"\x80/ok/\xfe\xff/end");
1746        let path = std::path::Path::new(os_str);
1747        assert_eq!(path_to_json_string(path), "\\x80/ok/\\xfe\\xff/end");
1748    }
1749
1750    #[test]
1751    fn path_to_json_string_escapes_backslashes() {
1752        // a path with a literal backslash must be escaped so it doesn't
1753        // collide with \xHH byte escapes
1754        let path = std::path::Path::new("/tmp/bad\\xffname.txt");
1755        assert_eq!(path_to_json_string(path), "/tmp/bad\\\\xffname.txt");
1756    }
1757
1758    #[test]
1759    fn path_to_json_string_no_collision() {
1760        use std::ffi::OsStr;
1761        use std::os::unix::ffi::OsStrExt;
1762        // literal backslash-x-f-f in the filename
1763        let literal = std::path::Path::new("/tmp/bad\\xffname.txt");
1764        // actual 0xFF byte in the filename
1765        let raw = std::path::Path::new(OsStr::from_bytes(b"/tmp/bad\xffname.txt"));
1766        // these must produce different output
1767        assert_ne!(path_to_json_string(literal), path_to_json_string(raw));
1768    }
1769
1770    /// Stress tests exercising max-files-in-flight saturation during cmp.
1771    mod max_files_in_flight_tests {
1772        use super::*;
1773        use anyhow::Context;
1774
1775        /// Deep + wide cmp: a directory tree deeper than the files-in-flight limit, with files at every
1776        /// level. Verifies directories do not retain pending-metadata permits across recursion.
1777        #[tokio::test]
1778        #[traced_test]
1779        async fn deep_tree_no_deadlock_under_files_in_flight_saturation() -> Result<()> {
1780            let tmp_dir = testutils::create_temp_dir().await?;
1781            let src = tmp_dir.join("src");
1782            let dst = tmp_dir.join("dst");
1783            let depth = 20;
1784            let files_per_level = 5;
1785            let limit = 4;
1786            // create matching directory chains in src and dst, deeper than the permit limit
1787            let mut src_dir = src.clone();
1788            let mut dst_dir = dst.clone();
1789            for level in 0..depth {
1790                tokio::fs::create_dir_all(&src_dir).await?;
1791                tokio::fs::create_dir_all(&dst_dir).await?;
1792                for f in 0..files_per_level {
1793                    let name = format!("f{}_{}.txt", level, f);
1794                    let content = format!("L{}F{}", level, f);
1795                    tokio::fs::write(src_dir.join(&name), &content).await?;
1796                    tokio::fs::write(dst_dir.join(&name), &content).await?;
1797                }
1798                src_dir = src_dir.join(format!("d{}", level));
1799                dst_dir = dst_dir.join(format!("d{}", level));
1800            }
1801            let admission = crate::testutils::AdmissionLimit::new().await;
1802            admission.set_files_in_flight(limit);
1803            let compare_settings = Settings {
1804                fail_early: false,
1805                exit_early: false,
1806                expand_missing: false,
1807                compare: enum_map::enum_map! {
1808                    ObjType::File => filecmp::MetadataCmpSettings { size: true, ..Default::default() },
1809                    ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1810                    ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1811                    ObjType::Other => filecmp::MetadataCmpSettings::default(),
1812                },
1813                filter: None,
1814            };
1815            let summary = admission
1816                .run_with_timeout(
1817                    std::time::Duration::from_secs(30),
1818                    cmp(
1819                        &PROGRESS,
1820                        &src,
1821                        &dst,
1822                        &LogWriter::silent().await?,
1823                        &compare_settings,
1824                    ),
1825                )
1826                .await
1827                .context("cmp timed out — possible deadlock")?
1828                .context("cmp failed")?;
1829            assert_eq!(
1830                summary.mismatch[ObjType::File][CompareResult::Same],
1831                depth * files_per_level
1832            );
1833            Ok(())
1834        }
1835
1836        /// expand_missing under saturation: dst is empty, src is a deep tree.
1837        /// verifies expand_missing_tree's recursion bounds tasks under the permit cap.
1838        #[tokio::test]
1839        #[traced_test]
1840        async fn expand_missing_under_files_in_flight_saturation() -> Result<()> {
1841            let tmp_dir = testutils::create_temp_dir().await?;
1842            let src = tmp_dir.join("src");
1843            let dst = tmp_dir.join("dst");
1844            let depth = 10;
1845            let files_per_level = 5;
1846            let limit = 4;
1847            // create a deep tree in src; dst stays empty
1848            let mut dir = src.clone();
1849            for level in 0..depth {
1850                tokio::fs::create_dir_all(&dir).await?;
1851                for f in 0..files_per_level {
1852                    tokio::fs::write(dir.join(format!("f{}_{}.txt", level, f)), "x").await?;
1853                }
1854                dir = dir.join(format!("d{}", level));
1855            }
1856            tokio::fs::create_dir(&dst).await?;
1857            let admission = crate::testutils::AdmissionLimit::new().await;
1858            admission.set_files_in_flight(limit);
1859            let compare_settings = Settings {
1860                fail_early: false,
1861                exit_early: false,
1862                expand_missing: true,
1863                compare: enum_map::enum_map! {
1864                    ObjType::File => filecmp::MetadataCmpSettings::default(),
1865                    ObjType::Dir => filecmp::MetadataCmpSettings::default(),
1866                    ObjType::Symlink => filecmp::MetadataCmpSettings::default(),
1867                    ObjType::Other => filecmp::MetadataCmpSettings::default(),
1868                },
1869                filter: None,
1870            };
1871            let summary = admission
1872                .run_with_timeout(
1873                    std::time::Duration::from_secs(30),
1874                    cmp(
1875                        &PROGRESS,
1876                        &src,
1877                        &dst,
1878                        &LogWriter::silent().await?,
1879                        &compare_settings,
1880                    ),
1881                )
1882                .await
1883                .context("cmp timed out — possible deadlock")?
1884                .context("cmp failed")?;
1885            // every file under src is missing on dst
1886            assert_eq!(
1887                summary.mismatch[ObjType::File][CompareResult::DstMissing],
1888                depth * files_per_level
1889            );
1890            Ok(())
1891        }
1892    }
1893}