Skip to main content

common/
copy.rs

1pub(crate) mod destination;
2pub(crate) use destination::{
3    DestinationContext, PreparedDestination, PreviewParent, SourceSnapshot,
4};
5
6use std::ffi::{OsStr, OsString};
7use std::path::PathBuf;
8use std::sync::Arc;
9
10use anyhow::{Context, anyhow};
11use throttle::get_file_iops_tokens;
12use tracing::instrument;
13
14use crate::config::DryRunMode;
15use crate::copy_data::copy_file_data;
16use crate::filecmp;
17use crate::preserve;
18use crate::progress;
19use crate::rm;
20use crate::rm::{Settings as RmSettings, Summary as RmSummary};
21use crate::safedir::{self, Dir, FileMeta, Handle, RemovalSnapshot};
22use crate::walk::{AdmittedEntry, AdmittedLeaf, EntryAdmission, EntryKind, LeafPermit, PermitKind};
23use crate::walk_driver::{
24    DirAction, DirPostInput, DirPreResult, EntryCx, NameCollection, SkippedEntry, WalkVisitor,
25    process_admitted_entry, process_entry,
26};
27
28/// Error type for copy operations. See [`crate::error::OperationError`] for
29/// logging conventions and rationale.
30pub type Error = crate::error::OperationError<Summary>;
31
32/// Filter condition for overwrite operations.
33///
34/// Used with `--overwrite-filter` to skip overwriting files that match
35/// a directional condition (e.g., destination is newer than source).
36#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
37pub enum OverwriteFilter {
38    /// Skip overwriting if the destination file is strictly newer (by mtime).
39    #[value(name = "newer")]
40    Newer,
41}
42
43impl std::fmt::Display for OverwriteFilter {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            OverwriteFilter::Newer => write!(f, "newer"),
47        }
48    }
49}
50
51/// A destination entry the source compares against, taken from the directory manifest.
52pub struct ExistingDst<'a, M: crate::preserve::Metadata> {
53    /// The destination entry's metadata (with `size()` populated).
54    pub meta: &'a M,
55    /// Whether the destination entry is a regular file (only files are eligible for the
56    /// metadata-equality compare; a non-file means the source must send so the destination
57    /// can remove-and-replace it).
58    pub is_file: bool,
59}
60
61/// Decide whether the source may SKIP sending a file because the destination already holds a
62/// matching entry. `dst` is `None` when the destination has no entry at that name. Returns
63/// `true` to skip (the caller sends a `FileUnchanged` notification instead of file data).
64///
65/// This mirrors the destination's `process_single_file` identical/`--ignore-existing`/newer
66/// checks, so the source pre-filters exactly the files the destination would otherwise receive
67/// and drain. Skipping performs no filesystem mutation.
68pub fn skip_unchanged_send<S, D>(
69    overwrite_compare: &filecmp::MetadataCmpSettings,
70    overwrite_filter: Option<OverwriteFilter>,
71    ignore_existing: bool,
72    src: &S,
73    dst: Option<ExistingDst<'_, D>>,
74) -> bool
75where
76    S: crate::preserve::Metadata + std::fmt::Debug,
77    D: crate::preserve::Metadata + std::fmt::Debug,
78{
79    let Some(dst) = dst else {
80        return false; // nothing at the destination — must send
81    };
82    if ignore_existing {
83        return true; // any pre-existing entry (file/dir/symlink) — skip
84    }
85    if !dst.is_file {
86        return false; // dest is a non-file under --overwrite — send so dest replaces it
87    }
88    if filecmp::metadata_equal(overwrite_compare, src, dst.meta) {
89        return true; // identical per --overwrite-compare
90    }
91    if overwrite_filter == Some(OverwriteFilter::Newer) && filecmp::dest_is_newer(src, dst.meta) {
92        return true; // --overwrite-filter=newer and destination is strictly newer
93    }
94    false
95}
96
97pub use crate::delete::DeleteSettings;
98
99/// Scheduling policy for the first vacant-slot creation of a local regular file.
100#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
101pub enum LocalCopyHandoff {
102    /// Submit creation and payload copying as separate blocking jobs.
103    #[default]
104    Never,
105    /// Let a successful first vacant-slot create hand the worker to its payload.
106    Fresh,
107}
108
109impl std::fmt::Display for LocalCopyHandoff {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.write_str(match self {
112            Self::Never => "never",
113            Self::Fresh => "fresh",
114        })
115    }
116}
117
118#[derive(Debug, Clone)]
119pub struct Settings {
120    /// Reflink policy for local file data copies.
121    pub reflink: crate::copy_data::ReflinkMode,
122    /// Local create-to-copy scheduling policy; defaults to separate jobs.
123    pub local_copy_handoff: LocalCopyHandoff,
124    pub dereference: bool,
125    pub fail_early: bool,
126    pub overwrite: bool,
127    pub overwrite_compare: filecmp::MetadataCmpSettings,
128    pub overwrite_filter: Option<OverwriteFilter>,
129    pub ignore_existing: bool,
130    pub chunk_size: u64,
131    /// Skip special files (sockets, FIFOs, devices) without error.
132    pub skip_specials: bool,
133    /// Maximum remote transfer buffer and file I/O request size in bytes.
134    ///
135    /// Source buffer size, destination Tokio file I/O limits, and receiver scratch requests are
136    /// capped to the file size and isize::MAX, with a one-byte minimum. These bounds ensure
137    /// representability, not allocation success or an available-memory budget.
138    /// Individual operations can be shorter. Destination internal and outer buffers can coexist;
139    /// previously retained receiver scratch follows its independent retention limit.
140    pub remote_copy_buffer_size: usize,
141    /// filter settings for include/exclude patterns
142    pub filter: Option<crate::filter::FilterSettings>,
143    /// dry-run mode for previewing operations
144    pub dry_run: Option<crate::config::DryRunMode>,
145    /// rsync-style `--delete` settings; `None` disables deletion entirely.
146    pub delete: Option<DeleteSettings>,
147}
148
149/// Summary with the appropriate `*_skipped` counter set to 1 for the given entry kind.
150/// Special files count as `files_skipped` to match the historical mapping used
151/// when filters skip an entry (`specials_skipped` is reserved for `--skip-specials`).
152fn skipped_summary_for(kind: EntryKind) -> Summary {
153    match kind {
154        EntryKind::Dir => Summary {
155            directories_skipped: 1,
156            ..Default::default()
157        },
158        EntryKind::Symlink => Summary {
159            symlinks_skipped: 1,
160            ..Default::default()
161        },
162        EntryKind::File | EntryKind::Special => Summary {
163            files_skipped: 1,
164            ..Default::default()
165        },
166    }
167}
168
169/// Result of checking if an empty directory should be cleaned up.
170/// Used when filtering is active and a directory we created ended up empty.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub(crate) enum EmptyDirAction {
173    /// keep the directory (directly matched or no filter active)
174    Keep,
175    /// directory was only traversed, remove it
176    Remove,
177    /// dry-run mode, don't count this directory in summary
178    DryRunSkip,
179}
180
181/// Determine what to do with an empty directory when filtering is active.
182///
183/// This is called when we created a directory but nothing was copied into it
184/// (no files, symlinks, or child directories). The decision depends on whether
185/// the directory itself was directly matched by an include pattern, or if we
186/// only entered it to look for potential matches inside.
187///
188/// # Arguments
189/// * `filter` - the active filter settings (None means no filtering)
190/// * `we_created_dir` - whether we created this directory (vs it already existed)
191/// * `anything_copied` - whether any content was copied into this directory
192/// * `relative_path` - logical filter path (empty only at the user-specified root)
193/// * `is_dry_run` - whether we're in dry-run mode
194pub(crate) fn check_empty_dir_cleanup(
195    filter: Option<&crate::filter::FilterSettings>,
196    we_created_dir: bool,
197    anything_copied: bool,
198    relative_path: &std::path::Path,
199    is_dry_run: bool,
200) -> EmptyDirAction {
201    let Some(filter) = filter else {
202        return EmptyDirAction::Keep;
203    };
204    // if something was copied, keep the directory
205    if anything_copied {
206        return EmptyDirAction::Keep;
207    }
208    // if we didn't create this directory, don't remove it
209    if !we_created_dir {
210        return EmptyDirAction::Keep;
211    }
212    // never remove the root directory — it's the user-specified source
213    if relative_path.as_os_str().is_empty() {
214        return EmptyDirAction::Keep;
215    }
216    // check if directory directly matches include pattern
217    if filter.directly_matches_include(relative_path, true) {
218        return EmptyDirAction::Keep;
219    }
220    // directory was only traversed for potential matches
221    if is_dry_run {
222        EmptyDirAction::DryRunSkip
223    } else {
224        EmptyDirAction::Remove
225    }
226}
227
228#[instrument]
229pub fn is_file_type_same(md1: &std::fs::Metadata, md2: &std::fs::Metadata) -> bool {
230    let ft1 = md1.file_type();
231    let ft2 = md2.file_type();
232    ft1.is_dir() == ft2.is_dir()
233        && ft1.is_file() == ft2.is_file()
234        && ft1.is_symlink() == ft2.is_symlink()
235}
236
237#[derive(Copy, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
238pub struct Summary {
239    pub bytes_copied: u64,
240    pub files_copied: usize,
241    pub symlinks_created: usize,
242    pub directories_created: usize,
243    pub files_unchanged: usize,
244    pub symlinks_unchanged: usize,
245    pub directories_unchanged: usize,
246    pub files_skipped: usize,
247    pub symlinks_skipped: usize,
248    pub directories_skipped: usize,
249    pub specials_skipped: usize,
250    pub rm_summary: RmSummary,
251}
252
253impl std::ops::Add for Summary {
254    type Output = Self;
255    fn add(self, other: Self) -> Self {
256        Self {
257            bytes_copied: self.bytes_copied + other.bytes_copied,
258            files_copied: self.files_copied + other.files_copied,
259            symlinks_created: self.symlinks_created + other.symlinks_created,
260            directories_created: self.directories_created + other.directories_created,
261            files_unchanged: self.files_unchanged + other.files_unchanged,
262            symlinks_unchanged: self.symlinks_unchanged + other.symlinks_unchanged,
263            directories_unchanged: self.directories_unchanged + other.directories_unchanged,
264            files_skipped: self.files_skipped + other.files_skipped,
265            symlinks_skipped: self.symlinks_skipped + other.symlinks_skipped,
266            directories_skipped: self.directories_skipped + other.directories_skipped,
267            specials_skipped: self.specials_skipped + other.specials_skipped,
268            rm_summary: self.rm_summary + other.rm_summary,
269        }
270    }
271}
272
273impl std::fmt::Display for Summary {
274    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
275        write!(
276            f,
277            "copy:\n\
278            -----\n\
279            bytes copied: {}\n\
280            files copied: {}\n\
281            symlinks created: {}\n\
282            directories created: {}\n\
283            files unchanged: {}\n\
284            symlinks unchanged: {}\n\
285            directories unchanged: {}\n\
286            files skipped: {}\n\
287            symlinks skipped: {}\n\
288            directories skipped: {}\n\
289            specials skipped: {}\n\
290            \n\
291            delete:\n\
292            -------\n\
293            {}",
294            bytesize::ByteSize(self.bytes_copied),
295            self.files_copied,
296            self.symlinks_created,
297            self.directories_created,
298            self.files_unchanged,
299            self.symlinks_unchanged,
300            self.directories_unchanged,
301            self.files_skipped,
302            self.symlinks_skipped,
303            self.directories_skipped,
304            self.specials_skipped,
305            &self.rm_summary,
306        )
307    }
308}
309
310/// Public entry point for copy operations.
311///
312/// The local copy walk is fd-based: the source and destination roots are opened relative to
313/// their parent directories and payload operations use file-descriptor-relative syscalls
314/// (see [`crate::safedir`]). Held parents prevent full-path redirection and contain each by-name
315/// operation to its intended directory. `--dereference` still resolves symlinks by path
316/// (`canonicalize`) and is not hardened. Read-only leaf `--dry-run --ignore-existing` destination
317/// probes also re-resolve paths: default mode may observe a redirected preview, while strict mode
318/// rejects intermediate symlinks via `openat2` and a no-follow final-component probe.
319pub async fn copy(
320    prog_track: &'static progress::Progress,
321    src: &std::path::Path,
322    dst: &std::path::Path,
323    settings: &Settings,
324    preserve: &preserve::Settings,
325    is_fresh: bool,
326) -> Result<Summary, Error> {
327    CopySession::default()
328        .copy(prog_track, src, dst, settings, preserve, is_fresh)
329        .await
330}
331
332/// Shared input/output identities for all source operands of one local copy invocation.
333/// Clones retain the same registry, including when strict-mode roots run sequentially.
334#[derive(Clone)]
335pub struct CopySession {
336    overlap: Arc<safedir::overlap::DirectoryOverlap>,
337    protection: Arc<crate::input_protection::InputProtection>,
338}
339
340impl Default for CopySession {
341    fn default() -> Self {
342        let overlap = Arc::new(safedir::overlap::DirectoryOverlap::default());
343        Self {
344            protection: Arc::new(crate::input_protection::InputProtection::new(Arc::clone(
345                &overlap,
346            ))),
347            overlap,
348        }
349    }
350}
351
352/// One explicit operand prepared without retaining descriptors or scanning its descendants.
353/// Keep every prepared operand alive until dispatch to protect inputs that have not started yet.
354pub struct PreparedCopy {
355    src: PathBuf,
356    dst: PathBuf,
357    settings: Settings,
358    destination: DestinationContext,
359}
360
361fn root_is_selected(settings: &Settings, name: &OsStr, kind: EntryKind) -> bool {
362    settings.filter.as_ref().is_none_or(|filter| {
363        matches!(
364            filter.should_include_root_item(std::path::Path::new(name), kind == EntryKind::Dir),
365            crate::filter::FilterResult::Included,
366        )
367    })
368}
369
370impl CopySession {
371    /// Register an explicit input root before any operand can mutate the destination.
372    /// This performs only root lookups, and is needed only for destructive local operations.
373    pub async fn prepare(
374        &self,
375        src: &std::path::Path,
376        dst: &std::path::Path,
377        settings: &Settings,
378    ) -> Result<PreparedCopy, Error> {
379        if settings.dereference && safedir::strict_operand_resolution() {
380            return Err(Error::new(
381                anyhow!("--dereference cannot be combined with strict operand resolution"),
382                Default::default(),
383            ));
384        }
385        let mut destination = DestinationContext::with_registry(
386            src,
387            dst,
388            Arc::clone(&self.overlap),
389            Arc::clone(&self.protection),
390        );
391        if settings.overwrite || settings.delete.is_some() {
392            let permit = throttle::open_file_permit().await;
393            safedir::with_fd_admission(permit.admission(), async {
394                let operand = crate::walk::split_root_operand(src).await?;
395                let parent =
396                    safedir::open_preview_operand_parent(&operand.parent, congestion::Side::Source)
397                        .await?;
398                let entry = parent.child(&operand.name).await?;
399                if !root_is_selected(settings, &operand.name, entry.kind()) {
400                    return Ok::<_, anyhow::Error>(());
401                }
402                destination
403                    .record_root(&parent, &operand.name, &entry, src)
404                    .await?;
405                if settings.dereference && entry.kind() == EntryKind::Symlink {
406                    let target = crate::walk::run_metadata_probed(
407                        congestion::Side::Source,
408                        congestion::MetadataOp::Stat,
409                        tokio::fs::canonicalize(src),
410                    )
411                    .await?;
412                    let target = crate::walk::split_root_operand(&target).await?;
413                    let parent = safedir::open_preview_operand_parent(
414                        &target.parent,
415                        congestion::Side::Source,
416                    )
417                    .await?;
418                    let entry = parent.child(&target.name).await?;
419                    // dereference re-enters root filtering under the referent's own basename
420                    if !root_is_selected(settings, &target.name, entry.kind()) {
421                        return Ok(());
422                    }
423                    destination
424                        .record_root(&parent, &target.name, &entry, &target.display)
425                        .await?;
426                    if entry.kind() == EntryKind::Dir {
427                        destination.reserve_roots(&[entry.meta()])?;
428                    }
429                } else if entry.kind() == EntryKind::Dir {
430                    destination.reserve_roots(&[entry.meta()])?;
431                }
432                Ok(())
433            })
434            .await
435            .with_context(|| format!("cannot prepare input {src:?}"))
436            .map_err(|error| Error::new(error, Default::default()))?;
437        }
438        Ok(PreparedCopy {
439            src: src.to_owned(),
440            dst: dst.to_owned(),
441            settings: settings.clone(),
442            destination,
443        })
444    }
445
446    /// Copy one operand while retaining the other operands' directory identities.
447    pub async fn copy(
448        &self,
449        prog_track: &'static progress::Progress,
450        src: &std::path::Path,
451        dst: &std::path::Path,
452        settings: &Settings,
453        preserve: &preserve::Settings,
454        is_fresh: bool,
455    ) -> Result<Summary, Error> {
456        self.prepare(src, dst, settings)
457            .await?
458            .copy(prog_track, preserve, is_fresh)
459            .await
460    }
461}
462
463impl PreparedCopy {
464    /// Execute a prepared operand, retaining its tentative root claim until admission or failure.
465    #[instrument(name = "copy", skip(self, prog_track, preserve), fields(src = ?self.src, dst = ?self.dst))]
466    pub async fn copy(
467        self,
468        prog_track: &'static progress::Progress,
469        preserve: &preserve::Settings,
470        is_fresh: bool,
471    ) -> Result<Summary, Error> {
472        crate::timing_scope!("local.copy")
473            .measure(copy_root_admitted(
474                prog_track,
475                &self.src,
476                &self.dst,
477                &self.settings,
478                preserve,
479                is_fresh,
480                self.destination,
481                None,
482            ))
483            .await
484    }
485}
486
487/// Path-based root setup with transferable leaf admission.
488///
489/// Normal public calls arrive without a guard and acquire before opening either operand parent or
490/// performing a strict fd-based root filter probe. `--dereference` transfers its spawn-loop guard
491/// here, so a wide set of symlinks cannot fan out into unadmitted target walks. The shared driver
492/// releases the guard if authoritative target classification proves it is a directory.
493#[instrument(skip(prog_track, settings, preserve, open_file_guard))]
494#[allow(clippy::too_many_arguments)]
495async fn copy_root_admitted(
496    prog_track: &'static progress::Progress,
497    src: &std::path::Path,
498    dst: &std::path::Path,
499    settings: &Settings,
500    preserve: &preserve::Settings,
501    is_fresh: bool,
502    destination: DestinationContext,
503    open_file_guard: Option<throttle::OpenFileGuard>,
504) -> Result<Summary, Error> {
505    if settings.dereference && safedir::strict_operand_resolution() {
506        return Err(Error::new(
507            anyhow!("--dereference cannot be combined with strict operand resolution"),
508            Default::default(),
509        ));
510    }
511    let open_file_guard = match open_file_guard {
512        Some(guard) => guard,
513        None => throttle::open_file_permit().await,
514    };
515    enum CopyRootSetup {
516        Complete(Summary),
517        Ready {
518            src_operand: crate::walk::RootOperand,
519            src_parent: Arc<Dir>,
520            dst_parent: Option<Arc<Dir>>,
521            preview_parent: Option<destination::PreviewParent>,
522        },
523    }
524    let setup_admission = open_file_guard.admission();
525    let setup = safedir::with_fd_admission(setup_admission, async {
526        // Source: decompose via the shared helper so `.`/`..` operands (e.g. `rcp . dst`, `rcp src/..
527        // dst`) are canonicalized to a real directory + basename instead of being rejected; `/` is still
528        // rejected. (The helper also maps a single-component relative path's empty parent to ".".)
529        let src_operand = crate::walk::split_root_operand(src)
530            .await
531            .map_err(|err| Error::new(err, Default::default()))?;
532        let src_parent_path = src_operand.parent.as_path();
533        let src_name = src_operand.name.as_os_str();
534        let src = src_operand.display.as_path();
535        // The destination's parent path, split leniently for the up-front strict validation below (a
536        // `.`/`..`/`/` destination has no distinct parent+name; the authoritative split — which rejects
537        // such a destination — runs AFTER the filter, preserving default-mode ordering so a filtered-out
538        // source still skips cleanly).
539        let dst_parent_path_opt: Option<&std::path::Path> = match (dst.parent(), dst.file_name()) {
540            (Some(parent), Some(_)) if parent.as_os_str().is_empty() => {
541                Some(std::path::Path::new("."))
542            }
543            (Some(parent), Some(_)) => Some(parent),
544            _ => None,
545        };
546        // Under strict operand resolution (--require-toctou-safe), resolve BOTH operand parents UP
547        // FRONT — before the source root-filter early-return, unconditionally, in every mode (real and
548        // dry-run) — with openat2 RESOLVE_NO_SYMLINKS (O_PATH for the preview destination parent).
549        // this single open per operand is the strict validation: a symlink in any directory component of the source OR destination
550        // path fails closed with ELOOP here, so no filter/dry-run/overwrite branch downstream can let a
551        // symlinked prefix through. The held fds are reused below (source classify + walk; destination
552        // walk). On the DEFAULT path this is skipped: the filter check runs first over a path stat, so
553        // an excluded root under an execute-only (0111, searchable-not-readable) parent skips cleanly
554        // without requiring parent read.
555        let strict = crate::safedir::strict_operand_resolution();
556        let strict_src_parent: Option<Arc<Dir>> = if strict {
557            let parent = Dir::open_parent_dir(src_parent_path, congestion::Side::Source)
558                .await
559                .with_context(|| {
560                    format!("cannot open source parent directory {:?}", src_parent_path)
561                })
562                .map_err(|err| Error::new(err, Default::default()))?;
563            // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below here).
564            Some(Arc::new(parent.into_tree()))
565        } else {
566            None
567        };
568        let preview_parent = if strict && settings.dry_run.is_some() {
569            match dst_parent_path_opt {
570                Some(path) => Some(
571                    destination::PreviewParent::open(path)
572                        .await
573                        .with_context(|| {
574                            format!("cannot open destination parent directory {path:?}")
575                        })
576                        .map_err(|err| Error::new(err, Default::default()))?,
577                ),
578                None => None,
579            }
580        } else {
581            None
582        };
583        let strict_dst_parent: Option<Arc<Dir>> =
584            match (strict && settings.dry_run.is_none(), dst_parent_path_opt) {
585                (true, Some(dst_parent_path)) => {
586                    match Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination).await
587                    {
588                        Ok(parent) => Some(Arc::new(parent.into_tree())),
589                        // a missing or invalid parent can still belong to a filtered-out root.
590                        // defer its functional error until after filtering; reject symlinks here.
591                        Err(err)
592                            if err.kind() == std::io::ErrorKind::NotFound
593                                || err.raw_os_error() == Some(libc::ENOTDIR) =>
594                        {
595                            None
596                        }
597                        Err(err) => {
598                            return Err(Error::new(
599                                anyhow::Error::new(err).context(format!(
600                                    "cannot open destination parent directory {dst_parent_path:?}"
601                                )),
602                                Default::default(),
603                            ));
604                        }
605                    }
606                }
607                // default mode, or a degenerate destination (rejected by the authoritative split below)
608                _ => None,
609            };
610        // check filter for top-level source (files, directories, and symlinks)
611        if let Some(ref filter) = settings.filter {
612            let (kind, is_dir) = match &strict_src_parent {
613                // strict: classify via the held parent fd (O_NOFOLLOW), never by path
614                Some(parent) => {
615                    let root_handle = parent
616                        .child(src_name)
617                        .await
618                        .with_context(|| format!("failed reading metadata from src: {:?}", &src))
619                        .map_err(|err| Error::new(err, Default::default()))?;
620                    (root_handle.kind(), root_handle.kind() == EntryKind::Dir)
621                }
622                None => {
623                    let src_metadata = crate::walk::run_metadata_probed(
624                        congestion::Side::Source,
625                        congestion::MetadataOp::Stat,
626                        tokio::fs::symlink_metadata(src),
627                    )
628                    .await
629                    .with_context(|| format!("failed reading metadata from src: {:?}", &src))
630                    .map_err(|err| Error::new(err, Default::default()))?;
631                    (
632                        EntryKind::from_metadata(&src_metadata),
633                        src_metadata.is_dir(),
634                    )
635                }
636            };
637            let result = filter.should_include_root_item(std::path::Path::new(src_name), is_dir);
638            match result {
639                crate::filter::FilterResult::Included => {}
640                result => {
641                    if let Some(mode) = settings.dry_run {
642                        crate::dry_run::report_skip(src, &result, mode, kind.label_long());
643                    }
644                    kind.inc_skipped(prog_track);
645                    return Ok(CopyRootSetup::Complete(skipped_summary_for(kind)));
646                }
647            }
648        }
649        // Source parent for the walk: reuse the strict-validated fd, or open it following symlinks
650        // (default mode; the trusted prefix up to and including the operand's container).
651        let src_parent = match strict_src_parent {
652            Some(parent) => parent,
653            None => {
654                let parent = Dir::open_parent_dir(src_parent_path, congestion::Side::Source)
655                    .await
656                    .with_context(|| {
657                        format!("cannot open source parent directory {:?}", src_parent_path)
658                    })
659                    .map_err(|err| Error::new(err, Default::default()))?;
660                Arc::new(parent.into_tree())
661            }
662        };
663        // One `listxattr` on the source ROOT per run — a constant, not a per-entry probe — warning that
664        // a source root carrying an ACL is about to be copied by settings that drop it. Skipped
665        // entirely by a copy that asked for no preservation at all, once ACLs are preserved for both
666        // kinds, and after the first root of the run.
667        crate::safedir::warn_if_root_acl_unpreserved_at(
668            &src_parent,
669            src_name,
670            src,
671            crate::safedir::RootAclNotice::for_preserve(preserve),
672        )
673        .await;
674        // Authoritative destination split (runs AFTER the filter, preserving default-mode ordering): a
675        // `.`/`..`/`/` destination is not a meaningful copy target, and rejecting it avoids clobbering
676        // the cwd. empty parent (a single-component relative path) means the current directory.
677        let (Some(dst_parent_path), Some(_dst_name)) = (dst.parent(), dst.file_name()) else {
678            return Err(Error::new(
679                anyhow!(
680                    "copy destination {:?} has no parent directory or file name",
681                    dst
682                ),
683                Default::default(),
684            ));
685        };
686        let dst_parent_path = if dst_parent_path.as_os_str().is_empty() {
687            std::path::Path::new(".")
688        } else {
689            dst_parent_path
690        };
691        // dry-run has no writable destination parent (the parent may not even exist). delete
692        // previews open separate read-only directory handles before descent. `dst_parent == None`
693        // suppresses mutation. In a real copy, reuse the strict-validated parent, or open it
694        // following symlinks (default mode; `rcp file symlink_to_dir/out` copies into the real dir).
695        let dst_parent = if settings.dry_run.is_some() {
696            None
697        } else {
698            match strict_dst_parent {
699                Some(parent) => Some(parent),
700                None => {
701                    let dir = Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination)
702                        .await
703                        .with_context(|| {
704                            format!(
705                                "cannot open destination parent directory {:?}",
706                                dst_parent_path
707                            )
708                        })
709                        .map_err(|err| Error::new(err, Default::default()))?;
710                    Some(Arc::new(dir.into_tree()))
711                }
712            }
713        };
714        Ok(CopyRootSetup::Ready {
715            src_operand,
716            src_parent,
717            dst_parent,
718            preview_parent,
719        })
720    })
721    .await?;
722    let (src_operand, src_parent, dst_parent, preview_parent) = match setup {
723        CopyRootSetup::Complete(summary) => return Ok(summary),
724        CopyRootSetup::Ready {
725            src_operand,
726            src_parent,
727            dst_parent,
728            preview_parent,
729        } => (src_operand, src_parent, dst_parent, preview_parent),
730    };
731    run_copy_root(
732        prog_track,
733        &src_parent,
734        dst_parent,
735        &src_operand.name,
736        &src_operand.display,
737        dst,
738        settings,
739        preserve,
740        is_fresh,
741        destination.with_preview_parent(preview_parent),
742        EntryAdmission::Held(LeafPermit::OpenFile(open_file_guard)).into(),
743    )
744    .await
745}
746
747/// Classification state accepted by copy's fd-relative root boundary.
748///
749/// Ordinary roots classify under admission; tests can also supply an exact admitted root whose
750/// root filter decision is pending. A filtered entry is rlink's exact handle after filtering in
751/// its logical namespace, so the shared driver must consume it directly rather than re-filter it
752/// under a delegated physical basename. Regular-file and directory payload opens remain fd-relative
753/// by parent and name, preserving their existing same-type replacement semantics; symlink payload
754/// stays pinned to the admitted handle. Ordinary unclassified entries retain the existing
755/// classify-under-admission path. Only the already-filtered variant carries a delegated logical
756/// base: ordinary roots always have empty coordinates and use root-item filtering.
757enum CopyEntryAdmission {
758    Unclassified(EntryAdmission),
759    #[cfg(test)]
760    Admitted(AdmittedEntry),
761    Filtered {
762        entry: AdmittedEntry,
763        filter_base: PathBuf,
764    },
765}
766
767impl From<EntryAdmission> for CopyEntryAdmission {
768    fn from(admission: EntryAdmission) -> Self {
769        Self::Unclassified(admission)
770    }
771}
772
773/// Copy a single entry `name` (within `src_parent`) into `dst_parent`, using held directory
774/// handles for the payload handoff. This is the fd-based delegation entry point for
775/// `rlink`: when an entry must be COPIED rather than hard-linked (a file that changed vs the
776/// update tree, a symlink, a type-mismatch, or an update-only entry), `link` hands its already-open
777/// parent `Dir`s plus the entry `name` here, so the copy inherits the same intermediate-component
778/// TOCTOU safety the link walk has. The path-based dereference and read-only preview exceptions
779/// documented on [`copy`] still apply.
780///
781/// `admission` must be the exact entry already filtered by rlink. `src_path` is its source display
782/// path, also used by `--dereference`. `dst_root` is the original rlink destination root, and
783/// `filter_base` is the entry's logical path relative to that root and the original filter root.
784/// A nonempty base must end in `name`; an empty base uses `dst_root`'s basename for the destination.
785/// This entry point always seeds that coordinate and bypasses root filtering. Its descendants use
786/// the same coordinate for destination reconstruction, filtering, and deletion.
787/// `destination` independently carries the held preview parent or its known absence, so
788/// preview authority never comes from a display or filter path. `dst_parent` is absent only in dry-run.
789#[instrument(skip(prog_track, src_parent, dst_parent, settings, preserve, admission))]
790#[allow(clippy::too_many_arguments)]
791pub(crate) async fn copy_child(
792    prog_track: &'static progress::Progress,
793    src_parent: &Arc<Dir>,
794    dst_parent: Option<&Arc<Dir>>,
795    name: &OsStr,
796    src_path: &std::path::Path,
797    dst_root: &std::path::Path,
798    filter_base: &std::path::Path,
799    settings: &Settings,
800    preserve: &preserve::Settings,
801    is_fresh: bool,
802    destination: DestinationContext,
803    admission: AdmittedEntry,
804) -> Result<Summary, Error> {
805    // nonempty delegated paths name an entry within the original destination root
806    debug_assert!(filter_base.as_os_str().is_empty() || filter_base.file_name() == Some(name));
807    run_copy_root(
808        prog_track,
809        src_parent,
810        dst_parent.map(Arc::clone),
811        name,
812        src_path,
813        dst_root,
814        settings,
815        preserve,
816        is_fresh,
817        destination,
818        CopyEntryAdmission::Filtered {
819            entry: admission,
820            filter_base: filter_base.to_path_buf(),
821        },
822    )
823    .await
824}
825
826/// The copy walk's [`WalkVisitor`]: holds the run-constant state shared by every entry and maps
827/// each per-entry decision onto the generic [`crate::walk_driver`] driver.
828///
829/// The driver owns enumeration, the leaf-permit lifecycle, spawning, the single
830/// drop-before-recurse site, and the error fold; this visitor supplies copy's per-entry bodies
831/// (`copy_file_fd`, `copy_symlink_fd`, `resolve_dst_dir`, `remove_existing`, the empty-dir cleanup,
832/// `--delete` prune, and directory metadata). The destination tree is threaded as an *inherited
833/// attribute* through [`Self::DirContext`] (each directory's children read their destination parent
834/// from `parent_ctx`), so the single-tree driver carries copy's second tree without modeling it.
835struct CopyVisitor {
836    prog_track: &'static progress::Progress,
837    /// The destination root operand. The root's destination basename comes from here (it may differ
838    /// from the source basename, e.g. copying `foo` → `bar`); nested entries reuse the source name.
839    /// The *source* root needs no field: an entry's source real path is the driver-maintained
840    /// `EntryCx::real_path` (seeded with the source root in [`run_copy_root`]).
841    dst_root: PathBuf,
842    /// The root's preview authority: the original destination operand for a public copy, or an
843    /// inherited held parent/absence for a delegated copy. Independent of filter coordinates.
844    destination: DestinationContext,
845    settings: Settings,
846    preserve: preserve::Settings,
847    /// The opened top-level destination parent directory (`None` in dry-run). Seeds the
848    /// [`Self::DirContext`] chain via [`WalkVisitor::root_dir_context`].
849    dst_parent: Option<Arc<Dir>>,
850    /// The initial freshness for the root entry's containing directory.
851    root_is_fresh: bool,
852}
853
854/// Inherited per-directory context: the destination parent directory for one level plus its
855/// freshness. `dst_dir == None` is the dry-run signal threaded throughout the walk (no destination
856/// mutation). `destination` independently carries read-only preview authority. Each child
857/// reads its destination parents from here rather than the driver knowing a second tree exists.
858#[derive(Clone)]
859struct CopyDirContext {
860    dst_dir: Option<Arc<Dir>>,
861    destination: DestinationContext,
862    is_fresh: bool,
863}
864
865/// State threaded from [`WalkVisitor::dir_pre`] to [`WalkVisitor::dir_post`] in the same task:
866/// everything `dir_post` needs to run empty-dir cleanup, `--delete` prune, and apply directory
867/// metadata.
868struct CopyDirState {
869    /// The directory actually enumerated, retained for live source checks during deletion.
870    src_dir: Arc<Dir>,
871    /// Read-only destination held from pre-order in dry-run deletion previews.
872    preview_dir: Option<Arc<Dir>>,
873    /// The destination directory just created/reused (`None` in dry-run).
874    dst_dir: Option<Arc<Dir>>,
875    /// The destination parent directory and this directory's destination name within it — used to
876    /// remove an empty directory fd-relative (`dst_parent.rmdir_at(dst_name)`). `None` in dry-run.
877    dst_parent: Option<Arc<Dir>>,
878    dst_name: OsString,
879    /// Whether we created the destination directory (vs. reused an existing one).
880    we_created: bool,
881    /// What the strict-mode lockdown must put back at finalize (original owner + original ACLs),
882    /// `Some` iff this reused directory was locked down. See [`DirSlot::reused_lock`].
883    reused_lock: Option<safedir::ReusedDirLock>,
884    /// Preservation state captured together before walking this held input.
885    snapshot: SourceSnapshot,
886    /// The `directories_created`/`directories_unchanged` contribution from resolving this
887    /// directory's destination, folded into the final summary.
888    base: Summary,
889}
890
891impl CopyVisitor {
892    /// The destination real path for the entry described by `cx` (`dst_root.join(rel_path)`, or the
893    /// root verbatim when `rel_path` is empty — joining an empty `rel_path` would append a trailing
894    /// separator that `canonicalize`/ENOTDIR-sensitive paths reject).
895    fn dst_path_for(&self, cx: &EntryCx) -> PathBuf {
896        crate::walk::join_rel(&self.dst_root, &cx.rel_path)
897    }
898
899    /// The destination entry's name within its parent. For nested entries this equals the source
900    /// `cx.name`, but for the root the source and destination basenames may differ (e.g. copying
901    /// `foo` → `bar`), so the root's destination name comes from `dst_root`.
902    // copy's `Error` carries a large `Summary`; Clippy's `result_large_err` measures only the
903    // `Err` type, independently of the borrowed success value. the error arm is
904    // unreachable in practice (`copy_root_admitted` pre-validates the root's file name and a
905    // delegated `copy_child` root path always has one) — keep it as defense-in-depth.
906    #[allow(clippy::result_large_err)]
907    fn dst_name_for<'a>(&'a self, cx: &'a EntryCx) -> Result<&'a OsStr, Error> {
908        if cx.rel_path.as_os_str().is_empty() {
909            self.dst_root.file_name().ok_or_else(|| {
910                Error::new(
911                    anyhow!("copy destination {:?} has no file name", &self.dst_root),
912                    Default::default(),
913                )
914            })
915        } else {
916            Ok(&cx.name)
917        }
918    }
919
920    /// rsync-style `--delete` prune for one finished directory: remove destination entries with no
921    /// source counterpart. Runs only when `--delete` was requested AND every observed child
922    /// succeeded — skipping the prune on any error (deleting based on a run that did not fully
923    /// succeed could remove data unexpectedly). Prune enumerates and removes through the
924    /// destination's own pinned directory fd, so a concurrent symlink swap cannot redirect it outside
925    /// the destination.
926    ///
927    /// Folds the successful or partial prune `RmSummary` into `copy_summary` and returns any scan
928    /// or prune error. [`Self::dir_post`] decides whether to fail early or finalize the directory
929    /// before surfacing that error. The typed keep-set arrives only from successful exact
930    /// collection; failed traversal never enters here.
931    async fn prune_finished_dir(
932        &self,
933        copy_summary: &mut Summary,
934        keep_set: &crate::delete::DeleteKeepSet<&[OsString]>,
935        src_dir: &Arc<Dir>,
936        prune_dir: &Arc<Dir>,
937        filter_path: &std::path::Path,
938    ) -> Result<(), anyhow::Error> {
939        let keep_set = keep_set.hashed();
940        crate::delete::prune_and_fold(
941            self.prog_track,
942            prune_dir,
943            crate::delete::DeleteSources::Single(src_dir),
944            filter_path,
945            &keep_set,
946            self.settings.filter.as_ref(),
947            self.settings.fail_early,
948            self.settings.dry_run,
949            &mut copy_summary.rm_summary,
950            Some(self.destination.protection()),
951        )
952        .await
953    }
954
955    /// Finish a directory after its children and `--delete` prune have run: when filtering left it
956    /// empty, clean it up (or, in dry-run, suppress its would-be-created count); otherwise apply the
957    /// source directory's metadata to the destination through its own held fd. A collected
958    /// `child_error` always takes precedence and is surfaced here (even when the empty directory was
959    /// pruned), so a failed child copy can never be reported as overall success.
960    async fn finalize_dir(&self, fin: FinalizeDir, cx: &EntryCx) -> Result<Summary, Error> {
961        let FinalizeDir {
962            mut copy_summary,
963            child_error,
964            dst_dir,
965            dst_parent,
966            dst_name,
967            src_meta,
968            src_acls,
969            we_created,
970            reused_lock,
971        } = fin;
972        let src_path = &cx.real_path;
973        let dst_path = self.dst_path_for(cx);
974        // when filtering is active and we created this directory, check whether anything was
975        // actually copied into it. if not, we may need to clean up the empty directory.
976        let this_dir_count = usize::from(we_created);
977        let child_dirs_created = copy_summary
978            .directories_created
979            .saturating_sub(this_dir_count);
980        let anything_copied = copy_summary.files_copied > 0
981            || copy_summary.symlinks_created > 0
982            || child_dirs_created > 0;
983
984        match check_empty_dir_cleanup(
985            self.settings.filter.as_ref(),
986            we_created,
987            anything_copied,
988            &cx.rel_path,
989            self.settings.dry_run.is_some(),
990        ) {
991            EmptyDirAction::Keep => { /* proceed with metadata application */ }
992            EmptyDirAction::DryRunSkip => {
993                tracing::debug!(
994                    "dry-run: directory {:?} would not be created (nothing to copy inside)",
995                    dst_path
996                );
997                copy_summary.directories_created = 0;
998                // the directory itself is not created, but a child error collected during the walk
999                // must still surface — otherwise a traversal-only directory whose only child FAILED
1000                // becomes "empty", gets skipped here, and the failed copy is reported as success.
1001                return match child_error {
1002                    Some(child_error) => Err(Error::new(child_error, copy_summary)),
1003                    None => Ok(copy_summary),
1004                };
1005            }
1006            EmptyDirAction::Remove => {
1007                tracing::debug!(
1008                    "directory {:?} has nothing to copy inside, removing empty directory",
1009                    dst_path
1010                );
1011                // remove the empty directory fd-relative, through its parent dir handle:
1012                // `rmdir_at` operates on `dst_name` within the held `dst_parent` fd (never by path)
1013                // and only succeeds on an empty directory, so it is contained to `dst_parent` and
1014                // cannot be redirected. our still-open fd to the directory itself simply detaches.
1015                // `dst_parent` is always Some here: it is None only in dry-run, where this arm is
1016                // unreachable (`check_empty_dir_cleanup` returns `DryRunSkip`, not `Remove`).
1017                if let Some(parent) = &dst_parent {
1018                    self.destination
1019                        .protection()
1020                        .check_child(parent, &dst_name, &dst_path)
1021                        .await
1022                        .map_err(|error| Error::new(error.into(), copy_summary))?;
1023                }
1024                let rmdir_result = match &dst_parent {
1025                    Some(dst_parent) => dst_parent.rmdir_at(&dst_name).await,
1026                    None => {
1027                        crate::walk::run_metadata_probed(
1028                            congestion::Side::Destination,
1029                            congestion::MetadataOp::RmDir,
1030                            tokio::fs::remove_dir(&dst_path),
1031                        )
1032                        .await
1033                    }
1034                };
1035                match rmdir_result {
1036                    Ok(()) => {
1037                        copy_summary.directories_created = 0;
1038                        // the empty directory is removed, but a child error collected during the
1039                        // walk must still surface — otherwise a traversal-only directory whose only
1040                        // child FAILED becomes "empty", is removed here, and the failed copy is
1041                        // reported as success.
1042                        return match child_error {
1043                            Some(child_error) => Err(Error::new(child_error, copy_summary)),
1044                            None => Ok(copy_summary),
1045                        };
1046                    }
1047                    Err(err) => {
1048                        tracing::debug!(
1049                            "failed to remove empty directory {:?}: {:#}, keeping",
1050                            dst_path,
1051                            &err
1052                        );
1053                        // fall through to apply metadata.
1054                    }
1055                }
1056            }
1057        }
1058        // apply directory metadata regardless of whether all children copied successfully (the
1059        // directory itself was created/opened in dir_pre). skipped in dry-run (no directory
1060        // exists). a child error takes precedence over a metadata error (matching the old tail:
1061        // log the metadata error, return the child error).
1062        tracing::debug!("set 'dst' directory metadata");
1063        let metadata_result = match &dst_dir {
1064            // For a reused directory locked down under strict mode, `set_reused_dir_metadata_fd`
1065            // restores the original owner component-wise — so no transient window hands the directory
1066            // back to a hostile prior owner — then applies the source metadata (mode last, so
1067            // setgid/special bits survive) and puts back the ACLs the lockdown stripped.
1068            // `reused_lock` is None for fresh dirs / non-strict reuse.
1069            Some(dst_dir) => {
1070                safedir::set_reused_dir_metadata_fd(
1071                    &self.preserve,
1072                    &src_meta,
1073                    src_acls.as_ref(),
1074                    reused_lock,
1075                    dst_dir,
1076                )
1077                .await
1078            }
1079            None => Ok(()),
1080        };
1081        if let Some(child_error) = child_error {
1082            if let Err(metadata_err) = metadata_result {
1083                tracing::error!(
1084                    "copy: {:?} -> {:?} failed to set directory metadata: {:#}",
1085                    src_path,
1086                    dst_path,
1087                    &metadata_err
1088                );
1089            }
1090            return Err(Error::new(child_error, copy_summary));
1091        }
1092        // no child failures, so the metadata error is the primary error.
1093        metadata_result
1094            .with_context(|| format!("failed setting directory metadata on {:?}", dst_path))
1095            .map_err(|err| Error::new(err, copy_summary))?;
1096        Ok(copy_summary)
1097    }
1098}
1099
1100/// The owned per-directory state [`CopyVisitor::dir_post`] hands to [`CopyVisitor::finalize_dir`]
1101/// after the child summaries are folded and `--delete` pruning has run: the accumulated summary, any
1102/// collected child error to surface, and this directory's destination handles / classification.
1103struct FinalizeDir {
1104    copy_summary: Summary,
1105    child_error: Option<anyhow::Error>,
1106    dst_dir: Option<Arc<Dir>>,
1107    dst_parent: Option<Arc<Dir>>,
1108    dst_name: OsString,
1109    src_meta: FileMeta,
1110    src_acls: Option<safedir::Acls>,
1111    we_created: bool,
1112    reused_lock: Option<safedir::ReusedDirLock>,
1113}
1114
1115async fn filter_and_process_admitted_root(
1116    visitor: Arc<CopyVisitor>,
1117    root_cx: EntryCx,
1118    root_ctx: CopyDirContext,
1119    entry: AdmittedEntry,
1120    filter: &crate::filter::FilterSettings,
1121) -> Result<Summary, Error> {
1122    let kind = entry.kind();
1123    let filter_result = filter.should_include_root_item(
1124        std::path::Path::new(root_cx.name.as_os_str()),
1125        kind == EntryKind::Dir,
1126    );
1127    if !matches!(filter_result, crate::filter::FilterResult::Included) {
1128        if let Some(mode) = visitor.settings.dry_run {
1129            crate::dry_run::report_skip(
1130                &root_cx.real_path,
1131                &filter_result,
1132                mode,
1133                kind.label_long(),
1134            );
1135        }
1136        kind.inc_skipped(visitor.prog_track);
1137        return Ok(skipped_summary_for(kind));
1138    }
1139    process_admitted_entry(visitor, root_cx, root_ctx, entry).await
1140}
1141
1142/// Build the [`CopyVisitor`] for one copy operation and process the root entry through the generic
1143/// driver. Shared by [`copy`] (which acquires root admission before parent setup)
1144/// and [`copy_child`] (rlink's already-filtered fd-based delegation entry point).
1145/// The root is processed exactly like a nested child via
1146/// [`process_entry`] or [`process_admitted_entry`], then dispatched to `visit_leaf`
1147/// (file/symlink/special) or `dir_pre`/recurse/`dir_post` (directory).
1148#[allow(clippy::too_many_arguments)]
1149async fn run_copy_root(
1150    prog_track: &'static progress::Progress,
1151    src_parent: &Arc<Dir>,
1152    dst_parent: Option<Arc<Dir>>,
1153    name: &OsStr,
1154    src_root: &std::path::Path,
1155    dst_root: &std::path::Path,
1156    settings: &Settings,
1157    preserve: &preserve::Settings,
1158    is_fresh: bool,
1159    destination: DestinationContext,
1160    admission: CopyEntryAdmission,
1161) -> Result<Summary, Error> {
1162    let visitor = Arc::new(CopyVisitor {
1163        prog_track,
1164        dst_root: dst_root.to_path_buf(),
1165        destination,
1166        settings: settings.clone(),
1167        preserve: *preserve,
1168        dst_parent,
1169        root_is_fresh: is_fresh,
1170    });
1171    // ordinary roots always use root-item filtering; only the already-filtered delegated
1172    // variant below seeds the shared filtering and destination coordinate
1173    let root_cx = EntryCx::root(
1174        Arc::clone(src_parent),
1175        name.to_owned(),
1176        src_root.to_path_buf(),
1177        prog_track,
1178    );
1179    let root_ctx = visitor.root_dir_context();
1180    match admission {
1181        CopyEntryAdmission::Unclassified(admission) => {
1182            if let Some(filter) = visitor.filter().cloned() {
1183                let admission = crate::walk::ensure_entry_admission(
1184                    visitor.permit_kind(),
1185                    admission.require_admission(),
1186                )
1187                .await;
1188                let entry = crate::walk::classify_admitted_entry(
1189                    &root_cx.parent,
1190                    &root_cx.name,
1191                    admission.into_permit(),
1192                )
1193                .await
1194                .with_context(|| format!("failed reading metadata from {:?}", &root_cx.real_path))
1195                .map_err(|err| Error::new(err, Default::default()))?;
1196                return filter_and_process_admitted_root(
1197                    visitor, root_cx, root_ctx, entry, &filter,
1198                )
1199                .await;
1200            }
1201            process_entry(visitor, root_cx, root_ctx, admission).await
1202        }
1203        #[cfg(test)]
1204        CopyEntryAdmission::Admitted(entry) => {
1205            if let Some(filter) = visitor.filter().cloned() {
1206                return filter_and_process_admitted_root(
1207                    visitor, root_cx, root_ctx, entry, &filter,
1208                )
1209                .await;
1210            }
1211            process_admitted_entry(visitor, root_cx, root_ctx, entry).await
1212        }
1213        CopyEntryAdmission::Filtered { entry, filter_base } => {
1214            process_admitted_entry(
1215                visitor,
1216                root_cx.with_relative_path(filter_base),
1217                root_ctx,
1218                entry,
1219            )
1220            .await
1221        }
1222    }
1223}
1224
1225impl WalkVisitor for CopyVisitor {
1226    type Summary = Summary;
1227    type DirContext = CopyDirContext;
1228    type DirState = CopyDirState;
1229
1230    fn root_dir_context(&self) -> CopyDirContext {
1231        CopyDirContext {
1232            dst_dir: self.dst_parent.clone(),
1233            destination: self.destination.clone(),
1234            is_fresh: self.root_is_fresh,
1235        }
1236    }
1237
1238    fn permit_kind(&self) -> PermitKind {
1239        // copy retains fd-backed handles across each leaf-dispatch path, including nested
1240        // destination removal under overwrite
1241        PermitKind::OpenFile
1242    }
1243
1244    fn fail_early(&self) -> bool {
1245        self.settings.fail_early
1246    }
1247
1248    fn name_collection(&self) -> NameCollection {
1249        if self.settings.delete.is_some() {
1250            NameCollection::Delete
1251        } else {
1252            NameCollection::None
1253        }
1254    }
1255
1256    fn filter(&self) -> Option<&crate::filter::FilterSettings> {
1257        self.settings.filter.as_ref()
1258    }
1259
1260    fn filter_requires_admitted_entry(&self) -> bool {
1261        true
1262    }
1263
1264    fn filter_allows_hint_only_skip(&self, _dir_ctx: &Self::DirContext) -> bool {
1265        // the driver enforces exact filtering for delete evidence. dry-run also exposes exact
1266        // action/counters, even without deletion, so it must not omit a replacement based on a hint
1267        self.settings.dry_run.is_none()
1268    }
1269
1270    fn on_skip(
1271        &self,
1272        cx: &SkippedEntry<'_>,
1273        kind: EntryKind,
1274        skip_result: &crate::filter::FilterResult,
1275    ) -> Summary {
1276        // mirror `copy_dir_contents`'s inline filter-skip: the dry-run "skip ..." line plus the
1277        // matching `*_skipped` counter. the driver already did the shared progress increment.
1278        cx.report_skip(self.settings.dry_run, skip_result, kind);
1279        skipped_summary_for(kind)
1280    }
1281
1282    async fn visit_leaf(
1283        &self,
1284        cx: &EntryCx,
1285        parent_ctx: &CopyDirContext,
1286        leaf: AdmittedLeaf,
1287    ) -> Result<Summary, Error> {
1288        let src_parent = &cx.parent;
1289        let dst_parent = parent_ctx.dst_dir.as_ref();
1290        let name = cx.name.as_os_str();
1291        let src_path = &cx.real_path;
1292        let dst_path = self.dst_path_for(cx);
1293        let dst_name = self.dst_name_for(cx)?;
1294        let is_fresh = parent_ctx.is_fresh;
1295        // --dereference: resolve a symlink to its target by path and copy that instead. this is the
1296        // path-based payload branch we intentionally keep (hardening -L is out of scope). transfer
1297        // provisional admission into the target's root walk; that walk releases it if authoritative
1298        // classification proves the target is a directory
1299        if self.settings.dereference && leaf.kind() == EntryKind::Symlink {
1300            let open_file_guard = match leaf.into_permit() {
1301                Some(permit) => permit.into_open_file(),
1302                None => throttle::open_file_permit().await,
1303            };
1304            // canonicalizing a payload target requires explicit dereferencing; read-only
1305            // destination preview probes elsewhere do not enter this payload branch
1306            debug_assert!(
1307                self.settings.dereference,
1308                "canonicalize reached with dereference == false; payload target resolution \
1309                 requires explicit dereferencing"
1310            );
1311            let link = crate::walk::run_metadata_probed(
1312                congestion::Side::Source,
1313                congestion::MetadataOp::Stat,
1314                tokio::fs::canonicalize(src_path),
1315            )
1316            .await
1317            .with_context(|| format!("failed reading src symlink {:?}", src_path))
1318            .map_err(|err| Error::new(err, Default::default()))?;
1319            return copy_root_admitted(
1320                self.prog_track,
1321                &link,
1322                &dst_path,
1323                &self.settings,
1324                &self.preserve,
1325                is_fresh,
1326                parent_ctx.destination.clone(),
1327                Some(open_file_guard),
1328            )
1329            .await;
1330        }
1331        match leaf.kind() {
1332            EntryKind::File => {
1333                copy_file_fd(
1334                    self.prog_track,
1335                    src_parent,
1336                    dst_parent,
1337                    name,
1338                    dst_name,
1339                    &dst_path,
1340                    src_path,
1341                    leaf.handle(),
1342                    &self.settings,
1343                    &self.preserve,
1344                    is_fresh,
1345                    &parent_ctx.destination,
1346                )
1347                .await
1348            }
1349            EntryKind::Symlink => {
1350                copy_symlink_fd(
1351                    self.prog_track,
1352                    src_parent,
1353                    dst_parent,
1354                    dst_name,
1355                    src_path,
1356                    &dst_path,
1357                    leaf.handle(),
1358                    &self.settings,
1359                    &self.preserve,
1360                    is_fresh,
1361                    &parent_ctx.destination,
1362                )
1363                .await
1364            }
1365            EntryKind::Special => {
1366                if self.settings.skip_specials {
1367                    tracing::debug!("skipping special file {:?}", src_path);
1368                    if let Some(mode) = self.settings.dry_run {
1369                        match mode {
1370                            DryRunMode::Brief => {}
1371                            DryRunMode::All => println!("skip special {:?}", src_path),
1372                            DryRunMode::Explain => {
1373                                println!("skip special {:?} (unsupported file type)", src_path);
1374                            }
1375                        }
1376                    }
1377                    self.prog_track.specials_skipped.inc();
1378                    return Ok(Summary {
1379                        specials_skipped: 1,
1380                        ..Default::default()
1381                    });
1382                }
1383                Err(Error::new(
1384                    anyhow!(
1385                        "copy: {:?} -> {:?} failed, unsupported src file type",
1386                        src_path,
1387                        dst_path
1388                    ),
1389                    Default::default(),
1390                ))
1391            }
1392            // a directory never reaches `visit_leaf`: the driver dispatches it to dir_pre/dir_post.
1393            EntryKind::Dir => unreachable!("directory entries are handled by dir_pre/dir_post"),
1394        }
1395    }
1396
1397    async fn dir_pre(
1398        &self,
1399        cx: &EntryCx,
1400        parent_ctx: &CopyDirContext,
1401        _handle: &Handle,
1402    ) -> DirPreResult<Self> {
1403        let src_parent = &cx.parent;
1404        let name = cx.name.as_os_str();
1405        let src_path = &cx.real_path;
1406        let dst_path = self.dst_path_for(cx);
1407        let dst_name = self.dst_name_for(cx)?.to_owned();
1408        let is_fresh = parent_ctx.is_fresh;
1409        // open the source directory's contents (O_NOFOLLOW) — this is the `dir` the driver walks.
1410        let (src_dir, src_meta) = src_parent
1411            .open_dir_with_meta(name)
1412            .await
1413            .with_context(|| format!("cannot open directory {:?} for reading", src_path))
1414            .map_err(|err| Error::new(err, Default::default()))?;
1415        let src_dir = Arc::new(src_dir);
1416        let admission = parent_ctx
1417            .destination
1418            .enter(
1419                self.prog_track,
1420                &[&src_meta],
1421                destination::PreservationSource {
1422                    dir: &src_dir,
1423                    meta: &src_meta,
1424                    path: src_path,
1425                    acl: self.preserve.dir.acl,
1426                },
1427                parent_ctx.dst_dir.as_ref(),
1428                &dst_name,
1429                &dst_path,
1430                &self.settings,
1431                self.settings.dry_run,
1432            )
1433            .await
1434            .map_err(|error| {
1435                Error::new(
1436                    error.source.context(format!(
1437                        "cannot copy directory {src_path:?} to {dst_path:?}"
1438                    )),
1439                    error.summary,
1440                )
1441            })?;
1442        let destination::Admission::Entered {
1443            destination,
1444            slot,
1445            preview,
1446            snapshot,
1447        } = admission
1448        else {
1449            let destination::Admission::Skip(summary) = admission else {
1450                unreachable!()
1451            };
1452            return Ok(DirAction::Skip(summary));
1453        };
1454        let (dst_dir, dst_parent, base, child_is_fresh, we_created, reused_lock) = match slot {
1455            Some(slot) => (
1456                Some(slot.dir),
1457                parent_ctx.dst_dir.clone(),
1458                slot.summary,
1459                slot.is_fresh,
1460                slot.we_created,
1461                slot.reused_lock,
1462            ),
1463            None => {
1464                crate::dry_run::report_action("copy", src_path, Some(&dst_path), "dir");
1465                (
1466                    None,
1467                    None,
1468                    Summary {
1469                        directories_created: 1,
1470                        ..Default::default()
1471                    },
1472                    is_fresh,
1473                    true,
1474                    None,
1475                )
1476            }
1477        };
1478        Ok(DirAction::Descend {
1479            dir: Arc::clone(&src_dir),
1480            child_ctx: CopyDirContext {
1481                dst_dir: dst_dir.clone(),
1482                destination: destination.child(),
1483                is_fresh: child_is_fresh,
1484            },
1485            state: CopyDirState {
1486                src_dir,
1487                preview_dir: preview,
1488                dst_dir,
1489                dst_parent,
1490                dst_name,
1491                we_created,
1492                reused_lock,
1493                snapshot,
1494                base,
1495            },
1496        })
1497    }
1498
1499    async fn dir_post(
1500        &self,
1501        cx: &EntryCx,
1502        state: CopyDirState,
1503        child_result: DirPostInput<Self>,
1504    ) -> Result<Summary, Error> {
1505        let CopyDirState {
1506            src_dir,
1507            preview_dir,
1508            dst_dir,
1509            dst_parent,
1510            dst_name,
1511            we_created,
1512            reused_lock,
1513            snapshot,
1514            base,
1515        } = state;
1516        // whether any child failed (non-fail-early: the driver still calls dir_post on error so we
1517        // can apply post-order directory metadata, but we must skip the destructive `--delete`
1518        // prune and surface the child error). the partial child summary is folded either way,
1519        // seeded with `base` (this directory's own create/unchanged contribution) — exactly as
1520        // `copy_dir_contents` seeded `copy_summary = base` before joining the children.
1521        let (copy_summary, child_error) = {
1522            let (mut summary, mut child_error, processed) = match child_result {
1523                Ok((summary, processed)) => (base + summary, None, Some(processed)),
1524                Err(error) => (base + error.summary, Some(error.source), None),
1525            };
1526            if let Some(delete) = &self.settings.delete {
1527                let dst_path = self.dst_path_for(cx);
1528                if let Some(keep_set) =
1529                    crate::delete::DeleteDecision::from_processed(delete, processed.as_ref())
1530                        .into_ready(&dst_path)
1531                    && let Some(prune_dir) = crate::delete::select_scan_dir(
1532                        dst_dir.as_ref(),
1533                        preview_dir.as_ref(),
1534                        &dst_path,
1535                    )
1536                {
1537                    match self
1538                        .prune_finished_dir(
1539                            &mut summary,
1540                            &keep_set,
1541                            &src_dir,
1542                            prune_dir,
1543                            &cx.rel_path,
1544                        )
1545                        .await
1546                    {
1547                        Ok(()) => {}
1548                        Err(error) if self.settings.fail_early => {
1549                            return Err(Error::new(error, summary));
1550                        }
1551                        Err(error) => {
1552                            child_error.get_or_insert(error);
1553                        }
1554                    }
1555                }
1556            }
1557            // child names authorize only the prune; this scope frees them before gated metadata work.
1558            (summary, child_error)
1559        };
1560        // empty-dir cleanup + post-order directory metadata; also surfaces any collected child error.
1561        self.finalize_dir(
1562            FinalizeDir {
1563                copy_summary,
1564                child_error,
1565                dst_dir,
1566                dst_parent,
1567                dst_name,
1568                src_meta: snapshot.meta,
1569                src_acls: snapshot.acls,
1570                we_created,
1571                reused_lock,
1572            },
1573            cx,
1574        )
1575        .await
1576    }
1577}
1578
1579/// Probe a destination operand's existence/kind for a dry-run `--ignore-existing`
1580/// decision under strict operand resolution: fd-relative via the destination's
1581/// parent (`openat2(RESOLVE_NO_SYMLINKS)`), so a symlinked destination prefix
1582/// fails closed instead of being followed by the path-based fallback. Only called
1583/// while strict operand resolution is armed (the default path keeps its
1584/// path-based probe unchanged).
1585async fn strict_dry_run_dst_kind(dst_path: &std::path::Path) -> Result<Option<EntryKind>, Error> {
1586    crate::safedir::strict_probe_dst_kind(dst_path, congestion::Side::Destination)
1587        .await
1588        .map_err(|err| {
1589            Error::new(
1590                anyhow::Error::new(err).context(format!("cannot probe destination {dst_path:?}")),
1591                Default::default(),
1592            )
1593        })
1594}
1595
1596/// Does anything occupy the destination path, as seen from a **dry-run**?
1597///
1598/// This leaf existence check remains path-based; deletion previews separately hold directory fds
1599/// for their scans. A real copy never calls it: there the create itself reports the
1600/// conflict, which is both cheaper and not subject to a swap between probe and act.
1601///
1602/// Call ONLY when the answer is used (`--ignore-existing`). Under strict operand resolution the
1603/// probe can *fail*, and an unused one must never fail a valid `--dry-run --delete` onto a final
1604/// destination symlink.
1605async fn dry_run_dst_exists(dst_path: &std::path::Path) -> Result<bool, Error> {
1606    if crate::safedir::strict_operand_resolution() {
1607        return Ok(strict_dry_run_dst_kind(dst_path).await?.is_some());
1608    }
1609    match tokio::fs::symlink_metadata(dst_path).await {
1610        Ok(_) => Ok(true),
1611        // `NotFound` is the ONE error that means the slot is empty — the same rule
1612        // [`preflight_dst_file`] and the remote destination follow. Every other failure (EACCES on a
1613        // parent directory,
1614        // ELOOP, ENOTDIR, EIO) says we could not LOOK, not that there is nothing there. Reporting
1615        // those as vacant made `--dry-run --ignore-existing` print "would copy" and exit 0 through a
1616        // destination parent it cannot even traverse — predicting a copy the real run then fails, and
1617        // swallowing the one error that explains why.
1618        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1619        Err(error) => Err(Error::new(
1620            anyhow::Error::new(error).context(format!("cannot probe destination {dst_path:?}")),
1621            Default::default(),
1622        )),
1623    }
1624}
1625
1626/// Copy a regular file fd-relative: create (or overwrite) the destination via `dst_parent`,
1627/// copy the bytes with `copy_file_data`, then apply metadata through the destination's own
1628/// fd — the open is held from creation through metadata, closing the path-based re-open TOCTOU
1629/// window. `--overwrite`/`--ignore-existing`/`is_fresh`/dry-run semantics mirror the path-based
1630/// [`copy_file`].
1631#[allow(clippy::too_many_arguments)]
1632async fn copy_file_fd(
1633    prog_track: &'static progress::Progress,
1634    src_parent: &Arc<Dir>,
1635    dst_parent: Option<&Arc<Dir>>,
1636    name: &OsStr,
1637    dst_name: &OsStr,
1638    dst_path: &std::path::Path,
1639    src_path: &std::path::Path,
1640    src_handle: &Handle,
1641    settings: &Settings,
1642    preserve: &preserve::Settings,
1643    is_fresh: bool,
1644    destination: &DestinationContext,
1645) -> Result<Summary, Error> {
1646    // bring `FileMeta::size()` into scope locally; importing the trait at module level would
1647    // collide with `std::os::unix::fs::MetadataExt` on `std::fs::Metadata` elsewhere in this file.
1648    use crate::preserve::Metadata as _;
1649    debug_assert_eq!(src_handle.kind(), EntryKind::File);
1650    // --ignore-existing in dry-run: skip if the destination already exists (any type, including a
1651    // dangling symlink). a real copy does NOT probe here — [`preflight_dst_file`] below is the single
1652    // owner of every conflict decision, `--ignore-existing` included, and it reaches that decision
1653    // on both of its routes, so an fd-based probe here would be a redundant `child()` whose only
1654    // distinct effect was to mistake a lookup *failure* (EACCES, EMFILE, ESTALE) for a vacant slot.
1655    if dst_parent.is_none()
1656        && !is_fresh
1657        && settings.ignore_existing
1658        && dry_run_dst_exists(dst_path).await?
1659    {
1660        if let Some(mode) = settings.dry_run {
1661            match mode {
1662                DryRunMode::Brief => {}
1663                DryRunMode::All => println!("skip file {:?}", dst_path),
1664                DryRunMode::Explain => {
1665                    println!("skip file {:?} (destination exists)", dst_path)
1666                }
1667            }
1668        }
1669        tracing::debug!("destination exists, skipping (--ignore-existing)");
1670        prog_track.files_unchanged.inc();
1671        return Ok(Summary {
1672            files_unchanged: 1,
1673            ..Default::default()
1674        });
1675    }
1676    if settings.dry_run.is_none() {
1677        // dst_parent is guaranteed Some here: it is None only in dry-run.
1678        let dst_parent = dst_parent.expect("destination parent must be open for a real copy");
1679        let preflight = if is_fresh {
1680            DestinationPreflight::Vacant
1681        } else {
1682            preflight_dst_file(prog_track, dst_parent, dst_name, dst_path, settings).await?
1683        };
1684        // the admitted handle is the approved point-in-time metadata snapshot. Only a vacant slot
1685        // or a candidate that differs from that snapshot needs the current payload opened.
1686        let (current, plan) = match preflight {
1687            DestinationPreflight::Skip(summary) => return Ok(summary),
1688            DestinationPreflight::Vacant => (
1689                CurrentRegular::open(src_parent, name, src_path).await?,
1690                FilePlan::Vacant,
1691            ),
1692            DestinationPreflight::OverwriteCandidate(dst_handle) => {
1693                match plan_overwrite_candidate(prog_track, &dst_handle, src_handle.meta(), settings)
1694                {
1695                    OverwriteCandidateDecision::Skip(summary) => return Ok(summary),
1696                    OverwriteCandidateDecision::Replace => {}
1697                }
1698                // if the actionable payload no longer has the admitted identity, re-plan from the
1699                // payload fd's paired metadata before touching the destination.
1700                let current = CurrentRegular::open(src_parent, name, src_path).await?;
1701                if !current.matches(src_handle)
1702                    && let OverwriteCandidateDecision::Skip(summary) =
1703                        plan_overwrite_candidate(prog_track, &dst_handle, &current.meta, settings)
1704                {
1705                    return Ok(summary);
1706                }
1707                (
1708                    current,
1709                    FilePlan::Replace(dst_handle.into_removal_snapshot()),
1710                )
1711            }
1712        };
1713        return copy_current_regular(
1714            prog_track,
1715            src_parent,
1716            dst_parent,
1717            dst_name,
1718            dst_path,
1719            src_path,
1720            current,
1721            plan,
1722            settings,
1723            preserve,
1724            destination,
1725        )
1726        .await;
1727    }
1728    // dry-run: report and return what would happen without touching the destination.
1729    crate::dry_run::report_action("copy", src_path, Some(dst_path), "file");
1730    Ok(Summary {
1731        files_copied: 1,
1732        bytes_copied: src_handle.meta().size(),
1733        ..Default::default()
1734    })
1735}
1736
1737// the destination precedes the test visit token so abandoned output closes its fd before the
1738// token witnesses admission release, matching the canonical blocking-output ownership contract
1739struct FileDataOutput {
1740    result: std::io::Result<u64>,
1741    destination: std::fs::File,
1742    #[cfg(test)]
1743    gate_visit: Option<crate::testutils::BlockingPathGateVisit>,
1744}
1745
1746enum FileCopyStart {
1747    CreatedAndCopied(FileDataOutput),
1748    CreateResult {
1749        source: std::fs::File,
1750        destination: std::io::Result<std::fs::File>,
1751    },
1752}
1753
1754fn copy_file_payload(
1755    source: std::fs::File,
1756    destination: std::fs::File,
1757    len: u64,
1758    reflink: crate::copy_data::ReflinkMode,
1759    #[cfg(test)] data_gate_path: &std::path::Path,
1760) -> FileDataOutput {
1761    #[cfg(test)]
1762    let gate_visit = {
1763        use std::os::fd::{AsFd as _, AsRawFd as _};
1764        crate::testutils::wait_on_blocking_path_gate(
1765            data_gate_path,
1766            destination.as_fd().as_raw_fd(),
1767        )
1768    };
1769    let result = copy_file_data(&source, &destination, len, reflink);
1770    FileDataOutput {
1771        result,
1772        destination,
1773        #[cfg(test)]
1774        gate_visit,
1775    }
1776}
1777
1778/// Copies one already-open current regular source after destination-only preflight has completed.
1779#[allow(clippy::too_many_arguments)]
1780async fn copy_current_regular(
1781    prog_track: &'static progress::Progress,
1782    src_parent: &Arc<Dir>,
1783    dst_parent: &Arc<Dir>,
1784    dst_name: &OsStr,
1785    dst_path: &std::path::Path,
1786    src_path: &std::path::Path,
1787    current: CurrentRegular,
1788    plan: FilePlan,
1789    settings: &Settings,
1790    preserve: &preserve::Settings,
1791    destination: &DestinationContext,
1792) -> Result<Summary, Error> {
1793    use crate::preserve::Metadata as _;
1794    let CurrentRegular {
1795        file: src_file,
1796        meta: src_meta,
1797    } = current;
1798    // `copy_summary` accumulates what has already happened to the destination, so every error
1799    // payload below reports the removals an overwrite performed.
1800    let mut copy_summary = Summary::default();
1801    // preflight, metadata planning, payload open, reserve, then mutate. the current source was
1802    // opened while the destination was still intact, and its metadata was re-planned if it differed
1803    // from the metadata-only snapshot. an overwrite that unlinked first would leave the user with
1804    // neither file whenever the source turned out to be unreadable or had changed kind: a copy that
1805    // could never have produced bytes must not destroy what it was going to replace.
1806    //
1807    // this is not cancellation safety and does not try to be. `create_file` waits on the ops-throttle
1808    // internally, so the removal below and the create after it are not one committed step:
1809    // cancellation (Ctrl-C, a `--fail-early` sibling abort) can land between them and leave the
1810    // destination absent, and `create_file` can itself fail with EMFILE/ENOSPC/EIO. rcp's copy
1811    // semantics are point-in-time and non-atomic (docs/remote_protocol.md) — an interrupted
1812    // `--overwrite` corrupting the files it was overwriting is accepted, and the data copy in the very
1813    // next step would leave a truncated destination anyway. Closing that gap means staging plus
1814    // rename, which costs performance rcp deliberately does not spend.
1815    //
1816    get_file_iops_tokens(settings.chunk_size, src_meta.size()).await;
1817    // read the source ACL from the SAME fd whose bytes are about to be copied (read-side fidelity,
1818    // docs/tocttou.md), and before the destination is touched — an unreadable source must not cost
1819    // the user the file being overwritten. Only when `acl` was requested: the probe is a syscall per
1820    // entry that `stat` cannot fold in, so an ordinary copy must not pay for it.
1821    let (src_file, src_acls) = if preserve.file.acl {
1822        let (src_file, acls) = safedir::read_acls_owned(src_file, src_parent.side(), false)
1823            .await
1824            .with_context(|| format!("failed reading ACLs from {:?}", src_path))
1825            .map_err(|err| Error::new(err, copy_summary))?;
1826        (src_file, Some(acls))
1827    } else {
1828        (src_file, None)
1829    };
1830    // the source fd is held and the throttle budget is reserved, so the destination can now be
1831    // replaced: the failure that would most often abandon this copy before any byte exists is behind
1832    // us. It is not the last one — `create_file` below has its own (EMFILE, ENOSPC, EIO) and waits on
1833    // the ops-throttle, so a cancellation can still land between the two; see the note above on why
1834    // rcp accepts that rather than staging and renaming. `execute_dst_plan` removes by name through
1835    // the pinned parent; a compatible replacement since planning may be removed, but the operation
1836    // cannot escape that directory.
1837    let combine_create_and_copy =
1838        settings.local_copy_handoff == LocalCopyHandoff::Fresh && matches!(&plan, FilePlan::Vacant);
1839    let len = src_meta.size();
1840    let reflink = settings.reflink;
1841    #[cfg(test)]
1842    let data_gate_path = dst_path.to_path_buf();
1843    execute_dst_plan(
1844        prog_track,
1845        dst_parent,
1846        dst_name,
1847        dst_path,
1848        plan,
1849        settings,
1850        &mut copy_summary,
1851        destination,
1852    )
1853    .await?;
1854    // keep source opening, IOPS reservation, and ACL capture ahead of creation. Only the first
1855    // vacant-slot attempt combines creation and payload; conflict recovery keeps the source fd and
1856    // the existing single retry. The create probe/permit end before the cancellable payload claim.
1857    let started = if combine_create_and_copy {
1858        #[cfg(test)]
1859        let data_gate_path = data_gate_path.clone();
1860        dst_parent
1861            .create_file_and_then(dst_name, move |destination| match destination {
1862                Ok(destination) => FileCopyStart::CreatedAndCopied(copy_file_payload(
1863                    src_file,
1864                    destination,
1865                    len,
1866                    reflink,
1867                    #[cfg(test)]
1868                    &data_gate_path,
1869                )),
1870                Err(error) => FileCopyStart::CreateResult {
1871                    source: src_file,
1872                    destination: Err(error),
1873                },
1874            })
1875            .await
1876            .with_context(|| format!("failed creating or copying {:?}", dst_path))
1877            .map_err(|err| Error::new(err, copy_summary))?
1878    } else {
1879        FileCopyStart::CreateResult {
1880            source: src_file,
1881            destination: dst_parent.create_file(dst_name).await,
1882        }
1883    };
1884    let data_output = match started {
1885        FileCopyStart::CreatedAndCopied(output) => output,
1886        FileCopyStart::CreateResult {
1887            source,
1888            destination: created,
1889        } => {
1890            let dst_file = match created {
1891                Ok(dst_file) => dst_file,
1892                // the destination slot is occupied. `create_file`'s `O_EXCL` is the only way either route
1893                // finds out that a writer got here between our last look and now: on the known-fresh route
1894                // there was no earlier look at all (freshness is an optimization hint, not an enforceable
1895                // invariant — see `resolve_dst_dir` — so a concurrent writer can populate a directory we
1896                // just created), and on the other route the slot was planned but has been refilled since.
1897                // both cases are the same conflict, so resolve it here and honor --overwrite /
1898                // --ignore-existing rather than failing the copy on EEXIST. Planning and executing are
1899                // back-to-back here, unlike the route above: the source and the tokens are already held, so
1900                // there is nothing left that could abandon the copy after the removal.
1901                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
1902                    let preflight =
1903                        preflight_dst_file(prog_track, dst_parent, dst_name, dst_path, settings)
1904                            .await
1905                            // rebuild from `err.source`, never from a stringified error: the chain must survive.
1906                            .map_err(|err| Error::new(err.source, err.summary + copy_summary))?;
1907                    let plan = match preflight {
1908                        DestinationPreflight::Vacant => FilePlan::Vacant,
1909                        DestinationPreflight::Skip(summary) => {
1910                            return Ok(skip_summary(summary, &copy_summary));
1911                        }
1912                        DestinationPreflight::OverwriteCandidate(dst_handle) => {
1913                            match plan_overwrite_candidate(
1914                                prog_track,
1915                                &dst_handle,
1916                                &src_meta,
1917                                settings,
1918                            ) {
1919                                OverwriteCandidateDecision::Skip(summary) => {
1920                                    return Ok(skip_summary(summary, &copy_summary));
1921                                }
1922                                OverwriteCandidateDecision::Replace => {
1923                                    FilePlan::Replace(dst_handle.into_removal_snapshot())
1924                                }
1925                            }
1926                        }
1927                    };
1928                    execute_dst_plan(
1929                        prog_track,
1930                        dst_parent,
1931                        dst_name,
1932                        dst_path,
1933                        plan,
1934                        settings,
1935                        &mut copy_summary,
1936                        destination,
1937                    )
1938                    .await?;
1939                    // retry exactly once. the slot was cleared just above, so a second EEXIST means yet
1940                    // another writer refilled it — report that rather than looping, which against a live
1941                    // competing writer would never terminate.
1942                    dst_parent
1943                        .create_file(dst_name)
1944                        .await
1945                        .with_context(|| format!("failed creating {:?}", dst_path))
1946                        .map_err(|err| Error::new(err, copy_summary))?
1947                }
1948                Err(error) => {
1949                    return Err(Error::new(
1950                        anyhow::Error::new(error)
1951                            .context(format!("failed creating {:?}", dst_path)),
1952                        copy_summary,
1953                    ));
1954                }
1955            };
1956            // payload latency is deliberately outside metadata congestion probes. The canonical
1957            // boundary retains descriptor admission through work and abandoned output destruction.
1958            safedir::run_fd_admitted_blocking(move || {
1959                Ok(copy_file_payload(
1960                    source,
1961                    dst_file,
1962                    len,
1963                    reflink,
1964                    #[cfg(test)]
1965                    &data_gate_path,
1966                ))
1967            })
1968            .await
1969            .with_context(|| format!("failed copying data to {:?}", dst_path))
1970            .map_err(|err| Error::new(err, copy_summary))?
1971        }
1972    };
1973    let FileDataOutput {
1974        result: copy_result,
1975        destination: dst_file,
1976        #[cfg(test)]
1977            gate_visit: _gate_visit,
1978    } = data_output;
1979    let copied = copy_result
1980        .with_context(|| format!("failed copying data to {:?}", dst_path))
1981        .map_err(|err| Error::new(err, copy_summary))?;
1982    // account for the bytes ACTUALLY copied, not `len` (the size snapshotted at open): if the source
1983    // is concurrently truncated, `copy_file_data` returns the shorter real count, so using `len`
1984    // would over-report. `len` still drives the copy loop and the iops-token reservation above.
1985    prog_track.files_copied.inc();
1986    prog_track.bytes_copied.add(copied);
1987    tracing::debug!("setting permissions");
1988    safedir::set_file_metadata_owned(
1989        preserve,
1990        &src_meta,
1991        src_acls.as_ref(),
1992        dst_file.into(),
1993        congestion::Side::Destination,
1994    )
1995    .await
1996    .with_context(|| format!("failed setting metadata on {:?}", dst_path))
1997    .map_err(|err| Error::new(err, copy_summary))?;
1998    // count the file as copied only after all metadata has been applied (actual bytes, see above).
1999    copy_summary.bytes_copied += copied;
2000    copy_summary.files_copied += 1;
2001    Ok(copy_summary)
2002}
2003
2004/// Create a symlink fd-relative and apply its metadata through the created link's own handle.
2005/// `--overwrite`/`--ignore-existing`/dry-run semantics mirror the path-based symlink handling.
2006#[allow(clippy::too_many_arguments)]
2007async fn copy_symlink_fd(
2008    prog_track: &'static progress::Progress,
2009    src_parent: &Arc<Dir>,
2010    dst_parent: Option<&Arc<Dir>>,
2011    dst_name: &OsStr,
2012    src_path: &std::path::Path,
2013    dst_path: &std::path::Path,
2014    src_handle: &Handle,
2015    settings: &Settings,
2016    preserve: &preserve::Settings,
2017    is_fresh: bool,
2018    destination: &DestinationContext,
2019) -> Result<Summary, Error> {
2020    // --ignore-existing in DRY-RUN: skip if the destination already exists (any type). A real copy
2021    // does NOT probe here, for the same reason [`copy_file_fd`] does not: `symlink_at` below fails
2022    // `EEXIST` on an occupied slot and its recovery branch already owns `--ignore-existing`, so an
2023    // fd-based probe here would be a redundant `child()` whose only distinct effect was to mistake
2024    // a lookup *failure* (EACCES, EMFILE, ESTALE) for a vacant slot.
2025    if dst_parent.is_none()
2026        && !is_fresh
2027        && settings.ignore_existing
2028        && dry_run_dst_exists(dst_path).await?
2029    {
2030        if let Some(mode) = settings.dry_run {
2031            match mode {
2032                DryRunMode::Brief => {}
2033                DryRunMode::All => println!("skip symlink {:?}", dst_path),
2034                DryRunMode::Explain => {
2035                    println!("skip symlink {:?} (destination exists)", dst_path)
2036                }
2037            }
2038        }
2039        tracing::debug!("destination exists, skipping symlink (--ignore-existing)");
2040        prog_track.symlinks_unchanged.inc();
2041        return Ok(Summary {
2042            symlinks_unchanged: 1,
2043            ..Default::default()
2044        });
2045    }
2046    if settings.dry_run.is_some() {
2047        crate::dry_run::report_action("copy", src_path, Some(dst_path), "symlink");
2048        return Ok(Summary {
2049            symlinks_created: 1,
2050            ..Default::default()
2051        });
2052    }
2053    let dst_parent = dst_parent.expect("destination parent must be open for a real copy");
2054    // read the target AND metadata from the SAME pinned handle (one paired call), so a concurrent
2055    // same-name symlink swap can't pair one link's target with another link's owner/timestamps
2056    // (target/metadata fidelity, matching the regular-file path which takes both from one fd).
2057    let (target, src_meta) = src_handle
2058        .read_symlink(src_parent.side())
2059        .await
2060        .with_context(|| format!("failed reading symlink {:?}", src_path))
2061        .map_err(|err| Error::new(err, Default::default()))?;
2062    // fast path: the destination slot is empty, create the link directly.
2063    match dst_parent.symlink_at(dst_name, &target).await {
2064        Ok(link_handle) => {
2065            safedir::set_symlink_metadata_fd(
2066                preserve,
2067                &src_meta,
2068                &link_handle,
2069                congestion::Side::Destination,
2070            )
2071            .await
2072            .with_context(|| format!("failed setting symlink metadata on {:?}", dst_path))
2073            .map_err(|err| Error::new(err, Default::default()))?;
2074            prog_track.symlinks_created.inc();
2075            Ok(Summary {
2076                symlinks_created: 1,
2077                ..Default::default()
2078            })
2079        }
2080        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2081            if settings.ignore_existing {
2082                tracing::debug!("destination exists, skipping symlink (--ignore-existing)");
2083                prog_track.symlinks_unchanged.inc();
2084                return Ok(Summary {
2085                    symlinks_unchanged: 1,
2086                    ..Default::default()
2087                });
2088            }
2089            if !settings.overwrite {
2090                return Err(Error::new(
2091                    anyhow!("failed creating symlink {:?}", dst_path),
2092                    Default::default(),
2093                ));
2094            }
2095            let dst_handle = dst_parent
2096                .child(dst_name)
2097                .await
2098                .with_context(|| format!("failed reading metadata from dst: {:?}", dst_path))
2099                .map_err(|err| Error::new(err, Default::default()))?;
2100            if dst_handle.kind() == EntryKind::Symlink {
2101                let dst_link = dst_parent
2102                    .read_link_at(dst_name) // rcp-toctou-allow: destination symlink (overwrite compare), not a source payload
2103                    .await
2104                    .with_context(|| format!("failed reading dst symlink: {:?}", dst_path))
2105                    .map_err(|err| Error::new(err, Default::default()))?;
2106                if dst_link == target {
2107                    tracing::debug!("'dst' is a symlink and points to the same location as 'src'");
2108                    if preserve.symlink.any()
2109                        && !filecmp::metadata_equal(
2110                            &settings.overwrite_compare,
2111                            &src_meta,
2112                            dst_handle.meta(),
2113                        )
2114                    {
2115                        tracing::debug!("'dst' metadata is different, updating");
2116                        safedir::set_symlink_metadata_fd(
2117                            preserve,
2118                            &src_meta,
2119                            &dst_handle,
2120                            congestion::Side::Destination,
2121                        )
2122                        .await
2123                        .with_context(|| {
2124                            format!("failed setting symlink metadata on {:?}", dst_path)
2125                        })
2126                        .map_err(|err| Error::new(err, Default::default()))?;
2127                        prog_track.symlinks_removed.inc();
2128                        prog_track.symlinks_created.inc();
2129                        return Ok(Summary {
2130                            rm_summary: RmSummary {
2131                                symlinks_removed: 1,
2132                                ..Default::default()
2133                            },
2134                            symlinks_created: 1,
2135                            ..Default::default()
2136                        });
2137                    }
2138                    tracing::debug!("symlink already exists, skipping");
2139                    prog_track.symlinks_unchanged.inc();
2140                    return Ok(Summary {
2141                        symlinks_unchanged: 1,
2142                        ..Default::default()
2143                    });
2144                }
2145                tracing::debug!("'dst' is a symlink but points to a different path, updating");
2146            } else {
2147                tracing::info!("'dst' is not a symlink, updating");
2148            }
2149            // remove the conflicting destination entry, then create the link fresh.
2150            destination
2151                .check_leaf_replacement_parent(dst_parent, dst_path)
2152                .await
2153                .map_err(|error| Error::new(error.into(), Default::default()))?;
2154            let rm_summary = remove_existing_guarded(
2155                prog_track,
2156                dst_parent,
2157                dst_name,
2158                dst_path,
2159                dst_handle.into_removal_snapshot(),
2160                settings,
2161                Some(destination.protection()),
2162            )
2163            .await?;
2164            let copy_summary = Summary {
2165                rm_summary,
2166                ..Default::default()
2167            };
2168            let link_handle = dst_parent
2169                .symlink_at(dst_name, &target)
2170                .await
2171                .with_context(|| format!("failed creating symlink {:?}", dst_path))
2172                .map_err(|err| Error::new(err, copy_summary))?;
2173            safedir::set_symlink_metadata_fd(
2174                preserve,
2175                &src_meta,
2176                &link_handle,
2177                congestion::Side::Destination,
2178            )
2179            .await
2180            .with_context(|| format!("failed setting symlink metadata on {:?}", dst_path))
2181            .map_err(|err| Error::new(err, copy_summary))?;
2182            prog_track.symlinks_created.inc();
2183            Ok(Summary {
2184                rm_summary,
2185                symlinks_created: 1,
2186                ..Default::default()
2187            })
2188        }
2189        Err(error) => Err(Error::new(
2190            anyhow::Error::new(error).context(format!("failed creating symlink {:?}", dst_path)),
2191            Default::default(),
2192        )),
2193    }
2194}
2195
2196/// The current by-name regular source whose metadata and bytes come from one open descriptor.
2197struct CurrentRegular {
2198    file: std::fs::File,
2199    meta: FileMeta,
2200}
2201
2202impl CurrentRegular {
2203    /// Opens the current final component and rejects a replacement of any non-regular type.
2204    async fn open(
2205        src_parent: &Dir,
2206        name: &OsStr,
2207        src_path: &std::path::Path,
2208    ) -> Result<Self, Error> {
2209        let (file, meta) = src_parent
2210            .open_file_read(name)
2211            .await
2212            .with_context(|| format!("failed opening src file {:?} for reading", src_path))
2213            .map_err(|err| Error::new(err, Default::default()))?;
2214        Ok(Self { file, meta })
2215    }
2216
2217    fn matches(&self, handle: &Handle) -> bool {
2218        self.meta.dev() == handle.dev() && self.meta.ino() == handle.ino()
2219    }
2220}
2221
2222/// Source-independent decision made before reopening the current regular source.
2223#[derive(Debug)]
2224enum DestinationPreflight {
2225    /// Nothing occupies the destination slot.
2226    Vacant,
2227    /// Leave the destination alone without acquiring the current source.
2228    Skip(Summary),
2229    /// An existing entry may be compared with the current source and then replaced.
2230    OverwriteCandidate(Handle),
2231}
2232
2233/// What to do about whatever occupies a destination file's slot — decided without touching it.
2234#[derive(Debug)]
2235enum FilePlan {
2236    /// Nothing is in the way. Create straight away.
2237    Vacant,
2238    /// An entry is in the way and `--overwrite` says to replace it. Once source-dependent planning
2239    /// completes, the lightweight snapshot keeps the planned kind and accounting size without
2240    /// holding the classification fd across the throttle wait. Removal is by name through the
2241    /// pinned parent, so retaining that fd could not bind the later mutation to the classified
2242    /// inode.
2243    Replace(RemovalSnapshot),
2244}
2245
2246/// Metadata-dependent decision for an occupied overwrite candidate.
2247#[derive(Clone, Copy, Debug)]
2248enum OverwriteCandidateDecision {
2249    Skip(Summary),
2250    Replace,
2251}
2252
2253/// Merge a skipped plan's summary with removals the copy already performed, producing what the
2254/// caller returns.
2255///
2256/// Needed because a copy can plan the slot twice — once up front, then again after `create_file`
2257/// reports it refilled — and a removal performed before the first create must survive into the
2258/// totals rather than being dropped when the second plan decides to skip. Its progress counter has
2259/// already been incremented either way.
2260fn skip_summary(skip: Summary, copy_summary: &Summary) -> Summary {
2261    Summary {
2262        rm_summary: copy_summary.rm_summary + skip.rm_summary,
2263        ..skip
2264    }
2265}
2266
2267/// Carry out the one mutating step a [`FilePlan`] can call for, folding its accounting into the
2268/// running copy summary so every later error payload reports the removal that already happened.
2269///
2270/// Split from [`preflight_dst_file`] and [`plan_overwrite_candidate`] deliberately: the caller
2271/// settles destination-only outcomes, opens the current source, and reserves throttle capacity
2272/// before actually unlinking. Separating these steps ensures a source-open failure leaves the
2273/// existing destination intact. The split buys nothing against *cancellation* — see
2274/// [`copy_file_fd`] for why rcp does not chase that.
2275#[allow(clippy::too_many_arguments)]
2276async fn execute_dst_plan(
2277    prog_track: &'static progress::Progress,
2278    dst_parent: &Arc<Dir>,
2279    dst_name: &OsStr,
2280    dst_path: &std::path::Path,
2281    plan: FilePlan,
2282    settings: &Settings,
2283    copy_summary: &mut Summary,
2284    destination: &DestinationContext,
2285) -> Result<(), Error> {
2286    let dst_snapshot = match plan {
2287        FilePlan::Vacant => return Ok(()),
2288        FilePlan::Replace(dst_snapshot) => dst_snapshot,
2289    };
2290    destination
2291        .check_leaf_replacement_parent(dst_parent, dst_path)
2292        .await
2293        .map_err(|error| Error::new(error.into(), *copy_summary))?;
2294    match remove_existing_guarded(
2295        prog_track,
2296        dst_parent,
2297        dst_name,
2298        dst_path,
2299        dst_snapshot,
2300        settings,
2301        Some(destination.protection()),
2302    )
2303    .await
2304    {
2305        Ok(rm_summary) => {
2306            copy_summary.rm_summary = copy_summary.rm_summary + rm_summary;
2307            Ok(())
2308        }
2309        // rebuild from `err.source`, never from a stringified error: the chain must survive.
2310        Err(err) => Err(Error::new(err.source, err.summary + *copy_summary)),
2311    }
2312}
2313
2314/// Resolve every destination-only outcome before reopening the current source.
2315///
2316/// An occupied slot either skips under `--ignore-existing`, fails without `--overwrite`, or becomes
2317/// an [`DestinationPreflight::OverwriteCandidate`] whose metadata-dependent comparison is deferred
2318/// to [`plan_overwrite_candidate`]. A vacant slot needs no source metadata either. This function
2319/// never mutates.
2320///
2321/// [`copy_file_fd`] calls this from both of its routes: up front when the destination is not
2322/// known-fresh, and again when the destination was believed fresh but `create_file` reported the
2323/// slot occupied anyway.
2324async fn preflight_dst_file(
2325    prog_track: &'static progress::Progress,
2326    dst_parent: &Arc<Dir>,
2327    dst_name: &OsStr,
2328    dst_path: &std::path::Path,
2329    settings: &Settings,
2330) -> Result<DestinationPreflight, Error> {
2331    let dst_handle = match dst_parent.child(dst_name).await {
2332        Ok(dst_handle) => dst_handle,
2333        // `NotFound` is the ONE error that means "nothing occupies the slot". Every other failure
2334        // (EACCES on the parent, EMFILE, ESTALE, EIO) says we could not look — not that there is
2335        // nothing there — and must keep its context rather than be recast as a vacant slot. The
2336        // difference is user-visible in both directions: `--ignore-existing` would fail on a
2337        // create instead of skipping, and the `create_file` recovery route, which reaches this
2338        // function only because the slot is KNOWN occupied, would report a second bare `EEXIST`
2339        // naming neither the real errno nor the fact that the lookup itself failed.
2340        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
2341            return Ok(DestinationPreflight::Vacant);
2342        }
2343        Err(error) => {
2344            return Err(Error::new(
2345                anyhow::Error::new(error)
2346                    .context(format!("failed looking up destination {:?}", dst_path)),
2347                Default::default(),
2348            ));
2349        }
2350    };
2351    if settings.ignore_existing {
2352        tracing::debug!("destination exists, skipping (--ignore-existing)");
2353        prog_track.files_unchanged.inc();
2354        return Ok(DestinationPreflight::Skip(Summary {
2355            files_unchanged: 1,
2356            ..Default::default()
2357        }));
2358    }
2359    if !settings.overwrite {
2360        return Err(Error::new(
2361            anyhow!(
2362                "destination {:?} already exists, did you intend to specify --overwrite?",
2363                dst_path
2364            ),
2365            Default::default(),
2366        ));
2367    }
2368    Ok(DestinationPreflight::OverwriteCandidate(dst_handle))
2369}
2370
2371/// Inspect an overwrite candidate using a regular source's metadata without consuming the
2372/// destination handle. The caller can therefore repeat the decision if payload identity drifts.
2373fn plan_overwrite_candidate(
2374    prog_track: &'static progress::Progress,
2375    dst_handle: &Handle,
2376    src_meta: &FileMeta,
2377    settings: &Settings,
2378) -> OverwriteCandidateDecision {
2379    tracing::debug!("file exists, check if it's identical");
2380    if dst_handle.kind() == EntryKind::File {
2381        if filecmp::metadata_equal(&settings.overwrite_compare, src_meta, dst_handle.meta()) {
2382            tracing::debug!("file is identical, skipping");
2383            prog_track.files_unchanged.inc();
2384            return OverwriteCandidateDecision::Skip(Summary {
2385                files_unchanged: 1,
2386                ..Default::default()
2387            });
2388        }
2389        if let Some(OverwriteFilter::Newer) = settings.overwrite_filter
2390            && filecmp::dest_is_newer(src_meta, dst_handle.meta())
2391        {
2392            tracing::debug!("dest is newer than source, skipping");
2393            prog_track.files_unchanged.inc();
2394            return OverwriteCandidateDecision::Skip(Summary {
2395                files_unchanged: 1,
2396                ..Default::default()
2397            });
2398        }
2399    }
2400    tracing::info!("destination differs, will replace existing entry");
2401    OverwriteCandidateDecision::Replace
2402}
2403
2404/// An opened destination directory plus the bookkeeping the caller needs.
2405pub(crate) struct DirSlot {
2406    pub(crate) dir: Arc<Dir>,
2407    pub(crate) summary: Summary,
2408    pub(crate) is_fresh: bool,
2409    pub(crate) we_created: bool,
2410    /// What the lockdown must undo at finalize (the original owner and the original ACLs), `Some`
2411    /// iff this directory was LOCKED (strict operand resolution + a reused existing directory).
2412    /// `None` for a freshly created directory, which must never be restore-chowned and whose
2413    /// inherited ACLs were stripped outright by `make_dir` rather than snapshotted. Its presence is
2414    /// the "locked" marker.
2415    pub(crate) reused_lock: Option<safedir::ReusedDirLock>,
2416}
2417
2418/// Outcome of resolving a destination directory.
2419pub(crate) enum DirResolution {
2420    /// Proceed into the directory.
2421    Proceed(DirSlot),
2422    /// Skip the whole subtree (e.g. `--ignore-existing` and a non-directory already exists).
2423    Skip(Summary),
2424}
2425
2426/// Create the destination directory `name` under `dst_parent`, or reuse / replace an existing
2427/// entry per `--overwrite`/`--ignore-existing`. Returns an open [`Dir`] handle to it.
2428///
2429/// New directories are created at [`safedir::DST_DIR_CREATE_MODE`] (writable so children can be
2430/// populated) — the real source mode is applied later by [`CopyVisitor::dir_post`] after all
2431/// children are copied, matching the path-based behavior of creating a writable directory and
2432/// restricting it last.
2433pub(crate) async fn resolve_dst_dir(
2434    prog_track: &'static progress::Progress,
2435    dst_parent: &Arc<Dir>,
2436    name: &OsStr,
2437    dst_path: &std::path::Path,
2438    settings: &Settings,
2439    reservation: &safedir::overlap::Reservation,
2440    protection: &Arc<crate::input_protection::InputProtection>,
2441) -> Result<DirResolution, Error> {
2442    let output = reservation.clone();
2443    match dst_parent
2444        .make_dir_checked(name, safedir::DST_DIR_CREATE_MODE, move |meta| {
2445            output.output(meta)?;
2446            output.commit();
2447            Ok(())
2448        })
2449        .await
2450    {
2451        Ok(dir) => {
2452            // freshly created: children may assume the destination is empty (no conflict checks).
2453            prog_track.directories_created.inc();
2454            Ok(DirResolution::Proceed(DirSlot {
2455                dir: Arc::new(dir),
2456                summary: Summary {
2457                    directories_created: 1,
2458                    ..Default::default()
2459                },
2460                is_fresh: true,
2461                we_created: true,
2462                // fresh dirs are already created copier-owned at 0o700, and `make_dir` stripped any
2463                // ACL they inherited; nothing to restore.
2464                reused_lock: None,
2465            }))
2466        }
2467        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2468            // the destination slot is occupied — including when the caller believed the parent was
2469            // fresh: freshness is an optimization hint, not an enforceable invariant. a concurrent
2470            // writer (another source operand of this same invocation whose destination aliases ours,
2471            // a second process, or a destination filesystem that folds two source names onto one)
2472            // can populate a directory we just created. handle it exactly like any other pre-existing
2473            // entry.
2474            let dst_handle = dst_parent
2475                .child(name)
2476                .await
2477                .with_context(|| format!("failed reading metadata from dst: {:?}", dst_path))
2478                .map_err(|err| Error::new(err, Default::default()))?;
2479            if dst_handle.kind() == EntryKind::Dir {
2480                // an existing directory: reuse it.
2481                //
2482                // In the default (non-strict) path we leave it exactly as-is and copy into it: its
2483                // permissions may stop us writing, but the alternative (opening it up while we copy)
2484                // isn't safe. Under strict operand resolution we instead LOCK IT DOWN — take it over
2485                // and restrict it to 0o700 for the copy's duration, restoring the original owner and
2486                // source mode at finalize (see `finalize_dir`) so the final state is unchanged.
2487                tracing::debug!("'dst' is a directory, reusing it");
2488                let (dir, meta) = dst_parent
2489                    .open_dir_with_meta(name)
2490                    .await
2491                    .with_context(|| format!("cannot open existing directory {:?}", dst_path))
2492                    .map_err(|err| Error::new(err, Default::default()))?;
2493                reservation
2494                    .output(&meta)
2495                    .with_context(|| format!("cannot use destination directory {dst_path:?}"))
2496                    .map_err(|error| Error::new(error, Default::default()))?;
2497                // strict-only lockdown: take over the reused directory and restrict it to 0o700 for
2498                // the copy's duration (no-op / None in the default path). A recheck or EPERM failure
2499                // surfaces as this directory's error, honoring --fail-early; `dir_pre` returning Err
2500                // skips descent, so no child is ever written into an unsecured directory.
2501                let mutation = reservation.clone();
2502                let reused_lock = safedir::lockdown_reused_dir_with(&dir, &dst_handle, move || {
2503                    mutation.commit();
2504                })
2505                .await
2506                .with_context(|| {
2507                    format!("cannot secure reused destination directory {:?}", dst_path)
2508                })
2509                .map_err(|err| Error::new(err, Default::default()))?;
2510                prog_track.directories_unchanged.inc();
2511                Ok(DirResolution::Proceed(DirSlot {
2512                    dir: Arc::new(dir),
2513                    summary: Summary {
2514                        directories_unchanged: 1,
2515                        ..Default::default()
2516                    },
2517                    // a directory we did NOT create is never fresh: its children must run their own
2518                    // existence checks.
2519                    is_fresh: false,
2520                    we_created: false,
2521                    reused_lock,
2522                }))
2523            } else if settings.ignore_existing {
2524                // a non-directory exists and --ignore-existing was set: skip the whole subtree.
2525                tracing::debug!(
2526                    "destination exists but is not a directory, skipping subtree (--ignore-existing)"
2527                );
2528                prog_track.directories_unchanged.inc();
2529                Ok(DirResolution::Skip(Summary {
2530                    directories_unchanged: 1,
2531                    ..Default::default()
2532                }))
2533            } else if settings.overwrite {
2534                // a non-directory exists and --overwrite was set: remove it and create the dir.
2535                tracing::info!("'dst' is not a directory, removing and creating a new one");
2536                // only a successful unlink commits history. its blocking job owns the reservation
2537                // until it finishes, including when the awaiting directory admission is cancelled
2538                let mutation = reservation.clone();
2539                let rm_summary = remove_existing_non_directory(
2540                    prog_track,
2541                    dst_parent,
2542                    name,
2543                    dst_path,
2544                    dst_handle.into_removal_snapshot(),
2545                    move || mutation.commit(),
2546                    Some(protection),
2547                )
2548                .await?;
2549                let output = reservation.clone();
2550                let dir = dst_parent
2551                    .make_dir_checked(name, safedir::DST_DIR_CREATE_MODE, move |meta| {
2552                        output.output(meta)?;
2553                        output.commit();
2554                        Ok(())
2555                    })
2556                    .await
2557                    .with_context(|| format!("cannot create directory {:?}", dst_path))
2558                    .map_err(|err| {
2559                        Error::new(
2560                            err,
2561                            Summary {
2562                                rm_summary,
2563                                ..Default::default()
2564                            },
2565                        )
2566                    })?;
2567                prog_track.directories_created.inc();
2568                Ok(DirResolution::Proceed(DirSlot {
2569                    dir: Arc::new(dir),
2570                    summary: Summary {
2571                        rm_summary,
2572                        directories_created: 1,
2573                        ..Default::default()
2574                    },
2575                    is_fresh: true,
2576                    we_created: true,
2577                    // freshly created after removing a non-dir: copier-owned at 0o700 with its
2578                    // inherited ACLs stripped by `make_dir`; nothing to restore.
2579                    reused_lock: None,
2580                }))
2581            } else {
2582                Err(Error::new(
2583                    anyhow!(
2584                        "destination {:?} already exists, did you intend to specify --overwrite?",
2585                        dst_path
2586                    ),
2587                    Default::default(),
2588                ))
2589            }
2590        }
2591        Err(error) => {
2592            let error = anyhow::Error::new(error)
2593                .context(format!("cannot create directory {:?}", dst_path));
2594            tracing::error!("{:#}", &error);
2595            Err(Error::new(error, Default::default()))
2596        }
2597    }
2598}
2599
2600async fn remove_existing_non_directory(
2601    prog_track: &'static progress::Progress,
2602    dst_parent: &Arc<Dir>,
2603    dst_name: &OsStr,
2604    dst_path: &std::path::Path,
2605    dst_snapshot: RemovalSnapshot,
2606    after_unlink: impl FnOnce() + Send + 'static,
2607    protection: Option<&Arc<crate::input_protection::InputProtection>>,
2608) -> Result<RmSummary, Error> {
2609    if let Some(protection) = protection {
2610        protection
2611            .check_child(dst_parent, dst_name, dst_path)
2612            .await
2613            .map_err(|error| Error::new(error.into(), Default::default()))?;
2614    }
2615    let removed_size = dst_snapshot.size();
2616    // single-entry, fd-relative removal contained to dst_parent; never follows a symlink.
2617    dst_parent
2618        .unlink_at_with(dst_name, after_unlink)
2619        .await
2620        .with_context(|| format!("failed removing existing destination {:?}", dst_path))
2621        .map_err(|err| Error::new(err, Default::default()))?;
2622    let is_symlink = dst_snapshot.kind() == EntryKind::Symlink;
2623    if is_symlink {
2624        prog_track.symlinks_removed.inc();
2625    } else {
2626        prog_track.files_removed.inc();
2627        prog_track.bytes_removed.add(removed_size);
2628    }
2629    Ok(RmSummary {
2630        // the summary must carry the same bytes the progress counter just took, or the
2631        // end-of-run totals and the error payloads disagree with the live display. a
2632        // symlink contributes none, matching `rm::rm_file`'s accounting.
2633        bytes_removed: if is_symlink { 0 } else { removed_size },
2634        files_removed: usize::from(!is_symlink),
2635        symlinks_removed: usize::from(is_symlink),
2636        ..Default::default()
2637    })
2638}
2639
2640/// Remove an existing destination entry (file, symlink, directory, or special) so a fresh copy can
2641/// take its place. The returned summary is folded into the caller's copy summary.
2642///
2643/// # Removal contract
2644///
2645/// The caller retains the entry's planned kind and accounting size in `dst_snapshot`, then releases
2646/// its classification fd. Removal is by name through the held `dst_parent` fd:
2647///
2648/// - File / Symlink / Special → [`Dir::unlink_at`] (single entry, never follows a symlink).
2649/// - Empty directory → [`Dir::rmdir_at`].
2650/// - Non-empty directory → fd-relative recursive [`rm::rm_child`] on the held `dst_parent`
2651///   (`O_NOFOLLOW|O_DIRECTORY` descent), the same mechanism the remote destination uses.
2652///
2653/// Every removal is contained to `dst_parent`. A final-component replacement can make the
2654/// kind-directed syscall fail or make it remove a different entry currently occupying `dst_name`,
2655/// but it cannot redirect the operation outside the pinned parent. Re-opening and comparing the
2656/// planned inode would add an `openat` and `fstatat` without closing the remaining window between
2657/// comparison and mutation, and exact final-component identity is outside the overwrite guarantee.
2658/// Overwrite comparison/filter decisions and direct-leaf removal counters therefore describe the
2659/// planning snapshot; a compatible replacement is not re-evaluated before the by-name syscall.
2660pub async fn remove_existing(
2661    prog_track: &'static progress::Progress,
2662    dst_parent: &Arc<Dir>,
2663    dst_name: &OsStr,
2664    dst_path: &std::path::Path,
2665    dst_snapshot: RemovalSnapshot,
2666    settings: &Settings,
2667) -> Result<RmSummary, Error> {
2668    remove_existing_guarded(
2669        prog_track,
2670        dst_parent,
2671        dst_name,
2672        dst_path,
2673        dst_snapshot,
2674        settings,
2675        None,
2676    )
2677    .await
2678}
2679
2680pub(crate) async fn remove_existing_guarded(
2681    prog_track: &'static progress::Progress,
2682    dst_parent: &Arc<Dir>,
2683    dst_name: &OsStr,
2684    dst_path: &std::path::Path,
2685    dst_snapshot: RemovalSnapshot,
2686    settings: &Settings,
2687    protection: Option<&Arc<crate::input_protection::InputProtection>>,
2688) -> Result<RmSummary, Error> {
2689    if dst_snapshot.kind() == EntryKind::Dir
2690        && let Some(protection) = protection
2691    {
2692        // rmdir needs only parent permission; reuse planning's identity before this by-name action.
2693        // nonempty directories still receive a held classification check before chmod and descent
2694        protection
2695            .check_child(dst_parent, dst_name, dst_path)
2696            .await
2697            .and_then(|()| protection.check_directory_identity(dst_snapshot.identity(), dst_path))
2698            .map_err(|error| Error::new(error.into(), Default::default()))?;
2699    }
2700    match dst_snapshot.kind() {
2701        EntryKind::File | EntryKind::Symlink | EntryKind::Special => {
2702            remove_existing_non_directory(
2703                prog_track,
2704                dst_parent,
2705                dst_name,
2706                dst_path,
2707                dst_snapshot,
2708                || {},
2709                protection,
2710            )
2711            .await
2712        }
2713        EntryKind::Dir => {
2714            // try the fd-relative fast path first: an empty directory removes cleanly via rmdir_at.
2715            match dst_parent.rmdir_at(dst_name).await {
2716                Ok(()) => {
2717                    prog_track.directories_removed.inc();
2718                    Ok(RmSummary {
2719                        directories_removed: 1,
2720                        ..Default::default()
2721                    })
2722                }
2723                // POSIX permits either ENOTEMPTY or EEXIST for a non-empty directory.
2724                Err(error)
2725                    if matches!(
2726                        error.raw_os_error(),
2727                        Some(libc::ENOTEMPTY) | Some(libc::EEXIST)
2728                    ) =>
2729                {
2730                    // fd-relative recursive removal of the subtree on the held parent: descent uses
2731                    // O_NOFOLLOW, so a concurrent symlink swap cannot redirect it out of dst_parent.
2732                    // Mirrors the remote destination path.
2733                    rm::rm_child_admitted(
2734                        prog_track,
2735                        dst_parent,
2736                        dst_name,
2737                        dst_path,
2738                        &RmSettings {
2739                            fail_early: settings.fail_early,
2740                            filter: None,
2741                            dry_run: None,
2742                            time_filter: None,
2743                        },
2744                        EntryAdmission::RootOrDelegated,
2745                        protection.cloned(),
2746                    )
2747                    .await
2748                    .map_err(|err| {
2749                        Error::new(
2750                            err.source,
2751                            Summary {
2752                                rm_summary: err.summary,
2753                                ..Default::default()
2754                            },
2755                        )
2756                    })
2757                }
2758                Err(error) => Err(Error::new(
2759                    anyhow::Error::new(error)
2760                        .context(format!("failed removing existing directory {:?}", dst_path)),
2761                    Default::default(),
2762                )),
2763            }
2764        }
2765    }
2766}
2767
2768#[cfg(test)]
2769mod copy_tests {
2770    use crate::testutils;
2771    use anyhow::Context;
2772    use std::os::unix::fs::MetadataExt;
2773    use std::os::unix::fs::PermissionsExt;
2774    use tracing_test::traced_test;
2775
2776    use super::*;
2777
2778    static PROGRESS: std::sync::LazyLock<progress::Progress> =
2779        std::sync::LazyLock::new(progress::Progress::new);
2780    static NO_PRESERVE_SETTINGS: std::sync::LazyLock<preserve::Settings> =
2781        std::sync::LazyLock::new(preserve::preserve_none);
2782    static DO_PRESERVE_SETTINGS: std::sync::LazyLock<preserve::Settings> =
2783        std::sync::LazyLock::new(preserve::preserve_all);
2784
2785    fn settings_with_delete(delete: Option<DeleteSettings>) -> Settings {
2786        Settings {
2787            reflink: Default::default(),
2788            local_copy_handoff: Default::default(),
2789            dereference: false,
2790            fail_early: false,
2791            overwrite: delete.is_some(), // --delete implies --overwrite
2792            overwrite_compare: filecmp::MetadataCmpSettings {
2793                size: true,
2794                mtime: true,
2795                ..Default::default()
2796            },
2797            overwrite_filter: None,
2798            ignore_existing: false,
2799            chunk_size: 0,
2800            skip_specials: false,
2801            remote_copy_buffer_size: 0,
2802            filter: None,
2803            dry_run: None,
2804            delete,
2805        }
2806    }
2807
2808    #[tokio::test]
2809    async fn failed_overwrite_removal_releases_input_history() -> anyhow::Result<()> {
2810        let root = tempfile::tempdir()?;
2811        let src = root.path().join("source");
2812        let next = root.path().join("next");
2813        let dst = root.path().join("occupied");
2814        for path in [&src, &next] {
2815            std::fs::create_dir(path)?;
2816            let mut config = crate::filegen::FileGenConfig::new(path.clone(), vec![], 1, 16);
2817            config.leaf_files = true;
2818            crate::filegen::filegen(&PROGRESS, &config).await?;
2819        }
2820        std::fs::write(&dst, b"keep")?;
2821        let mut settings = settings_with_delete(None);
2822        settings.overwrite = true;
2823        let session = CopySession::default();
2824        let task_session = session.clone();
2825        let task_src = src.clone();
2826        let task_dst = dst.clone();
2827        let task_settings = settings.clone();
2828        let mut gate = testutils::BlockingPathGate::install(dst.join(".rcp-unlink"));
2829        let task = tokio::spawn(async move {
2830            task_session
2831                .copy(
2832                    &PROGRESS,
2833                    &task_src,
2834                    &task_dst,
2835                    &task_settings,
2836                    &NO_PRESERVE_SETTINGS,
2837                    false,
2838                )
2839                .await
2840        });
2841        let timeout = std::time::Duration::from_secs(5);
2842        tokio::time::timeout(timeout, gate.wait_started()).await??;
2843        // a planned non-directory may become a directory; unlink must fail without recursing
2844        let retained = root.path().join("retained");
2845        std::fs::rename(&dst, &retained)?;
2846        std::fs::create_dir(&dst)?;
2847        std::fs::write(dst.join("sentinel"), b"retain directory")?;
2848        gate.release_all();
2849        let error = tokio::time::timeout(timeout, task).await??.unwrap_err();
2850        assert_eq!(gate.hit_count(), 1);
2851        assert_eq!(
2852            error
2853                .source
2854                .downcast_ref::<std::io::Error>()
2855                .unwrap()
2856                .raw_os_error(),
2857            Some(libc::EISDIR)
2858        );
2859        assert_eq!(error.summary.rm_summary.files_removed, 0);
2860        assert_eq!(error.summary.rm_summary.symlinks_removed, 0);
2861        assert_eq!(error.summary.rm_summary.directories_removed, 0);
2862        assert_eq!(error.summary.rm_summary.bytes_removed, 0);
2863        assert_eq!(std::fs::read(&retained)?, b"keep");
2864        assert_eq!(std::fs::read(dst.join("sentinel"))?, b"retain directory");
2865        session
2866            .copy(
2867                &PROGRESS,
2868                &next,
2869                &src.join("out"),
2870                &settings,
2871                &NO_PRESERVE_SETTINGS,
2872                false,
2873            )
2874            .await
2875            .map_err(|error| error.source)?;
2876        assert_eq!(std::fs::metadata(src.join("out/file0"))?.len(), 16);
2877        Ok(())
2878    }
2879
2880    #[tokio::test]
2881    async fn cancelled_overwrite_removal_keeps_input_history_after_success() -> anyhow::Result<()> {
2882        let root = tempfile::tempdir()?;
2883        let src = root.path().join("source");
2884        let dst = root.path().join("occupied");
2885        std::fs::create_dir(&src)?;
2886        std::fs::write(&dst, b"remove")?;
2887        let source_meta = std::fs::metadata(&src)?;
2888        let mut settings = settings_with_delete(None);
2889        settings.overwrite = true;
2890        let session = CopySession::default();
2891        let task_session = session.clone();
2892        let task_src = src.clone();
2893        let task_dst = dst.clone();
2894        let mut gate = testutils::BlockingPathGate::install(dst.join(".rcp-unlink"));
2895        let task = tokio::spawn(async move {
2896            task_session
2897                .copy(
2898                    &PROGRESS,
2899                    &task_src,
2900                    &task_dst,
2901                    &settings,
2902                    &NO_PRESERVE_SETTINGS,
2903                    false,
2904                )
2905                .await
2906        });
2907        let timeout = std::time::Duration::from_secs(5);
2908        tokio::time::timeout(timeout, gate.wait_started()).await??;
2909        task.abort();
2910        assert!(task.await.unwrap_err().is_cancelled());
2911        let conflicts = || {
2912            session
2913                .overlap
2914                .reserve(
2915                    &[],
2916                    &safedir::overlap::Evidence::from([(source_meta.dev(), source_meta.ino())]),
2917                    Arc::new(safedir::overlap::Operand {
2918                        source: root.path().join("next"),
2919                        update: None,
2920                        destination: src.join("out"),
2921                        destination_ancestors: Default::default(),
2922                    }),
2923                )
2924                .is_err()
2925        };
2926        let retained_while_running = conflicts();
2927        gate.release_all();
2928        tokio::time::timeout(timeout, gate.wait_completed()).await??;
2929        assert!(
2930            retained_while_running,
2931            "started removal must retain its input"
2932        );
2933        assert!(
2934            !dst.exists(),
2935            "the started unlink must finish after cancellation"
2936        );
2937        assert!(
2938            conflicts(),
2939            "successful removal must commit its input history"
2940        );
2941        Ok(())
2942    }
2943
2944    #[tokio::test]
2945    async fn ignored_non_directory_still_skips_when_source_acl_read_fails() -> anyhow::Result<()> {
2946        for use_link in [false, true] {
2947            let root = tempfile::tempdir()?;
2948            let src = root.path().join("source");
2949            let dst = root.path().join("destination");
2950            std::fs::create_dir(&src)?;
2951            std::fs::write(&dst, b"keep")?;
2952            let fault =
2953                testutils::BlockingPathGate::fail_once(src.join(".rcp-directory-acl"), libc::EIO);
2954            let mut settings = settings_with_delete(None);
2955            settings.ignore_existing = true;
2956            let preserve = preserve::preserve_all_with_acls();
2957            let summary = if use_link {
2958                crate::link::link(
2959                    &PROGRESS,
2960                    root.path(),
2961                    &src,
2962                    &dst,
2963                    &None,
2964                    &crate::link::Settings {
2965                        copy_settings: settings,
2966                        update_compare: Default::default(),
2967                        update_exclusive: false,
2968                        filter: None,
2969                        dry_run: None,
2970                        preserve,
2971                    },
2972                    false,
2973                )
2974                .await
2975                .map_err(|error| error.source)?
2976                .copy_summary
2977            } else {
2978                copy(&PROGRESS, &src, &dst, &settings, &preserve, false)
2979                    .await
2980                    .map_err(|error| error.source)?
2981            };
2982            assert_eq!(
2983                fault.hit_count(),
2984                1,
2985                "fixture must reach the failing source ACL read"
2986            );
2987            assert_eq!(summary.directories_unchanged, 1);
2988            assert_eq!(std::fs::read(&dst)?, b"keep");
2989        }
2990        Ok(())
2991    }
2992
2993    async fn root_acl_capture_after_ancestry(
2994        use_link: bool,
2995        with_update: bool,
2996    ) -> anyhow::Result<()> {
2997        use crate::testutils::acl::*;
2998        for (before, after) in [(0o2770, 0o750), (0o750, 0o700)] {
2999            let root = tempfile::tempdir()?;
3000            let root_path = root.path().canonicalize()?;
3001            let src = root_path.join("source");
3002            let update = root_path.join("update");
3003            let ancestor = root_path.join("ancestor");
3004            let dst = ancestor.join("parent/destination");
3005            for path in [&src, &update, &dst] {
3006                std::fs::create_dir_all(path)?;
3007            }
3008            std::fs::write(src.join("file"), b"source payload")?;
3009            std::fs::write(update.join("file"), b"update payload")?;
3010            let chosen = if with_update { &update } else { &src };
3011            let acl = encode_acl(&[
3012                (ACL_USER_OBJ, 7, ACL_UNDEFINED_ID),
3013                (ACL_USER, 0, nix::unistd::geteuid().as_raw()),
3014                (ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
3015                (ACL_MASK, 5, ACL_UNDEFINED_ID),
3016                (ACL_OTHER, 0, ACL_UNDEFINED_ID),
3017            ]);
3018            set_xattr_at(chosen, c"system.posix_acl_access", &acl);
3019            std::fs::set_permissions(chosen, std::fs::Permissions::from_mode(before))?;
3020            // ancestry opens this intermediate parent after sampling the input's initial metadata
3021            let mut gate = testutils::BlockingPathGate::install(&ancestor);
3022            let task_src = src.clone();
3023            let task_dst = dst.clone();
3024            let task_update = with_update.then_some(update.clone());
3025            let task = tokio::spawn(async move {
3026                let mut settings = settings_with_delete(None);
3027                settings.overwrite = true;
3028                let preserve = preserve::preserve_all_with_acls();
3029                if use_link {
3030                    crate::link::link(
3031                        &PROGRESS,
3032                        &root_path,
3033                        &task_src,
3034                        &task_dst,
3035                        &task_update,
3036                        &crate::link::Settings {
3037                            copy_settings: settings,
3038                            update_compare: Default::default(),
3039                            update_exclusive: false,
3040                            filter: None,
3041                            dry_run: None,
3042                            preserve,
3043                        },
3044                        false,
3045                    )
3046                    .await
3047                    .map(|summary| summary.copy_summary)
3048                    .map_err(|error| error.source)
3049                } else {
3050                    copy(&PROGRESS, &task_src, &task_dst, &settings, &preserve, false)
3051                        .await
3052                        .map_err(|error| error.source)
3053                }
3054            });
3055            tokio::time::timeout(std::time::Duration::from_secs(5), gate.wait_started()).await??;
3056            std::fs::set_permissions(chosen, std::fs::Permissions::from_mode(after))?;
3057            let expected_acl = get_xattr_at(chosen, c"system.posix_acl_access");
3058            gate.release_all();
3059            task.await?.with_context(|| {
3060                format!(
3061                    "root mode {before:#o} -> {after:#o}, link={use_link}, update={with_update}"
3062                )
3063            })?;
3064            assert!(dst.join("file").is_file());
3065            assert_eq!(
3066                std::fs::metadata(&dst)?.permissions().mode() & 0o7777,
3067                after
3068            );
3069            assert_eq!(get_xattr_at(&dst, c"system.posix_acl_access"), expected_acl);
3070        }
3071        Ok(())
3072    }
3073
3074    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
3075    #[tokio::test]
3076    async fn copy_root_acl_snapshot_refreshes_after_ancestry() -> anyhow::Result<()> {
3077        root_acl_capture_after_ancestry(false, false).await
3078    }
3079
3080    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
3081    #[tokio::test]
3082    async fn link_root_acl_snapshot_refreshes_after_ancestry() -> anyhow::Result<()> {
3083        root_acl_capture_after_ancestry(true, false).await
3084    }
3085
3086    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
3087    #[tokio::test]
3088    async fn link_update_root_acl_snapshot_refreshes_after_ancestry() -> anyhow::Result<()> {
3089        root_acl_capture_after_ancestry(true, true).await
3090    }
3091
3092    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
3093    #[test]
3094    fn strict_root_acl_snapshot_refreshes_after_ancestry() -> anyhow::Result<()> {
3095        const CHILD: &str = "RCP_TEST_STRICT_ROOT_ACL_SNAPSHOT";
3096        if std::env::var_os(CHILD).is_some() {
3097            // strict mode is process-global, so it must not leak into other libtest tests
3098            safedir::enable_strict_operand_resolution();
3099            return tokio::runtime::Runtime::new()?.block_on(async {
3100                for (use_link, with_update) in [(false, false), (true, false), (true, true)] {
3101                    root_acl_capture_after_ancestry(use_link, with_update).await?;
3102                }
3103                Ok(())
3104            });
3105        }
3106        let output = std::process::Command::new(std::env::current_exe()?)
3107            .args([
3108                "--exact",
3109                "copy::copy_tests::strict_root_acl_snapshot_refreshes_after_ancestry",
3110                "--nocapture",
3111            ])
3112            .env(CHILD, "1")
3113            .output()?;
3114        let stdout = String::from_utf8_lossy(&output.stdout);
3115        assert!(
3116            output.status.success() && stdout.contains("1 passed; 0 failed"),
3117            "strict root ACL test did not pass: {stdout}\n{}",
3118            String::from_utf8_lossy(&output.stderr)
3119        );
3120        Ok(())
3121    }
3122
3123    fn delete_on() -> Option<DeleteSettings> {
3124        Some(DeleteSettings {
3125            delete_excluded: false,
3126        })
3127    }
3128
3129    /// Runs admission-sensitive work and proves its sole open-file permit is returned afterwards.
3130    async fn run_with_open_file_cleanup<F>(
3131        admission: &testutils::AdmissionLimit,
3132        operation: F,
3133    ) -> Result<F::Output, anyhow::Error>
3134    where
3135        F: std::future::Future,
3136    {
3137        let output = admission
3138            .run_with_timeout(std::time::Duration::from_secs(20), operation)
3139            .await
3140            .context("copy operation did not finish at an open-file limit of one")?;
3141        let returned = admission
3142            .run_with_timeout(
3143                std::time::Duration::from_secs(20),
3144                throttle::open_file_permit(),
3145            )
3146            .await
3147            .context("copy operation did not return open-file capacity")?;
3148        drop(returned);
3149        Ok(output)
3150    }
3151
3152    // Regression: a source operand whose final component is `.`/`..` (e.g. `rcp tree/sub/.. dst`,
3153    // `rcp . dst`) must be copied, not rejected — `split_root_operand` canonicalizes it. Uses
3154    // `tree/sub/..` (== `tree`) rather than `.` to avoid touching the process-wide cwd.
3155    #[tokio::test]
3156    async fn copies_dot_dot_source_operand() -> Result<(), anyhow::Error> {
3157        let tmp = testutils::create_temp_dir().await?;
3158        let tree = tmp.join("tree");
3159        tokio::fs::create_dir(&tree).await?;
3160        tokio::fs::write(tree.join("a.txt"), "hello").await?;
3161        tokio::fs::create_dir(tree.join("sub")).await?;
3162        let src = tree.join("sub").join(".."); // == tree
3163        let dst = tmp.join("dst");
3164        let summary = copy(
3165            &PROGRESS,
3166            &src,
3167            &dst,
3168            &settings_with_delete(None),
3169            &NO_PRESERVE_SETTINGS,
3170            false,
3171        )
3172        .await?;
3173        assert_eq!(
3174            summary.files_copied, 1,
3175            "the dot-dot source's file must be copied"
3176        );
3177        assert_eq!(tokio::fs::read_to_string(dst.join("a.txt")).await?, "hello");
3178        assert!(
3179            dst.join("sub").is_dir(),
3180            "the dot-dot source's subdir must be copied"
3181        );
3182        Ok(())
3183    }
3184
3185    #[tokio::test]
3186    async fn delegated_destination_paths_keep_original_root_and_logical_seed() -> anyhow::Result<()>
3187    {
3188        use std::os::unix::ffi::OsStrExt;
3189        let temp = testutils::create_temp_dir().await?;
3190        let parent = Arc::new(Dir::open_root_dir(&temp, false, congestion::Side::Source).await?);
3191        let visitor = CopyVisitor {
3192            prog_track: &PROGRESS,
3193            dst_root: PathBuf::from("destination//./renamed"),
3194            destination: DestinationContext::parent(None),
3195            settings: settings_with_delete(None),
3196            preserve: *NO_PRESERVE_SETTINGS,
3197            dst_parent: None,
3198            root_is_fresh: false,
3199        };
3200        for physical in ["source-root", "update-root"] {
3201            let cx = EntryCx::root(
3202                Arc::clone(&parent),
3203                OsStr::new(physical).to_owned(),
3204                PathBuf::from(physical),
3205                &PROGRESS,
3206            );
3207            assert_eq!(
3208                visitor.dst_path_for(&cx).as_os_str().as_bytes(),
3209                b"destination//./renamed"
3210            );
3211            assert_eq!(visitor.dst_name_for(&cx)?, OsStr::new("renamed"));
3212        }
3213        for (relative, name, expected) in [
3214            (
3215                b"cache\xfe".as_slice(),
3216                b"cache\xfe".as_slice(),
3217                b"destination//./renamed/cache\xfe".as_slice(),
3218            ),
3219            (
3220                b"cache\xfe/branch\xff",
3221                b"branch\xff",
3222                b"destination//./renamed/cache\xfe/branch\xff",
3223            ),
3224            (
3225                b"cache\xfe/branch\xff/leaf\xfd",
3226                b"leaf\xfd",
3227                b"destination//./renamed/cache\xfe/branch\xff/leaf\xfd",
3228            ),
3229        ] {
3230            let relative = std::path::Path::new(OsStr::from_bytes(relative));
3231            let name = OsStr::from_bytes(name);
3232            let cx = EntryCx::root(
3233                Arc::clone(&parent),
3234                name.to_owned(),
3235                PathBuf::from("update//./tree").join(relative),
3236                &PROGRESS,
3237            )
3238            .with_relative_path(relative.to_path_buf());
3239            assert_eq!(visitor.dst_path_for(&cx).as_os_str().as_bytes(), expected);
3240            assert_eq!(visitor.dst_name_for(&cx)?, name);
3241        }
3242        Ok(())
3243    }
3244
3245    #[tokio::test]
3246    #[traced_test]
3247    async fn delete_protects_skipped_special_name() -> Result<(), anyhow::Error> {
3248        let tmp_dir = testutils::setup_test_dir().await?;
3249        let test_path = tmp_dir.as_path();
3250        let src = test_path.join("src_dir");
3251        let dst = test_path.join("dst_dir");
3252        tokio::fs::create_dir(&src).await?;
3253        tokio::fs::write(src.join("file.txt"), "hello").await?;
3254        // a special file in the source that --skip-specials will skip copying
3255        nix::unistd::mkfifo(
3256            &src.join("pipe"),
3257            nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
3258        )?;
3259        // pre-existing destination: a counterpart for the skipped special, plus a genuine extra
3260        tokio::fs::create_dir(&dst).await?;
3261        tokio::fs::write(dst.join("pipe"), "old").await?;
3262        tokio::fs::write(dst.join("stale.txt"), "junk").await?;
3263
3264        let mut settings = settings_with_delete(delete_on());
3265        settings.skip_specials = true;
3266        let summary = copy(
3267            &PROGRESS,
3268            &src,
3269            &dst,
3270            &settings,
3271            &DO_PRESERVE_SETTINGS,
3272            false,
3273        )
3274        .await?;
3275
3276        assert_eq!(summary.specials_skipped, 1);
3277        assert!(dst.join("file.txt").exists());
3278        assert!(
3279            dst.join("pipe").exists(),
3280            "a destination entry matching a skipped special must not be pruned (it has a source counterpart)"
3281        );
3282        assert!(!dst.join("stale.txt").exists()); // genuine extra removed
3283        Ok(())
3284    }
3285
3286    // FIX A (PR #247 review): the operand's TRUSTED parent prefix must be resolved following
3287    // symlinks. `rcp file symlink_to_dir/out` copies into the REAL directory the symlinked parent
3288    // points at (the parent prefix is trusted up to and including the operand's container); it must
3289    // NOT fail closed with ELOOP/ENOTDIR. The hardening only applies strictly below the named root.
3290    #[tokio::test]
3291    #[traced_test]
3292    async fn copies_into_symlinked_destination_parent() -> Result<(), anyhow::Error> {
3293        let tmp_dir = testutils::setup_test_dir().await?;
3294        let test_path = tmp_dir.as_path();
3295        let src = test_path.join("src.txt");
3296        tokio::fs::write(&src, b"payload").await?;
3297        // a real destination directory and a symlink-to-dir parent prefix pointing at it.
3298        let real_dir = test_path.join("real_dst_dir");
3299        tokio::fs::create_dir(&real_dir).await?;
3300        let link_dir = test_path.join("link_dst_dir");
3301        tokio::fs::symlink(&real_dir, &link_dir).await?;
3302        // destination operand sits UNDER the symlinked (trusted) parent prefix.
3303        let dst = link_dir.join("out.txt");
3304        let summary = copy(
3305            &PROGRESS,
3306            &src,
3307            &dst,
3308            &settings_with_delete(None),
3309            &DO_PRESERVE_SETTINGS,
3310            false,
3311        )
3312        .await?;
3313        assert_eq!(summary.files_copied, 1);
3314        // the file landed in the REAL directory (the symlinked parent was followed).
3315        let written = tokio::fs::read(real_dir.join("out.txt")).await?;
3316        assert_eq!(written, b"payload");
3317        Ok(())
3318    }
3319
3320    // FIX A (PR #247 review): a symlinked SOURCE parent prefix is likewise followed —
3321    // `rcp symlinkdir/src dst` reads the file through the real directory.
3322    #[tokio::test]
3323    #[traced_test]
3324    async fn copies_from_symlinked_source_parent() -> Result<(), anyhow::Error> {
3325        let tmp_dir = testutils::setup_test_dir().await?;
3326        let test_path = tmp_dir.as_path();
3327        // a real source directory containing the file, reached via a symlinked parent prefix.
3328        let real_src_dir = test_path.join("real_src_dir");
3329        tokio::fs::create_dir(&real_src_dir).await?;
3330        tokio::fs::write(real_src_dir.join("src.txt"), b"payload").await?;
3331        let link_src_dir = test_path.join("link_src_dir");
3332        tokio::fs::symlink(&real_src_dir, &link_src_dir).await?;
3333        let src = link_src_dir.join("src.txt");
3334        let dst = test_path.join("out.txt");
3335        let summary = copy(
3336            &PROGRESS,
3337            &src,
3338            &dst,
3339            &settings_with_delete(None),
3340            &DO_PRESERVE_SETTINGS,
3341            false,
3342        )
3343        .await?;
3344        assert_eq!(summary.files_copied, 1);
3345        let written = tokio::fs::read(&dst).await?;
3346        assert_eq!(written, b"payload");
3347        Ok(())
3348    }
3349
3350    #[tokio::test]
3351    #[traced_test]
3352    async fn delete_removes_extraneous_destination_entries() -> Result<(), anyhow::Error> {
3353        let tmp_dir = testutils::setup_test_dir().await?;
3354        let test_path = tmp_dir.as_path();
3355        let src = test_path.join("foo");
3356        let dst = test_path.join("bar");
3357        // initial copy (no delete)
3358        copy(
3359            &PROGRESS,
3360            &src,
3361            &dst,
3362            &settings_with_delete(None),
3363            &DO_PRESERVE_SETTINGS,
3364            false,
3365        )
3366        .await?;
3367        // introduce extraneous entries at the destination
3368        tokio::fs::write(dst.join("extraneous.txt"), b"junk").await?;
3369        tokio::fs::create_dir(dst.join("extra_dir")).await?;
3370        tokio::fs::write(dst.join("extra_dir").join("nested.txt"), b"junk").await?;
3371        // re-copy with --delete
3372        let summary = copy(
3373            &PROGRESS,
3374            &src,
3375            &dst,
3376            &settings_with_delete(delete_on()),
3377            &DO_PRESERVE_SETTINGS,
3378            false,
3379        )
3380        .await?;
3381        assert_eq!(summary.rm_summary.files_removed, 2); // extraneous.txt + extra_dir/nested.txt
3382        assert_eq!(summary.rm_summary.directories_removed, 1); // extra_dir
3383        assert!(!dst.join("extraneous.txt").exists());
3384        assert!(!dst.join("extra_dir").exists());
3385        testutils::check_dirs_identical(&src, &dst, testutils::FileEqualityCheck::Basic).await?;
3386        Ok(())
3387    }
3388
3389    #[tokio::test]
3390    #[traced_test]
3391    async fn delete_prunes_extraneous_at_depth() -> Result<(), anyhow::Error> {
3392        let tmp_dir = testutils::setup_test_dir().await?;
3393        let test_path = tmp_dir.as_path();
3394        let src = test_path.join("foo");
3395        let dst = test_path.join("bar");
3396        copy(
3397            &PROGRESS,
3398            &src,
3399            &dst,
3400            &settings_with_delete(None),
3401            &DO_PRESERVE_SETTINGS,
3402            false,
3403        )
3404        .await?;
3405        // foo/bar is a common subdirectory; place a stale file inside the dst copy of it
3406        let nested = dst.join("bar");
3407        assert!(
3408            nested.is_dir(),
3409            "expected common subdirectory bar/ to exist at destination"
3410        );
3411        tokio::fs::write(nested.join("stale_nested.txt"), b"junk").await?;
3412        let summary = copy(
3413            &PROGRESS,
3414            &src,
3415            &dst,
3416            &settings_with_delete(delete_on()),
3417            &DO_PRESERVE_SETTINGS,
3418            false,
3419        )
3420        .await?;
3421        assert!(
3422            !nested.join("stale_nested.txt").exists(),
3423            "stale entry inside a common subdirectory must be pruned"
3424        );
3425        assert!(summary.rm_summary.files_removed >= 1);
3426        testutils::check_dirs_identical(&src, &dst, testutils::FileEqualityCheck::Basic).await?;
3427        Ok(())
3428    }
3429
3430    #[tokio::test]
3431    #[traced_test]
3432    async fn delete_removes_extraneous_symlink() -> Result<(), anyhow::Error> {
3433        let tmp_dir = testutils::setup_test_dir().await?;
3434        let test_path = tmp_dir.as_path();
3435        let src = test_path.join("foo");
3436        let dst = test_path.join("bar");
3437        copy(
3438            &PROGRESS,
3439            &src,
3440            &dst,
3441            &settings_with_delete(None),
3442            &DO_PRESERVE_SETTINGS,
3443            false,
3444        )
3445        .await?;
3446        // an extraneous symlink at the destination root (no source counterpart)
3447        tokio::fs::symlink("/nonexistent/target", dst.join("stale_link")).await?;
3448        let summary = copy(
3449            &PROGRESS,
3450            &src,
3451            &dst,
3452            &settings_with_delete(delete_on()),
3453            &DO_PRESERVE_SETTINGS,
3454            false,
3455        )
3456        .await?;
3457        assert!(
3458            tokio::fs::symlink_metadata(dst.join("stale_link"))
3459                .await
3460                .is_err(),
3461            "extraneous symlink must be removed"
3462        );
3463        assert_eq!(summary.rm_summary.symlinks_removed, 1);
3464        Ok(())
3465    }
3466
3467    #[tokio::test]
3468    async fn rejects_destination_inside_source_before_creating_it() -> anyhow::Result<()> {
3469        for preview in [false, true] {
3470            let root = tempfile::tempdir()?;
3471            let src = root.path().join("src");
3472            let dst = src.join("dst");
3473            tokio::fs::create_dir(&src).await?;
3474            let mut config = crate::filegen::FileGenConfig::new(&src, vec![], 1, 32);
3475            config.leaf_files = true;
3476            crate::filegen::filegen(&PROGRESS, &config).await?;
3477            let original = tokio::fs::read(src.join("file0")).await?;
3478            let mut filter = crate::filter::FilterSettings::new();
3479            // keep the old implementation finite without hiding the invalid destination
3480            filter.add_exclude("dst/")?;
3481            let mut settings = settings_with_delete(None);
3482            settings.filter = Some(filter);
3483            settings.dry_run = preview.then_some(crate::config::DryRunMode::Brief);
3484            let error = copy(
3485                &PROGRESS,
3486                &src,
3487                &dst,
3488                &settings,
3489                &NO_PRESERVE_SETTINGS,
3490                false,
3491            )
3492            .await
3493            .expect_err("a destination inside its source must be rejected");
3494            assert!(format!("{:#}", error.source).contains("overlap"));
3495            assert_eq!(error.summary.directories_created, 0);
3496            assert!(!dst.exists());
3497            assert_eq!(tokio::fs::read(src.join("file0")).await?, original);
3498        }
3499        Ok(())
3500    }
3501
3502    #[tokio::test]
3503    async fn rejects_overlapping_destination_without_changing_existing_contents()
3504    -> anyhow::Result<()> {
3505        use std::os::unix::fs::PermissionsExt;
3506        for suffix in ["", "nested/dst"] {
3507            for preview in [false, true] {
3508                let root = tempfile::tempdir()?;
3509                let src = root.path().join("src");
3510                let physical_dst = src.join(suffix);
3511                tokio::fs::create_dir_all(&physical_dst).await?;
3512                let mut config = crate::filegen::FileGenConfig::new(&src, vec![], 1, 32);
3513                config.leaf_files = true;
3514                crate::filegen::filegen(&PROGRESS, &config).await?;
3515                let original = tokio::fs::read(src.join("file0")).await?;
3516                tokio::fs::write(physical_dst.join("sentinel"), b"keep").await?;
3517                tokio::fs::set_permissions(&physical_dst, std::fs::Permissions::from_mode(0o751))
3518                    .await?;
3519                // resolve the destination through a symlinked parent, not a lexical source prefix
3520                let alias = root.path().join("alias");
3521                tokio::fs::symlink(root.path(), &alias).await?;
3522                let dst = alias.join("src").join(suffix);
3523                let mut settings = settings_with_delete(delete_on());
3524                settings.dry_run = preview.then_some(crate::config::DryRunMode::Brief);
3525                let mut filter = crate::filter::FilterSettings::new();
3526                filter.add_exclude("nested/")?;
3527                settings.filter = Some(filter);
3528                let error = copy(
3529                    &PROGRESS,
3530                    &src,
3531                    &dst,
3532                    &settings,
3533                    &NO_PRESERVE_SETTINGS,
3534                    false,
3535                )
3536                .await
3537                .expect_err("overlapping directories must be rejected");
3538                assert!(format!("{:#}", error.source).contains("overlap"));
3539                assert_eq!(error.summary.directories_created, 0);
3540                assert_eq!(tokio::fs::read(src.join("file0")).await?, original);
3541                assert_eq!(
3542                    tokio::fs::read(physical_dst.join("sentinel")).await?,
3543                    b"keep"
3544                );
3545                assert_eq!(
3546                    tokio::fs::metadata(&physical_dst)
3547                        .await?
3548                        .permissions()
3549                        .mode()
3550                        & 0o777,
3551                    0o751
3552                );
3553            }
3554        }
3555        Ok(())
3556    }
3557
3558    #[tokio::test]
3559    async fn delete_preserves_live_names_omitted_from_listing() -> anyhow::Result<()> {
3560        use std::os::unix::ffi::OsStrExt;
3561        for rename_source in [false, true] {
3562            let root = tempfile::tempdir()?;
3563            let src = root.path().join("src");
3564            let dst = root.path().join("dst");
3565            let held = root.path().join("held-source");
3566            tokio::fs::create_dir(&src).await?;
3567            tokio::fs::create_dir(&dst).await?;
3568            let mut config = crate::filegen::FileGenConfig::new(&src, vec![], 1, 32);
3569            config.leaf_files = true;
3570            crate::filegen::filegen(&PROGRESS, &config).await?;
3571            let raw_name = std::ffi::OsStr::from_bytes(b"non-utf8-\xff");
3572            for name in [
3573                std::ffi::OsStr::new("file"),
3574                std::ffi::OsStr::new("dangling"),
3575                raw_name,
3576            ] {
3577                tokio::fs::write(dst.join(name), b"retained destination").await?;
3578            }
3579            tokio::fs::create_dir(dst.join("directory")).await?;
3580            tokio::fs::write(dst.join("directory/child"), b"retained child").await?;
3581            tokio::fs::write(dst.join("extra"), b"remove me").await?;
3582            let mut gate = testutils::BlockingPathGate::install(dst.join("file0"));
3583            let task_src = src.clone();
3584            let task_dst = dst.clone();
3585            let task = tokio::spawn(async move {
3586                copy(
3587                    &PROGRESS,
3588                    &task_src,
3589                    &task_dst,
3590                    &settings_with_delete(delete_on()),
3591                    &NO_PRESERVE_SETTINGS,
3592                    false,
3593                )
3594                .await
3595            });
3596            let timeout = std::time::Duration::from_secs(20);
3597            let started = tokio::time::timeout(timeout, gate.wait_started()).await;
3598            // the real walker already collected its names before this payload worker started
3599            let mutation = async {
3600                let live_source = if rename_source {
3601                    tokio::fs::rename(&src, &held).await?;
3602                    tokio::fs::create_dir(&src).await?;
3603                    &held
3604                } else {
3605                    &src
3606                };
3607                tokio::fs::write(live_source.join("file"), b"new source").await?;
3608                tokio::fs::write(live_source.join(raw_name), b"new source").await?;
3609                tokio::fs::symlink("missing-target", live_source.join("dangling")).await?;
3610                tokio::fs::create_dir(live_source.join("directory")).await?;
3611                Ok::<_, anyhow::Error>(())
3612            }
3613            .await;
3614            gate.release_all();
3615            let result = tokio::time::timeout(timeout, task).await;
3616            started??;
3617            mutation?;
3618            let summary = result???;
3619            for name in [
3620                std::ffi::OsStr::new("file"),
3621                std::ffi::OsStr::new("dangling"),
3622                raw_name,
3623            ] {
3624                assert!(
3625                    dst.join(name).exists(),
3626                    "pruned {name:?} despite its live source counterpart; renamed={rename_source}"
3627                );
3628                assert_eq!(
3629                    tokio::fs::read(dst.join(name)).await?,
3630                    b"retained destination",
3631                    "live source {name:?} was omitted from enumeration; renamed={rename_source}"
3632                );
3633            }
3634            assert_eq!(
3635                tokio::fs::read(dst.join("directory/child")).await?,
3636                b"retained child"
3637            );
3638            assert!(!dst.join("extra").exists());
3639            assert_eq!(summary.files_copied, 1);
3640            assert_eq!(summary.rm_summary.files_removed, 1);
3641            assert_eq!(summary.rm_summary.directories_removed, 0);
3642        }
3643        Ok(())
3644    }
3645
3646    #[tokio::test]
3647    async fn delete_reports_source_lookup_errors_without_pruning() -> anyhow::Result<()> {
3648        if nix::unistd::geteuid().is_root() {
3649            eprintln!("skipping permission-denial case: root bypasses directory permissions");
3650            return Ok(());
3651        }
3652        for fail_early in [false, true] {
3653            let root = tempfile::tempdir()?;
3654            let src = root.path().join("src");
3655            let dst = root.path().join("dst");
3656            tokio::fs::create_dir(&src).await?;
3657            tokio::fs::create_dir(&dst).await?;
3658            let mut config = crate::filegen::FileGenConfig::new(&src, vec![], 1, 32);
3659            config.leaf_files = true;
3660            crate::filegen::filegen(&PROGRESS, &config).await?;
3661            for name in ["first", "second"] {
3662                tokio::fs::write(dst.join(name), b"retain on lookup error").await?;
3663            }
3664            let mut gate = testutils::BlockingPathGate::install(dst.join("file0"));
3665            let task_src = src.clone();
3666            let task_dst = dst.clone();
3667            let task = tokio::spawn(async move {
3668                let mut settings = settings_with_delete(delete_on());
3669                settings.fail_early = fail_early;
3670                copy(
3671                    &PROGRESS,
3672                    &task_src,
3673                    &task_dst,
3674                    &settings,
3675                    &NO_PRESERVE_SETTINGS,
3676                    false,
3677                )
3678                .await
3679            });
3680            let timeout = std::time::Duration::from_secs(20);
3681            let started = tokio::time::timeout(timeout, gate.wait_started()).await;
3682            let permissions =
3683                tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o600)).await;
3684            gate.release_all();
3685            let result = tokio::time::timeout(timeout, task).await;
3686            tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o700)).await?;
3687            started??;
3688            permissions?;
3689            let error =
3690                result??.expect_err("an unavailable source lookup cannot authorize pruning");
3691            assert_eq!(
3692                error
3693                    .source
3694                    .downcast_ref::<std::io::Error>()
3695                    .unwrap()
3696                    .raw_os_error(),
3697                Some(libc::EACCES)
3698            );
3699            assert_eq!(error.summary.rm_summary.files_removed, 0);
3700            for name in ["first", "second"] {
3701                assert_eq!(
3702                    tokio::fs::read(dst.join(name)).await?,
3703                    b"retain on lookup error"
3704                );
3705            }
3706        }
3707        Ok(())
3708    }
3709
3710    #[derive(Clone, Copy, PartialEq, Eq)]
3711    enum PreviewOperation {
3712        Copy,
3713        Link,
3714        DelegatedCopy,
3715        Dereference,
3716    }
3717
3718    async fn preview_retains_opened_destination_case(mode: PreviewOperation) -> anyhow::Result<()> {
3719        let root = testutils::create_temp_dir().await?;
3720        let src = root.join("source");
3721        let update = root.join("update");
3722        let dst = root.join("destination");
3723        let held = root.join("held-destination");
3724        tokio::fs::create_dir(&src).await?;
3725        if mode == PreviewOperation::DelegatedCopy {
3726            tokio::fs::create_dir_all(update.join("a/b")).await?;
3727        } else if mode == PreviewOperation::Dereference {
3728            tokio::fs::create_dir_all(root.join("target/b")).await?;
3729            tokio::fs::symlink(root.join("target"), src.join("a")).await?;
3730        } else {
3731            tokio::fs::create_dir_all(src.join("a/b")).await?;
3732        }
3733        tokio::fs::create_dir_all(dst.join("a/b")).await?;
3734        tokio::fs::write(dst.join("a/b/original"), b"ORIGINAL").await?;
3735        tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o751)).await?;
3736        let mut gate = testutils::BlockingPathGate::install(dst.clone());
3737        let mut settings = settings_with_delete(delete_on());
3738        settings.dry_run = Some(DryRunMode::Brief);
3739        settings.dereference = mode == PreviewOperation::Dereference;
3740        let task_root = root.clone();
3741        let task_dst = dst.clone();
3742        let task = tokio::spawn(async move {
3743            if mode == PreviewOperation::Link || mode == PreviewOperation::DelegatedCopy {
3744                crate::link::link(
3745                    &PROGRESS,
3746                    &task_root,
3747                    &src,
3748                    &task_dst,
3749                    &if mode == PreviewOperation::DelegatedCopy {
3750                        Some(update)
3751                    } else {
3752                        None
3753                    },
3754                    &crate::link::Settings {
3755                        copy_settings: settings.clone(),
3756                        update_compare: Default::default(),
3757                        update_exclusive: false,
3758                        filter: None,
3759                        dry_run: settings.dry_run,
3760                        preserve: *NO_PRESERVE_SETTINGS,
3761                    },
3762                    false,
3763                )
3764                .await
3765                .map(|summary| summary.copy_summary)
3766                .map_err(|error| error.source)
3767            } else {
3768                copy(
3769                    &PROGRESS,
3770                    &src,
3771                    &task_dst,
3772                    &settings,
3773                    &NO_PRESERVE_SETTINGS,
3774                    false,
3775                )
3776                .await
3777                .map_err(|error| error.source)
3778            }
3779        });
3780        let timeout = std::time::Duration::from_secs(20);
3781        let started = tokio::time::timeout(timeout, gate.wait_started()).await;
3782        let replacement = async {
3783            tokio::fs::rename(&dst, &held).await?;
3784            tokio::fs::create_dir_all(dst.join("a/b")).await?;
3785            tokio::fs::write(dst.join("a/b/replacement-1"), b"UNSELECTED").await?;
3786            tokio::fs::write(dst.join("a/b/replacement-2"), b"UNSELECTED").await?;
3787            Ok::<_, anyhow::Error>(())
3788        }
3789        .await;
3790        gate.release_all();
3791        let result = tokio::time::timeout(timeout, task).await;
3792        started??;
3793        replacement?;
3794        let summary = result???;
3795        assert_eq!(
3796            summary.rm_summary.files_removed, 1,
3797            "preview must enumerate the original held tree"
3798        );
3799        assert_eq!(gate.hit_count(), 1, "the operand must only be opened once");
3800        assert_eq!(
3801            tokio::fs::read(held.join("a/b/original")).await?,
3802            b"ORIGINAL"
3803        );
3804        assert_eq!(tokio::fs::metadata(&held).await?.mode() & 0o777, 0o751);
3805        assert_eq!(
3806            tokio::fs::read(dst.join("a/b/replacement-1")).await?,
3807            b"UNSELECTED"
3808        );
3809        assert_eq!(
3810            tokio::fs::read(dst.join("a/b/replacement-2")).await?,
3811            b"UNSELECTED"
3812        );
3813        Ok(())
3814    }
3815
3816    #[tokio::test]
3817    async fn copy_preview_retains_opened_destination_across_rename() -> anyhow::Result<()> {
3818        preview_retains_opened_destination_case(PreviewOperation::Copy).await
3819    }
3820
3821    #[tokio::test]
3822    async fn link_preview_retains_opened_destination_across_rename() -> anyhow::Result<()> {
3823        preview_retains_opened_destination_case(PreviewOperation::Link).await
3824    }
3825
3826    #[tokio::test]
3827    async fn delegated_preview_retains_opened_destination_across_rename() -> anyhow::Result<()> {
3828        preview_retains_opened_destination_case(PreviewOperation::DelegatedCopy).await
3829    }
3830
3831    #[tokio::test]
3832    async fn dereferenced_preview_retains_opened_destination_across_rename() -> anyhow::Result<()> {
3833        preview_retains_opened_destination_case(PreviewOperation::Dereference).await
3834    }
3835
3836    async fn prune_error_preserves_partial_counts_and_finalization_case(
3837        use_link: bool,
3838    ) -> anyhow::Result<()> {
3839        if nix::unistd::geteuid().is_root() {
3840            eprintln!("skipping permission-denial case: root bypasses directory permissions");
3841            return Ok(());
3842        }
3843        for fail_early in [false, true] {
3844            let tmp = tempfile::tempdir()?;
3845            let root = tmp.path();
3846            let src = root.join("source");
3847            let dst = root.join("destination");
3848            tokio::fs::create_dir(&src).await?;
3849            tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o751)).await?;
3850            for child in ["extra1", "extra2"] {
3851                tokio::fs::create_dir_all(dst.join(child)).await?;
3852                tokio::fs::write(dst.join(child).join("file"), b"abc").await?;
3853            }
3854            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o500)).await?;
3855            let mut settings = settings_with_delete(delete_on());
3856            settings.fail_early = fail_early;
3857            let mut preserve = *NO_PRESERVE_SETTINGS;
3858            preserve.dir.mode_mask = 0o777;
3859            let result = if use_link {
3860                crate::link::link(
3861                    &PROGRESS,
3862                    root,
3863                    &src,
3864                    &dst,
3865                    &None,
3866                    &crate::link::Settings {
3867                        copy_settings: settings.clone(),
3868                        update_compare: Default::default(),
3869                        update_exclusive: false,
3870                        filter: None,
3871                        dry_run: None,
3872                        preserve,
3873                    },
3874                    false,
3875                )
3876                .await
3877                .map(|summary| summary.copy_summary)
3878                .map_err(|error| (error.source, error.summary.copy_summary))
3879            } else {
3880                copy(&PROGRESS, &src, &dst, &settings, &preserve, false)
3881                    .await
3882                    .map_err(|error| (error.source, error.summary))
3883            };
3884            let final_mode = tokio::fs::metadata(&dst).await?.permissions().mode() & 0o777;
3885            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
3886            let (error, summary) =
3887                result.expect_err("parent permissions must prevent pruning directories");
3888            assert_eq!(
3889                error
3890                    .downcast_ref::<std::io::Error>()
3891                    .unwrap()
3892                    .raw_os_error(),
3893                Some(libc::EACCES)
3894            );
3895            let removed = if fail_early { 1 } else { 2 };
3896            assert_eq!(summary.rm_summary.files_removed, removed);
3897            assert_eq!(summary.rm_summary.bytes_removed, 3 * removed as u64);
3898            assert_eq!(summary.rm_summary.directories_removed, 0);
3899            assert_eq!(
3900                ["extra1", "extra2"]
3901                    .iter()
3902                    .filter(|child| dst.join(child).join("file").exists())
3903                    .count(),
3904                2 - removed,
3905            );
3906            assert_eq!(
3907                final_mode,
3908                if fail_early { 0o500 } else { 0o751 },
3909                "keep-going must finalize directory metadata after a prune failure"
3910            );
3911        }
3912        Ok(())
3913    }
3914
3915    #[tokio::test]
3916    async fn copy_prune_error_preserves_partial_counts_and_finalization() -> anyhow::Result<()> {
3917        prune_error_preserves_partial_counts_and_finalization_case(false).await
3918    }
3919
3920    #[tokio::test]
3921    async fn link_prune_error_preserves_partial_counts_and_finalization() -> anyhow::Result<()> {
3922        prune_error_preserves_partial_counts_and_finalization_case(true).await
3923    }
3924
3925    async fn preview_stops_at_unreadable_destination_case(use_link: bool) -> anyhow::Result<()> {
3926        for dry_run in [false, true] {
3927            let root = testutils::create_temp_dir().await?;
3928            let src = root.join("source");
3929            let dst = root.join("destination");
3930            for child in ["x", "y"] {
3931                tokio::fs::create_dir_all(src.join("blocked").join(child)).await?;
3932                tokio::fs::write(src.join("blocked").join(child).join("file"), b"BLOCKED").await?;
3933            }
3934            tokio::fs::write(src.join("sibling"), b"COPY").await?;
3935            tokio::fs::create_dir_all(dst.join("blocked")).await?;
3936            tokio::fs::write(dst.join("sentinel"), b"KEEP").await?;
3937            tokio::fs::set_permissions(dst.join("blocked"), std::fs::Permissions::from_mode(0o000))
3938                .await?;
3939            let mut settings = settings_with_delete(delete_on());
3940            settings.dry_run = dry_run.then_some(DryRunMode::Brief);
3941            let result = if use_link {
3942                crate::link::link(
3943                    &PROGRESS,
3944                    &root,
3945                    &src,
3946                    &dst,
3947                    &None,
3948                    &crate::link::Settings {
3949                        copy_settings: settings.clone(),
3950                        update_compare: Default::default(),
3951                        update_exclusive: false,
3952                        filter: None,
3953                        dry_run: settings.dry_run,
3954                        preserve: *NO_PRESERVE_SETTINGS,
3955                    },
3956                    false,
3957                )
3958                .await
3959                .map(|summary| (summary.copy_summary, summary.hard_links_created))
3960                .map_err(|error| {
3961                    (
3962                        error.source,
3963                        error.summary.copy_summary,
3964                        error.summary.hard_links_created,
3965                    )
3966                })
3967            } else {
3968                copy(
3969                    &PROGRESS,
3970                    &src,
3971                    &dst,
3972                    &settings,
3973                    &NO_PRESERVE_SETTINGS,
3974                    false,
3975                )
3976                .await
3977                .map(|summary| (summary, 0))
3978                .map_err(|error| (error.source, error.summary, 0))
3979            };
3980            tokio::fs::set_permissions(dst.join("blocked"), std::fs::Permissions::from_mode(0o700))
3981                .await?;
3982            let (error, summary, links) = result.expect_err("an unreadable destination must fail");
3983            assert_eq!(
3984                summary.files_copied + links,
3985                1,
3986                "only the accessible sibling may be reported"
3987            );
3988            assert_eq!(summary.directories_created, usize::from(dry_run));
3989            assert_eq!(
3990                summary.rm_summary.files_removed, 0,
3991                "a child error must prevent parent pruning"
3992            );
3993            assert_eq!(tokio::fs::read(dst.join("sentinel")).await?, b"KEEP");
3994            assert!(!dst.join("blocked/x").exists());
3995            assert!(!dst.join("blocked/y").exists());
3996            assert_eq!(dst.join("sibling").exists(), !dry_run);
3997            let message = format!("{error:#}");
3998            assert!(
3999                message.contains(&format!("{:?}", dst.join("blocked"))),
4000                "{message}"
4001            );
4002            assert!(
4003                !message.contains("blocked/x") && !message.contains("blocked/y"),
4004                "{message}"
4005            );
4006        }
4007        Ok(())
4008    }
4009
4010    #[tokio::test]
4011    async fn copy_preview_stops_at_unreadable_destination_before_children() -> anyhow::Result<()> {
4012        preview_stops_at_unreadable_destination_case(false).await
4013    }
4014
4015    #[tokio::test]
4016    async fn link_preview_stops_at_unreadable_destination_before_children() -> anyhow::Result<()> {
4017        preview_stops_at_unreadable_destination_case(true).await
4018    }
4019
4020    #[tokio::test]
4021    async fn delete_scan_open_failure_prevents_dry_run_descent() -> anyhow::Result<()> {
4022        let root = testutils::create_temp_dir().await?;
4023        let src = root.join("source");
4024        let sub = src.join("sub");
4025        let dst = root.join("destination");
4026        tokio::fs::create_dir_all(&sub).await?;
4027        tokio::fs::write(sub.join("a.txt"), b"excluded").await?;
4028        for fail_early in [false, true] {
4029            for through_parent in [false, true] {
4030                let mut settings = settings_with_delete(delete_on());
4031                settings.dry_run = Some(DryRunMode::Brief);
4032                settings.fail_early = fail_early;
4033                let mut filter = crate::filter::FilterSettings::new();
4034                filter.add_include("*.rs")?;
4035                settings.filter = Some(filter);
4036                // an invalid scan anchor fails with EINVAL regardless of process privileges
4037                let destination = DestinationContext::new(std::path::Path::new("/"));
4038                let visitor = Arc::new(CopyVisitor {
4039                    prog_track: &PROGRESS,
4040                    dst_root: dst.clone(),
4041                    destination,
4042                    settings,
4043                    preserve: *NO_PRESERVE_SETTINGS,
4044                    dst_parent: None,
4045                    root_is_fresh: false,
4046                });
4047                let entry = if through_parent { &src } else { &sub };
4048                let relative = entry.strip_prefix(&src)?;
4049                let cx = EntryCx::root(
4050                    Arc::new(
4051                        Dir::open_root_dir(
4052                            entry.parent().unwrap(),
4053                            false,
4054                            congestion::Side::Source,
4055                        )
4056                        .await?,
4057                    ),
4058                    entry.file_name().unwrap().to_owned(),
4059                    entry.clone(),
4060                    &PROGRESS,
4061                )
4062                .with_relative_path(relative.to_owned());
4063                let context = visitor.root_dir_context();
4064                let error = process_entry(visitor, cx, context, None).await.unwrap_err();
4065                assert_eq!(error.summary.directories_created, 0);
4066                assert_eq!(error.summary.files_skipped, 0);
4067                let message = format!("{:#}", error.source);
4068                assert!(message.contains("for preview"), "{message}");
4069                assert!(
4070                    message.contains(&format!(
4071                        "{:?}",
4072                        if through_parent {
4073                            dst.clone()
4074                        } else {
4075                            dst.join("sub")
4076                        }
4077                    )),
4078                    "{message}"
4079                );
4080                assert!(error.source.chain().any(|cause| {
4081                    cause
4082                        .downcast_ref::<std::io::Error>()
4083                        .is_some_and(|error| error.raw_os_error() == Some(libc::EINVAL))
4084                }));
4085            }
4086        }
4087        Ok(())
4088    }
4089
4090    #[tokio::test]
4091    async fn delete_prunes_with_a_collected_empty_keep_set() -> anyhow::Result<()> {
4092        let root = testutils::create_temp_dir().await?;
4093        let src = root.join("source");
4094        let dst = root.join("destination");
4095        tokio::fs::create_dir(&src).await?;
4096        tokio::fs::create_dir(&dst).await?;
4097        tokio::fs::write(dst.join("stale"), b"stale").await?;
4098        let summary = copy(
4099            &PROGRESS,
4100            &src,
4101            &dst,
4102            &settings_with_delete(delete_on()),
4103            &NO_PRESERVE_SETTINGS,
4104            false,
4105        )
4106        .await?;
4107        assert_eq!(summary.rm_summary.files_removed, 1);
4108        assert!(
4109            tokio::fs::read_dir(&dst)
4110                .await?
4111                .next_entry()
4112                .await?
4113                .is_none()
4114        );
4115        Ok(())
4116    }
4117
4118    #[tokio::test]
4119    #[traced_test]
4120    async fn delete_skips_pruning_when_copy_has_errors() -> Result<(), anyhow::Error> {
4121        let tmp_dir = testutils::setup_test_dir().await?;
4122        let test_path = tmp_dir.as_path();
4123        let src = test_path.join("foo");
4124        let dst = test_path.join("bar");
4125        // baseline copy establishes the destination
4126        copy(
4127            &PROGRESS,
4128            &src,
4129            &dst,
4130            &settings_with_delete(None),
4131            &DO_PRESERVE_SETTINGS,
4132            false,
4133        )
4134        .await?;
4135        // an extraneous file that --delete would normally prune
4136        tokio::fs::write(dst.join("extraneous.txt"), b"junk").await?;
4137        // make a source sub-directory unreadable so traversal fails (fail_early is false).
4138        // a directory (not a file) is used because --overwrite with mtime-equal files skips
4139        // copying identical files; a directory's read_dir fails unconditionally when mode is 0o000.
4140        let unreadable = src.join("baz");
4141        let original = tokio::fs::metadata(&unreadable).await?.permissions();
4142        tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
4143
4144        let result = copy(
4145            &PROGRESS,
4146            &src,
4147            &dst,
4148            &settings_with_delete(delete_on()),
4149            &DO_PRESERVE_SETTINGS,
4150            false,
4151        )
4152        .await;
4153
4154        tokio::fs::set_permissions(&unreadable, original).await?;
4155
4156        assert!(
4157            result.is_err(),
4158            "copy of the unreadable directory should fail"
4159        );
4160        assert!(
4161            dst.join("extraneous.txt").exists(),
4162            "pruning must be skipped when the copy reported errors"
4163        );
4164        assert!(logs_contain(
4165            "because entry processing failed or did not provide complete exact names"
4166        ));
4167        Ok(())
4168    }
4169
4170    #[tokio::test]
4171    #[traced_test]
4172    async fn check_basic_copy() -> Result<(), anyhow::Error> {
4173        let tmp_dir = testutils::setup_test_dir().await?;
4174        let test_path = tmp_dir.as_path();
4175        let summary = copy(
4176            &PROGRESS,
4177            &test_path.join("foo"),
4178            &test_path.join("bar"),
4179            &Settings {
4180                reflink: Default::default(),
4181                local_copy_handoff: Default::default(),
4182                dereference: false,
4183                fail_early: false,
4184                overwrite: false,
4185                overwrite_compare: filecmp::MetadataCmpSettings {
4186                    size: true,
4187                    mtime: true,
4188                    ..Default::default()
4189                },
4190                overwrite_filter: None,
4191                ignore_existing: false,
4192                chunk_size: 0,
4193                skip_specials: false,
4194                remote_copy_buffer_size: 0,
4195                filter: None,
4196                dry_run: None,
4197                delete: None,
4198            },
4199            &NO_PRESERVE_SETTINGS,
4200            false,
4201        )
4202        .await?;
4203        assert_eq!(summary.files_copied, 5);
4204        assert_eq!(summary.symlinks_created, 2);
4205        assert_eq!(summary.directories_created, 3);
4206        testutils::check_dirs_identical(
4207            &test_path.join("foo"),
4208            &test_path.join("bar"),
4209            testutils::FileEqualityCheck::Basic,
4210        )
4211        .await?;
4212        Ok(())
4213    }
4214
4215    #[tokio::test]
4216    #[traced_test]
4217    async fn no_read_permission() -> Result<(), anyhow::Error> {
4218        let tmp_dir = testutils::setup_test_dir().await?;
4219        let test_path = tmp_dir.as_path();
4220        let filepaths = vec![
4221            test_path.join("foo").join("0.txt"),
4222            test_path.join("foo").join("baz"),
4223        ];
4224        for fpath in &filepaths {
4225            // change file permissions to not readable
4226            tokio::fs::set_permissions(&fpath, std::fs::Permissions::from_mode(0o000)).await?;
4227        }
4228        match copy(
4229            &PROGRESS,
4230            &test_path.join("foo"),
4231            &test_path.join("bar"),
4232            &Settings {
4233                reflink: Default::default(),
4234                local_copy_handoff: Default::default(),
4235                dereference: false,
4236                fail_early: false,
4237                overwrite: false,
4238                overwrite_compare: filecmp::MetadataCmpSettings {
4239                    size: true,
4240                    mtime: true,
4241                    ..Default::default()
4242                },
4243                overwrite_filter: None,
4244                ignore_existing: false,
4245                chunk_size: 0,
4246                skip_specials: false,
4247                remote_copy_buffer_size: 0,
4248                filter: None,
4249                dry_run: None,
4250                delete: None,
4251            },
4252            &NO_PRESERVE_SETTINGS,
4253            false,
4254        )
4255        .await
4256        {
4257            Ok(_) => panic!("Expected the copy to error!"),
4258            Err(error) => {
4259                tracing::info!("{:#}", &error);
4260                // foo
4261                // |- 0.txt  // <- no read permission
4262                // |- bar
4263                //    |- 1.txt
4264                //    |- 2.txt
4265                //    |- 3.txt
4266                // |- baz   // <- no read permission
4267                //    |- 4.txt
4268                //    |- 5.txt -> ../bar/2.txt
4269                //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
4270                assert_eq!(error.summary.files_copied, 3);
4271                assert_eq!(error.summary.symlinks_created, 0);
4272                assert_eq!(error.summary.directories_created, 2);
4273            }
4274        }
4275        // make source directory same as what we expect destination to be
4276        for fpath in &filepaths {
4277            tokio::fs::set_permissions(&fpath, std::fs::Permissions::from_mode(0o700)).await?;
4278            if tokio::fs::symlink_metadata(fpath).await?.is_file() {
4279                tokio::fs::remove_file(fpath).await?;
4280            } else {
4281                tokio::fs::remove_dir_all(fpath).await?;
4282            }
4283        }
4284        testutils::check_dirs_identical(
4285            &test_path.join("foo"),
4286            &test_path.join("bar"),
4287            testutils::FileEqualityCheck::Basic,
4288        )
4289        .await?;
4290        Ok(())
4291    }
4292
4293    #[cfg_attr(
4294        rcp_nix_sandbox,
4295        ignore = "Nix sandbox cannot set special permission bits"
4296    )]
4297    #[tokio::test]
4298    #[traced_test]
4299    async fn check_default_mode() -> Result<(), anyhow::Error> {
4300        let tmp_dir = testutils::setup_test_dir().await?;
4301        // set file to executable
4302        tokio::fs::set_permissions(
4303            tmp_dir.join("foo").join("0.txt"),
4304            std::fs::Permissions::from_mode(0o700),
4305        )
4306        .await?;
4307        // set file executable AND also set sticky bit, setuid and setgid
4308        let exec_sticky_file = tmp_dir.join("foo").join("bar").join("1.txt");
4309        tokio::fs::set_permissions(&exec_sticky_file, std::fs::Permissions::from_mode(0o3770))
4310            .await?;
4311        let test_path = tmp_dir.as_path();
4312        let summary = copy(
4313            &PROGRESS,
4314            &test_path.join("foo"),
4315            &test_path.join("bar"),
4316            &Settings {
4317                reflink: Default::default(),
4318                local_copy_handoff: Default::default(),
4319                dereference: false,
4320                fail_early: false,
4321                overwrite: false,
4322                overwrite_compare: filecmp::MetadataCmpSettings {
4323                    size: true,
4324                    mtime: true,
4325                    ..Default::default()
4326                },
4327                overwrite_filter: None,
4328                ignore_existing: false,
4329                chunk_size: 0,
4330                skip_specials: false,
4331                remote_copy_buffer_size: 0,
4332                filter: None,
4333                dry_run: None,
4334                delete: None,
4335            },
4336            &NO_PRESERVE_SETTINGS,
4337            false,
4338        )
4339        .await?;
4340        assert_eq!(summary.files_copied, 5);
4341        assert_eq!(summary.symlinks_created, 2);
4342        assert_eq!(summary.directories_created, 3);
4343        // clear the setuid, setgid and sticky bit for comparison
4344        tokio::fs::set_permissions(
4345            &exec_sticky_file,
4346            std::fs::Permissions::from_mode(
4347                std::fs::symlink_metadata(&exec_sticky_file)?
4348                    .permissions()
4349                    .mode()
4350                    & 0o0777,
4351            ),
4352        )
4353        .await?;
4354        testutils::check_dirs_identical(
4355            &test_path.join("foo"),
4356            &test_path.join("bar"),
4357            testutils::FileEqualityCheck::Basic,
4358        )
4359        .await?;
4360        Ok(())
4361    }
4362
4363    #[tokio::test]
4364    #[traced_test]
4365    async fn no_write_permission() -> Result<(), anyhow::Error> {
4366        let tmp_dir = testutils::setup_test_dir().await?;
4367        let test_path = tmp_dir.as_path();
4368        // directory - readable and non-executable
4369        let non_exec_dir = test_path.join("foo").join("bogey");
4370        tokio::fs::create_dir(&non_exec_dir).await?;
4371        tokio::fs::set_permissions(&non_exec_dir, std::fs::Permissions::from_mode(0o400)).await?;
4372        // directory - readable and executable
4373        tokio::fs::set_permissions(
4374            &test_path.join("foo").join("baz"),
4375            std::fs::Permissions::from_mode(0o500),
4376        )
4377        .await?;
4378        // file
4379        tokio::fs::set_permissions(
4380            &test_path.join("foo").join("baz").join("4.txt"),
4381            std::fs::Permissions::from_mode(0o440),
4382        )
4383        .await?;
4384        let summary = copy(
4385            &PROGRESS,
4386            &test_path.join("foo"),
4387            &test_path.join("bar"),
4388            &Settings {
4389                reflink: Default::default(),
4390                local_copy_handoff: Default::default(),
4391                dereference: false,
4392                fail_early: false,
4393                overwrite: false,
4394                overwrite_compare: filecmp::MetadataCmpSettings {
4395                    size: true,
4396                    mtime: true,
4397                    ..Default::default()
4398                },
4399                overwrite_filter: None,
4400                ignore_existing: false,
4401                chunk_size: 0,
4402                skip_specials: false,
4403                remote_copy_buffer_size: 0,
4404                filter: None,
4405                dry_run: None,
4406                delete: None,
4407            },
4408            &NO_PRESERVE_SETTINGS,
4409            false,
4410        )
4411        .await?;
4412        assert_eq!(summary.files_copied, 5);
4413        assert_eq!(summary.symlinks_created, 2);
4414        assert_eq!(summary.directories_created, 4);
4415        testutils::check_dirs_identical(
4416            &test_path.join("foo"),
4417            &test_path.join("bar"),
4418            testutils::FileEqualityCheck::Basic,
4419        )
4420        .await?;
4421        Ok(())
4422    }
4423
4424    #[tokio::test]
4425    #[traced_test]
4426    async fn dereference() -> Result<(), anyhow::Error> {
4427        let tmp_dir = testutils::setup_test_dir().await?;
4428        let test_path = tmp_dir.as_path();
4429        // make files pointed to by symlinks have different permissions than the symlink itself
4430        let src1 = &test_path.join("foo").join("bar").join("2.txt");
4431        let src2 = &test_path.join("foo").join("bar").join("3.txt");
4432        let test_mode = 0o440;
4433        for f in [src1, src2] {
4434            tokio::fs::set_permissions(f, std::fs::Permissions::from_mode(test_mode)).await?;
4435        }
4436        let summary = copy(
4437            &PROGRESS,
4438            &test_path.join("foo"),
4439            &test_path.join("bar"),
4440            &Settings {
4441                reflink: Default::default(),
4442                local_copy_handoff: Default::default(),
4443                dereference: true, // <- important!
4444                fail_early: false,
4445                overwrite: false,
4446                overwrite_compare: filecmp::MetadataCmpSettings {
4447                    size: true,
4448                    mtime: true,
4449                    ..Default::default()
4450                },
4451                overwrite_filter: None,
4452                ignore_existing: false,
4453                chunk_size: 0,
4454                skip_specials: false,
4455                remote_copy_buffer_size: 0,
4456                filter: None,
4457                dry_run: None,
4458                delete: None,
4459            },
4460            &NO_PRESERVE_SETTINGS,
4461            false,
4462        )
4463        .await?;
4464        assert_eq!(summary.files_copied, 7);
4465        assert_eq!(summary.symlinks_created, 0);
4466        assert_eq!(summary.directories_created, 3);
4467        // ...
4468        // |- baz
4469        //    |- 4.txt
4470        //    |- 5.txt -> ../bar/2.txt
4471        //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
4472        let dst1 = &test_path.join("bar").join("baz").join("5.txt");
4473        let dst2 = &test_path.join("bar").join("baz").join("6.txt");
4474        for f in [dst1, dst2] {
4475            let metadata = tokio::fs::symlink_metadata(f)
4476                .await
4477                .with_context(|| format!("failed reading metadata from {:?}", &f))?;
4478            assert!(metadata.is_file());
4479            // check that the permissions are the same as the source file modulo no sticky bit, setuid and setgid
4480            assert_eq!(metadata.permissions().mode() & 0o777, test_mode);
4481        }
4482        Ok(())
4483    }
4484
4485    async fn cp_compare(
4486        cp_args: &[&str],
4487        rcp_settings: &Settings,
4488        preserve: bool,
4489    ) -> Result<(), anyhow::Error> {
4490        let tmp_dir = testutils::setup_test_dir().await?;
4491        let test_path = tmp_dir.as_path();
4492        // run a cp command to copy the files
4493        let cp_output = tokio::process::Command::new("cp")
4494            .args(cp_args)
4495            .arg(test_path.join("foo"))
4496            .arg(test_path.join("bar"))
4497            .output()
4498            .await?;
4499        assert!(cp_output.status.success());
4500        // now run rcp
4501        let summary = copy(
4502            &PROGRESS,
4503            &test_path.join("foo"),
4504            &test_path.join("baz"),
4505            rcp_settings,
4506            if preserve {
4507                &DO_PRESERVE_SETTINGS
4508            } else {
4509                &NO_PRESERVE_SETTINGS
4510            },
4511            false,
4512        )
4513        .await?;
4514        if rcp_settings.dereference {
4515            assert_eq!(summary.files_copied, 7);
4516            assert_eq!(summary.symlinks_created, 0);
4517        } else {
4518            assert_eq!(summary.files_copied, 5);
4519            assert_eq!(summary.symlinks_created, 2);
4520        }
4521        assert_eq!(summary.directories_created, 3);
4522        testutils::check_dirs_identical(
4523            &test_path.join("bar"),
4524            &test_path.join("baz"),
4525            if preserve {
4526                testutils::FileEqualityCheck::Timestamp
4527            } else {
4528                testutils::FileEqualityCheck::Basic
4529            },
4530        )
4531        .await?;
4532        Ok(())
4533    }
4534
4535    #[tokio::test]
4536    #[traced_test]
4537    async fn test_cp_compat() -> Result<(), anyhow::Error> {
4538        cp_compare(
4539            &["-r"],
4540            &Settings {
4541                reflink: Default::default(),
4542                local_copy_handoff: Default::default(),
4543                dereference: false,
4544                fail_early: false,
4545                overwrite: false,
4546                overwrite_compare: filecmp::MetadataCmpSettings {
4547                    size: true,
4548                    mtime: true,
4549                    ..Default::default()
4550                },
4551                overwrite_filter: None,
4552                ignore_existing: false,
4553                chunk_size: 0,
4554                skip_specials: false,
4555                remote_copy_buffer_size: 0,
4556                filter: None,
4557                dry_run: None,
4558                delete: None,
4559            },
4560            false,
4561        )
4562        .await?;
4563        Ok(())
4564    }
4565
4566    #[tokio::test]
4567    #[traced_test]
4568    async fn test_cp_compat_preserve() -> Result<(), anyhow::Error> {
4569        cp_compare(
4570            &["-r", "-p"],
4571            &Settings {
4572                reflink: Default::default(),
4573                local_copy_handoff: Default::default(),
4574                dereference: false,
4575                fail_early: false,
4576                overwrite: false,
4577                overwrite_compare: filecmp::MetadataCmpSettings {
4578                    size: true,
4579                    mtime: true,
4580                    ..Default::default()
4581                },
4582                overwrite_filter: None,
4583                ignore_existing: false,
4584                chunk_size: 0,
4585                skip_specials: false,
4586                remote_copy_buffer_size: 0,
4587                filter: None,
4588                dry_run: None,
4589                delete: None,
4590            },
4591            true,
4592        )
4593        .await?;
4594        Ok(())
4595    }
4596
4597    #[tokio::test]
4598    #[traced_test]
4599    async fn test_cp_compat_dereference() -> Result<(), anyhow::Error> {
4600        cp_compare(
4601            &["-r", "-L"],
4602            &Settings {
4603                reflink: Default::default(),
4604                local_copy_handoff: Default::default(),
4605                dereference: true,
4606                fail_early: false,
4607                overwrite: false,
4608                overwrite_compare: filecmp::MetadataCmpSettings {
4609                    size: true,
4610                    mtime: true,
4611                    ..Default::default()
4612                },
4613                overwrite_filter: None,
4614                ignore_existing: false,
4615                chunk_size: 0,
4616                skip_specials: false,
4617                remote_copy_buffer_size: 0,
4618                filter: None,
4619                dry_run: None,
4620                delete: None,
4621            },
4622            false,
4623        )
4624        .await?;
4625        Ok(())
4626    }
4627
4628    #[tokio::test]
4629    #[traced_test]
4630    async fn test_cp_compat_preserve_and_dereference() -> Result<(), anyhow::Error> {
4631        cp_compare(
4632            &["-r", "-p", "-L"],
4633            &Settings {
4634                reflink: Default::default(),
4635                local_copy_handoff: Default::default(),
4636                dereference: true,
4637                fail_early: false,
4638                overwrite: false,
4639                overwrite_compare: filecmp::MetadataCmpSettings {
4640                    size: true,
4641                    mtime: true,
4642                    ..Default::default()
4643                },
4644                overwrite_filter: None,
4645                ignore_existing: false,
4646                chunk_size: 0,
4647                skip_specials: false,
4648                remote_copy_buffer_size: 0,
4649                filter: None,
4650                dry_run: None,
4651                delete: None,
4652            },
4653            true,
4654        )
4655        .await?;
4656        Ok(())
4657    }
4658
4659    async fn setup_test_dir_and_copy() -> Result<std::path::PathBuf, anyhow::Error> {
4660        let tmp_dir = testutils::setup_test_dir().await?;
4661        let test_path = tmp_dir.as_path();
4662        let summary = copy(
4663            &PROGRESS,
4664            &test_path.join("foo"),
4665            &test_path.join("bar"),
4666            &Settings {
4667                reflink: Default::default(),
4668                local_copy_handoff: Default::default(),
4669                dereference: false,
4670                fail_early: false,
4671                overwrite: false,
4672                overwrite_compare: filecmp::MetadataCmpSettings {
4673                    size: true,
4674                    mtime: true,
4675                    ..Default::default()
4676                },
4677                overwrite_filter: None,
4678                ignore_existing: false,
4679                chunk_size: 0,
4680                skip_specials: false,
4681                remote_copy_buffer_size: 0,
4682                filter: None,
4683                dry_run: None,
4684                delete: None,
4685            },
4686            &DO_PRESERVE_SETTINGS,
4687            false,
4688        )
4689        .await?;
4690        assert_eq!(summary.files_copied, 5);
4691        assert_eq!(summary.symlinks_created, 2);
4692        assert_eq!(summary.directories_created, 3);
4693        Ok(tmp_dir)
4694    }
4695
4696    #[tokio::test]
4697    #[traced_test]
4698    async fn test_cp_overwrite_basic() -> Result<(), anyhow::Error> {
4699        let tmp_dir = setup_test_dir_and_copy().await?;
4700        let output_path = &tmp_dir.join("bar");
4701        {
4702            // bar
4703            // |- 0.txt
4704            // |- bar  <---------------------------------------- REMOVE
4705            //    |- 1.txt  <----------------------------------- REMOVE
4706            //    |- 2.txt  <----------------------------------- REMOVE
4707            //    |- 3.txt  <----------------------------------- REMOVE
4708            // |- baz
4709            //    |- 4.txt
4710            //    |- 5.txt -> ../bar/2.txt <-------------------- REMOVE
4711            //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
4712            let summary = rm::rm(
4713                &PROGRESS,
4714                &output_path.join("bar"),
4715                &RmSettings {
4716                    fail_early: false,
4717                    filter: None,
4718                    dry_run: None,
4719                    time_filter: None,
4720                },
4721            )
4722            .await?
4723                + rm::rm(
4724                    &PROGRESS,
4725                    &output_path.join("baz").join("5.txt"),
4726                    &RmSettings {
4727                        fail_early: false,
4728                        filter: None,
4729                        dry_run: None,
4730                        time_filter: None,
4731                    },
4732                )
4733                .await?;
4734            assert_eq!(summary.files_removed, 3);
4735            assert_eq!(summary.symlinks_removed, 1);
4736            assert_eq!(summary.directories_removed, 1);
4737        }
4738        let summary = copy(
4739            &PROGRESS,
4740            &tmp_dir.join("foo"),
4741            output_path,
4742            &Settings {
4743                reflink: Default::default(),
4744                local_copy_handoff: Default::default(),
4745                dereference: false,
4746                fail_early: false,
4747                overwrite: true, // <- important!
4748                overwrite_compare: filecmp::MetadataCmpSettings {
4749                    size: true,
4750                    mtime: true,
4751                    ..Default::default()
4752                },
4753                overwrite_filter: None,
4754                ignore_existing: false,
4755                chunk_size: 0,
4756                skip_specials: false,
4757                remote_copy_buffer_size: 0,
4758                filter: None,
4759                dry_run: None,
4760                delete: None,
4761            },
4762            &DO_PRESERVE_SETTINGS,
4763            false,
4764        )
4765        .await?;
4766        assert_eq!(summary.files_copied, 3);
4767        assert_eq!(summary.symlinks_created, 1);
4768        assert_eq!(summary.directories_created, 1);
4769        testutils::check_dirs_identical(
4770            &tmp_dir.join("foo"),
4771            output_path,
4772            testutils::FileEqualityCheck::Timestamp,
4773        )
4774        .await?;
4775        Ok(())
4776    }
4777
4778    #[tokio::test]
4779    #[traced_test]
4780    async fn test_cp_overwrite_dir_file() -> Result<(), anyhow::Error> {
4781        let tmp_dir = setup_test_dir_and_copy().await?;
4782        let output_path = &tmp_dir.join("bar");
4783        {
4784            // bar
4785            // |- 0.txt
4786            // |- bar
4787            //    |- 1.txt  <------------------------------------- REMOVE
4788            //    |- 2.txt
4789            //    |- 3.txt
4790            // |- baz  <------------------------------------------ REMOVE
4791            //    |- 4.txt  <------------------------------------- REMOVE
4792            //    |- 5.txt -> ../bar/2.txt <---------------------- REMOVE
4793            //    |- 6.txt -> (absolute path) .../foo/bar/3.txt <- REMOVE
4794            let summary = rm::rm(
4795                &PROGRESS,
4796                &output_path.join("bar").join("1.txt"),
4797                &RmSettings {
4798                    fail_early: false,
4799                    filter: None,
4800                    dry_run: None,
4801                    time_filter: None,
4802                },
4803            )
4804            .await?
4805                + rm::rm(
4806                    &PROGRESS,
4807                    &output_path.join("baz"),
4808                    &RmSettings {
4809                        fail_early: false,
4810                        filter: None,
4811                        dry_run: None,
4812                        time_filter: None,
4813                    },
4814                )
4815                .await?;
4816            assert_eq!(summary.files_removed, 2);
4817            assert_eq!(summary.symlinks_removed, 2);
4818            assert_eq!(summary.directories_removed, 1);
4819        }
4820        {
4821            // replace bar/1.txt file with a directory
4822            tokio::fs::create_dir(&output_path.join("bar").join("1.txt")).await?;
4823            // replace baz directory with a file
4824            tokio::fs::write(&output_path.join("baz"), "baz").await?;
4825        }
4826        let summary = copy(
4827            &PROGRESS,
4828            &tmp_dir.join("foo"),
4829            output_path,
4830            &Settings {
4831                reflink: Default::default(),
4832                local_copy_handoff: Default::default(),
4833                dereference: false,
4834                fail_early: false,
4835                overwrite: true, // <- important!
4836                overwrite_compare: filecmp::MetadataCmpSettings {
4837                    size: true,
4838                    mtime: true,
4839                    ..Default::default()
4840                },
4841                overwrite_filter: None,
4842                ignore_existing: false,
4843                chunk_size: 0,
4844                skip_specials: false,
4845                remote_copy_buffer_size: 0,
4846                filter: None,
4847                dry_run: None,
4848                delete: None,
4849            },
4850            &DO_PRESERVE_SETTINGS,
4851            false,
4852        )
4853        .await?;
4854        assert_eq!(summary.rm_summary.files_removed, 1);
4855        assert_eq!(summary.rm_summary.symlinks_removed, 0);
4856        assert_eq!(summary.rm_summary.directories_removed, 1);
4857        assert_eq!(summary.files_copied, 2);
4858        assert_eq!(summary.symlinks_created, 2);
4859        assert_eq!(summary.directories_created, 1);
4860        testutils::check_dirs_identical(
4861            &tmp_dir.join("foo"),
4862            output_path,
4863            testutils::FileEqualityCheck::Timestamp,
4864        )
4865        .await?;
4866        Ok(())
4867    }
4868
4869    #[tokio::test]
4870    #[traced_test]
4871    async fn test_cp_overwrite_symlink_file() -> Result<(), anyhow::Error> {
4872        let tmp_dir = setup_test_dir_and_copy().await?;
4873        let output_path = &tmp_dir.join("bar");
4874        {
4875            // bar
4876            // |- 0.txt
4877            // |- baz
4878            //    |- 4.txt  <------------------------------------- REMOVE
4879            //    |- 5.txt -> ../bar/2.txt <---------------------- REMOVE
4880            // ...
4881            let summary = rm::rm(
4882                &PROGRESS,
4883                &output_path.join("baz").join("4.txt"),
4884                &RmSettings {
4885                    fail_early: false,
4886                    filter: None,
4887                    dry_run: None,
4888                    time_filter: None,
4889                },
4890            )
4891            .await?
4892                + rm::rm(
4893                    &PROGRESS,
4894                    &output_path.join("baz").join("5.txt"),
4895                    &RmSettings {
4896                        fail_early: false,
4897                        filter: None,
4898                        dry_run: None,
4899                        time_filter: None,
4900                    },
4901                )
4902                .await?;
4903            assert_eq!(summary.files_removed, 1);
4904            assert_eq!(summary.symlinks_removed, 1);
4905            assert_eq!(summary.directories_removed, 0);
4906        }
4907        {
4908            // replace baz/4.txt file with a symlink
4909            tokio::fs::symlink("../0.txt", &output_path.join("baz").join("4.txt")).await?;
4910            // replace baz/5.txt symlink with a file
4911            tokio::fs::write(&output_path.join("baz").join("5.txt"), "baz").await?;
4912        }
4913        let summary = copy(
4914            &PROGRESS,
4915            &tmp_dir.join("foo"),
4916            output_path,
4917            &Settings {
4918                reflink: Default::default(),
4919                local_copy_handoff: Default::default(),
4920                dereference: false,
4921                fail_early: false,
4922                overwrite: true, // <- important!
4923                overwrite_compare: filecmp::MetadataCmpSettings {
4924                    size: true,
4925                    mtime: true,
4926                    ..Default::default()
4927                },
4928                overwrite_filter: None,
4929                ignore_existing: false,
4930                chunk_size: 0,
4931                skip_specials: false,
4932                remote_copy_buffer_size: 0,
4933                filter: None,
4934                dry_run: None,
4935                delete: None,
4936            },
4937            &DO_PRESERVE_SETTINGS,
4938            false,
4939        )
4940        .await?;
4941        assert_eq!(summary.rm_summary.files_removed, 1);
4942        assert_eq!(summary.rm_summary.symlinks_removed, 1);
4943        assert_eq!(summary.rm_summary.directories_removed, 0);
4944        assert_eq!(summary.files_copied, 1);
4945        assert_eq!(summary.symlinks_created, 1);
4946        assert_eq!(summary.directories_created, 0);
4947        testutils::check_dirs_identical(
4948            &tmp_dir.join("foo"),
4949            output_path,
4950            testutils::FileEqualityCheck::Timestamp,
4951        )
4952        .await?;
4953        Ok(())
4954    }
4955
4956    #[tokio::test]
4957    #[traced_test]
4958    async fn test_cp_overwrite_symlink_dir() -> Result<(), anyhow::Error> {
4959        let tmp_dir = setup_test_dir_and_copy().await?;
4960        let output_path = &tmp_dir.join("bar");
4961        {
4962            // bar
4963            // |- 0.txt
4964            // |- bar  <------------------------------------------ REMOVE
4965            //    |- 1.txt  <------------------------------------- REMOVE
4966            //    |- 2.txt  <------------------------------------- REMOVE
4967            //    |- 3.txt  <------------------------------------- REMOVE
4968            // |- baz
4969            //    |- 5.txt -> ../bar/2.txt <---------------------- REMOVE
4970            // ...
4971            let summary = rm::rm(
4972                &PROGRESS,
4973                &output_path.join("bar"),
4974                &RmSettings {
4975                    fail_early: false,
4976                    filter: None,
4977                    dry_run: None,
4978                    time_filter: None,
4979                },
4980            )
4981            .await?
4982                + rm::rm(
4983                    &PROGRESS,
4984                    &output_path.join("baz").join("5.txt"),
4985                    &RmSettings {
4986                        fail_early: false,
4987                        filter: None,
4988                        dry_run: None,
4989                        time_filter: None,
4990                    },
4991                )
4992                .await?;
4993            assert_eq!(summary.files_removed, 3);
4994            assert_eq!(summary.symlinks_removed, 1);
4995            assert_eq!(summary.directories_removed, 1);
4996        }
4997        {
4998            // replace bar directory with a symlink
4999            tokio::fs::symlink("0.txt", &output_path.join("bar")).await?;
5000            // replace baz/5.txt symlink with a directory
5001            tokio::fs::create_dir(&output_path.join("baz").join("5.txt")).await?;
5002        }
5003        let summary = copy(
5004            &PROGRESS,
5005            &tmp_dir.join("foo"),
5006            output_path,
5007            &Settings {
5008                reflink: Default::default(),
5009                local_copy_handoff: Default::default(),
5010                dereference: false,
5011                fail_early: false,
5012                overwrite: true, // <- important!
5013                overwrite_compare: filecmp::MetadataCmpSettings {
5014                    size: true,
5015                    mtime: true,
5016                    ..Default::default()
5017                },
5018                overwrite_filter: None,
5019                ignore_existing: false,
5020                chunk_size: 0,
5021                skip_specials: false,
5022                remote_copy_buffer_size: 0,
5023                filter: None,
5024                dry_run: None,
5025                delete: None,
5026            },
5027            &DO_PRESERVE_SETTINGS,
5028            false,
5029        )
5030        .await?;
5031        assert_eq!(summary.rm_summary.files_removed, 0);
5032        assert_eq!(summary.rm_summary.symlinks_removed, 1);
5033        assert_eq!(summary.rm_summary.directories_removed, 1);
5034        assert_eq!(summary.files_copied, 3);
5035        assert_eq!(summary.symlinks_created, 1);
5036        assert_eq!(summary.directories_created, 1);
5037        assert_eq!(summary.files_unchanged, 2);
5038        assert_eq!(summary.symlinks_unchanged, 1);
5039        assert_eq!(summary.directories_unchanged, 2);
5040        testutils::check_dirs_identical(
5041            &tmp_dir.join("foo"),
5042            output_path,
5043            testutils::FileEqualityCheck::Timestamp,
5044        )
5045        .await?;
5046        Ok(())
5047    }
5048
5049    #[tokio::test]
5050    #[traced_test]
5051    async fn test_cp_overwrite_error() -> Result<(), anyhow::Error> {
5052        let tmp_dir = testutils::setup_test_dir().await?;
5053        let test_path = tmp_dir.as_path();
5054        let summary = copy(
5055            &PROGRESS,
5056            &test_path.join("foo"),
5057            &test_path.join("bar"),
5058            &Settings {
5059                reflink: Default::default(),
5060                local_copy_handoff: Default::default(),
5061                dereference: false,
5062                fail_early: false,
5063                overwrite: false,
5064                overwrite_compare: filecmp::MetadataCmpSettings {
5065                    size: true,
5066                    mtime: true,
5067                    ..Default::default()
5068                },
5069                overwrite_filter: None,
5070                ignore_existing: false,
5071                chunk_size: 0,
5072                skip_specials: false,
5073                remote_copy_buffer_size: 0,
5074                filter: None,
5075                dry_run: None,
5076                delete: None,
5077            },
5078            &NO_PRESERVE_SETTINGS, // we want timestamps to differ!
5079            false,
5080        )
5081        .await?;
5082        assert_eq!(summary.files_copied, 5);
5083        assert_eq!(summary.symlinks_created, 2);
5084        assert_eq!(summary.directories_created, 3);
5085        let source_path = &test_path.join("foo");
5086        let output_path = &tmp_dir.join("bar");
5087        // unreadable
5088        tokio::fs::set_permissions(
5089            &source_path.join("bar"),
5090            std::fs::Permissions::from_mode(0o000),
5091        )
5092        .await?;
5093        tokio::fs::set_permissions(
5094            &source_path.join("baz").join("4.txt"),
5095            std::fs::Permissions::from_mode(0o000),
5096        )
5097        .await?;
5098        // bar
5099        // |- 0.txt
5100        // |- bar  <---------------------------------------- NON READABLE
5101        // |- baz
5102        //    |- 4.txt  <----------------------------------- NON READABLE
5103        //    |- 5.txt -> ../bar/2.txt
5104        //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
5105        match copy(
5106            &PROGRESS,
5107            &tmp_dir.join("foo"),
5108            output_path,
5109            &Settings {
5110                reflink: Default::default(),
5111                local_copy_handoff: Default::default(),
5112                dereference: false,
5113                fail_early: false,
5114                overwrite: true, // <- important!
5115                overwrite_compare: filecmp::MetadataCmpSettings {
5116                    size: true,
5117                    mtime: true,
5118                    ..Default::default()
5119                },
5120                overwrite_filter: None,
5121                ignore_existing: false,
5122                chunk_size: 0,
5123                skip_specials: false,
5124                remote_copy_buffer_size: 0,
5125                filter: None,
5126                dry_run: None,
5127                delete: None,
5128            },
5129            &DO_PRESERVE_SETTINGS,
5130            false,
5131        )
5132        .await
5133        {
5134            Ok(_) => panic!("Expected the copy to error!"),
5135            Err(error) => {
5136                tracing::info!("{:#}", &error);
5137                assert_eq!(error.summary.files_copied, 1);
5138                assert_eq!(error.summary.symlinks_created, 2);
5139                assert_eq!(error.summary.directories_created, 0);
5140                // one removal, not two: `foo/baz/4.txt` is unreadable, so its copy fails at the
5141                // source open before the destination is unlinked. `bar/baz/4.txt` survives a copy
5142                // that could never have replaced it, which is the failure-ordering invariant owned
5143                // by `plan_overwrite_candidate` and `execute_dst_plan`.
5144                assert_eq!(error.summary.rm_summary.files_removed, 1);
5145                assert!(
5146                    output_path.join("baz").join("4.txt").exists(),
5147                    "the destination of an unreadable source must not be removed"
5148                );
5149                assert_eq!(error.summary.rm_summary.symlinks_removed, 2);
5150                assert_eq!(error.summary.rm_summary.directories_removed, 0);
5151            }
5152        }
5153        Ok(())
5154    }
5155
5156    #[tokio::test]
5157    #[traced_test]
5158    async fn test_cp_dereference_symlink_chain() -> Result<(), anyhow::Error> {
5159        // Create a fresh temporary directory to avoid conflicts
5160        let tmp_dir = testutils::create_temp_dir().await?;
5161        let test_path = tmp_dir.as_path();
5162        // Create a chain of symlinks: foo -> bar -> baz (actual file)
5163        let baz_file = test_path.join("baz_file.txt");
5164        tokio::fs::write(&baz_file, "final content").await?;
5165        let bar_link = test_path.join("bar_link");
5166        let foo_link = test_path.join("foo_link");
5167        // Create chain: foo_link -> bar_link -> baz_file.txt
5168        tokio::fs::symlink(&baz_file, &bar_link).await?;
5169        tokio::fs::symlink(&bar_link, &foo_link).await?;
5170        // Create source directory with the symlink chain
5171        let src_dir = test_path.join("src_chain");
5172        tokio::fs::create_dir(&src_dir).await?;
5173        // Copy the chain into the source directory
5174        tokio::fs::symlink("../foo_link", &src_dir.join("foo")).await?;
5175        tokio::fs::symlink("../bar_link", &src_dir.join("bar")).await?;
5176        tokio::fs::symlink("../baz_file.txt", &src_dir.join("baz")).await?;
5177        // Test with dereference - should copy 3 files with same content
5178        let summary = copy(
5179            &PROGRESS,
5180            &src_dir,
5181            &test_path.join("dst_with_deref"),
5182            &Settings {
5183                reflink: Default::default(),
5184                local_copy_handoff: Default::default(),
5185                dereference: true, // <- important!
5186                fail_early: false,
5187                overwrite: false,
5188                overwrite_compare: filecmp::MetadataCmpSettings {
5189                    size: true,
5190                    mtime: true,
5191                    ..Default::default()
5192                },
5193                overwrite_filter: None,
5194                ignore_existing: false,
5195                chunk_size: 0,
5196                skip_specials: false,
5197                remote_copy_buffer_size: 0,
5198                filter: None,
5199                dry_run: None,
5200                delete: None,
5201            },
5202            &NO_PRESERVE_SETTINGS,
5203            false,
5204        )
5205        .await?;
5206        assert_eq!(summary.files_copied, 3); // foo, bar, baz all copied as files
5207        assert_eq!(summary.symlinks_created, 0); // dereference is set
5208        assert_eq!(summary.directories_created, 1);
5209        let dst_dir = test_path.join("dst_with_deref");
5210        // Verify all three are now regular files with the same content
5211        let foo_content = tokio::fs::read_to_string(dst_dir.join("foo")).await?;
5212        let bar_content = tokio::fs::read_to_string(dst_dir.join("bar")).await?;
5213        let baz_content = tokio::fs::read_to_string(dst_dir.join("baz")).await?;
5214        assert_eq!(foo_content, "final content");
5215        assert_eq!(bar_content, "final content");
5216        assert_eq!(baz_content, "final content");
5217        // Verify they are all regular files, not symlinks
5218        assert!(dst_dir.join("foo").is_file());
5219        assert!(dst_dir.join("bar").is_file());
5220        assert!(dst_dir.join("baz").is_file());
5221        assert!(!dst_dir.join("foo").is_symlink());
5222        assert!(!dst_dir.join("bar").is_symlink());
5223        assert!(!dst_dir.join("baz").is_symlink());
5224        Ok(())
5225    }
5226
5227    #[tokio::test]
5228    #[traced_test]
5229    async fn test_cp_dereference_symlink_to_directory() -> Result<(), anyhow::Error> {
5230        let tmp_dir = testutils::create_temp_dir().await?;
5231        let test_path = tmp_dir.as_path();
5232        // Create a directory with specific permissions and content
5233        let target_dir = test_path.join("target_dir");
5234        tokio::fs::create_dir(&target_dir).await?;
5235        tokio::fs::set_permissions(&target_dir, std::fs::Permissions::from_mode(0o755)).await?;
5236        // Add some files to the directory
5237        tokio::fs::write(target_dir.join("file1.txt"), "content1").await?;
5238        tokio::fs::write(target_dir.join("file2.txt"), "content2").await?;
5239        tokio::fs::set_permissions(
5240            &target_dir.join("file1.txt"),
5241            std::fs::Permissions::from_mode(0o644),
5242        )
5243        .await?;
5244        tokio::fs::set_permissions(
5245            &target_dir.join("file2.txt"),
5246            std::fs::Permissions::from_mode(0o600),
5247        )
5248        .await?;
5249        // Create a symlink pointing to the directory
5250        let dir_symlink = test_path.join("dir_symlink");
5251        tokio::fs::symlink(&target_dir, &dir_symlink).await?;
5252        // Test copying the symlink with dereference - should copy as a directory
5253        let summary = copy(
5254            &PROGRESS,
5255            &dir_symlink,
5256            &test_path.join("copied_dir"),
5257            &Settings {
5258                reflink: Default::default(),
5259                local_copy_handoff: Default::default(),
5260                dereference: true, // <- important!
5261                fail_early: false,
5262                overwrite: false,
5263                overwrite_compare: filecmp::MetadataCmpSettings {
5264                    size: true,
5265                    mtime: true,
5266                    ..Default::default()
5267                },
5268                overwrite_filter: None,
5269                ignore_existing: false,
5270                chunk_size: 0,
5271                skip_specials: false,
5272                remote_copy_buffer_size: 0,
5273                filter: None,
5274                dry_run: None,
5275                delete: None,
5276            },
5277            &DO_PRESERVE_SETTINGS,
5278            false,
5279        )
5280        .await?;
5281        assert_eq!(summary.files_copied, 2); // file1.txt, file2.txt
5282        assert_eq!(summary.symlinks_created, 0); // dereference is set
5283        assert_eq!(summary.directories_created, 1); // copied_dir
5284        let copied_dir = test_path.join("copied_dir");
5285        // Verify the directory and its contents were copied
5286        assert!(copied_dir.is_dir());
5287        assert!(!copied_dir.is_symlink()); // Should be a real directory, not a symlink
5288        // Verify files were copied with correct content
5289        let file1_content = tokio::fs::read_to_string(copied_dir.join("file1.txt")).await?;
5290        let file2_content = tokio::fs::read_to_string(copied_dir.join("file2.txt")).await?;
5291        assert_eq!(file1_content, "content1");
5292        assert_eq!(file2_content, "content2");
5293        // Verify permissions were preserved
5294        let copied_dir_metadata = tokio::fs::metadata(&copied_dir).await?;
5295        let file1_metadata = tokio::fs::metadata(copied_dir.join("file1.txt")).await?;
5296        let file2_metadata = tokio::fs::metadata(copied_dir.join("file2.txt")).await?;
5297        assert_eq!(copied_dir_metadata.permissions().mode() & 0o777, 0o755);
5298        assert_eq!(file1_metadata.permissions().mode() & 0o777, 0o644);
5299        assert_eq!(file2_metadata.permissions().mode() & 0o777, 0o600);
5300        Ok(())
5301    }
5302
5303    #[tokio::test]
5304    #[traced_test]
5305    async fn test_cp_dereference_permissions_preserved() -> Result<(), anyhow::Error> {
5306        let tmp_dir = testutils::create_temp_dir().await?;
5307        let test_path = tmp_dir.as_path();
5308        // Create files with specific permissions
5309        let file1 = test_path.join("file1.txt");
5310        let file2 = test_path.join("file2.txt");
5311        tokio::fs::write(&file1, "content1").await?;
5312        tokio::fs::write(&file2, "content2").await?;
5313        tokio::fs::set_permissions(&file1, std::fs::Permissions::from_mode(0o755)).await?;
5314        tokio::fs::set_permissions(&file2, std::fs::Permissions::from_mode(0o640)).await?;
5315        // Create symlinks pointing to these files
5316        let symlink1 = test_path.join("symlink1");
5317        let symlink2 = test_path.join("symlink2");
5318        tokio::fs::symlink(&file1, &symlink1).await?;
5319        tokio::fs::symlink(&file2, &symlink2).await?;
5320        // Test copying symlinks with dereference and preserve
5321        let summary1 = copy(
5322            &PROGRESS,
5323            &symlink1,
5324            &test_path.join("copied_file1.txt"),
5325            &Settings {
5326                reflink: Default::default(),
5327                local_copy_handoff: Default::default(),
5328                dereference: true, // <- important!
5329                fail_early: false,
5330                overwrite: false,
5331                overwrite_compare: filecmp::MetadataCmpSettings::default(),
5332                overwrite_filter: None,
5333                ignore_existing: false,
5334                chunk_size: 0,
5335                skip_specials: false,
5336                remote_copy_buffer_size: 0,
5337                filter: None,
5338                dry_run: None,
5339                delete: None,
5340            },
5341            &DO_PRESERVE_SETTINGS, // <- important!
5342            false,
5343        )
5344        .await?;
5345        let summary2 = copy(
5346            &PROGRESS,
5347            &symlink2,
5348            &test_path.join("copied_file2.txt"),
5349            &Settings {
5350                reflink: Default::default(),
5351                local_copy_handoff: Default::default(),
5352                dereference: true,
5353                fail_early: false,
5354                overwrite: false,
5355                overwrite_compare: filecmp::MetadataCmpSettings::default(),
5356                overwrite_filter: None,
5357                ignore_existing: false,
5358                chunk_size: 0,
5359                skip_specials: false,
5360                remote_copy_buffer_size: 0,
5361                filter: None,
5362                dry_run: None,
5363                delete: None,
5364            },
5365            &DO_PRESERVE_SETTINGS,
5366            false,
5367        )
5368        .await?;
5369        assert_eq!(summary1.files_copied, 1);
5370        assert_eq!(summary1.symlinks_created, 0);
5371        assert_eq!(summary2.files_copied, 1);
5372        assert_eq!(summary2.symlinks_created, 0);
5373        let copied1 = test_path.join("copied_file1.txt");
5374        let copied2 = test_path.join("copied_file2.txt");
5375        // Verify files are regular files, not symlinks
5376        assert!(copied1.is_file());
5377        assert!(!copied1.is_symlink());
5378        assert!(copied2.is_file());
5379        assert!(!copied2.is_symlink());
5380        // Verify content was copied correctly
5381        let content1 = tokio::fs::read_to_string(&copied1).await?;
5382        let content2 = tokio::fs::read_to_string(&copied2).await?;
5383        assert_eq!(content1, "content1");
5384        assert_eq!(content2, "content2");
5385        // Verify permissions from the target files were preserved (not symlink permissions)
5386        let copied1_metadata = tokio::fs::metadata(&copied1).await?;
5387        let copied2_metadata = tokio::fs::metadata(&copied2).await?;
5388        assert_eq!(copied1_metadata.permissions().mode() & 0o777, 0o755);
5389        assert_eq!(copied2_metadata.permissions().mode() & 0o777, 0o640);
5390        Ok(())
5391    }
5392
5393    #[tokio::test]
5394    #[traced_test]
5395    async fn test_cp_dereference_dir() -> Result<(), anyhow::Error> {
5396        let tmp_dir = testutils::setup_test_dir().await?;
5397        // symlink bar to bar-link
5398        tokio::fs::symlink("bar", &tmp_dir.join("foo").join("bar-link")).await?;
5399        // symlink bar-link to bar-link-link
5400        tokio::fs::symlink("bar-link", &tmp_dir.join("foo").join("bar-link-link")).await?;
5401        let summary = copy(
5402            &PROGRESS,
5403            &tmp_dir.join("foo"),
5404            &tmp_dir.join("bar"),
5405            &Settings {
5406                reflink: Default::default(),
5407                local_copy_handoff: Default::default(),
5408                dereference: true, // <- important!
5409                fail_early: false,
5410                overwrite: false,
5411                overwrite_compare: filecmp::MetadataCmpSettings {
5412                    size: true,
5413                    mtime: true,
5414                    ..Default::default()
5415                },
5416                overwrite_filter: None,
5417                ignore_existing: false,
5418                chunk_size: 0,
5419                skip_specials: false,
5420                remote_copy_buffer_size: 0,
5421                filter: None,
5422                dry_run: None,
5423                delete: None,
5424            },
5425            &DO_PRESERVE_SETTINGS,
5426            false,
5427        )
5428        .await?;
5429        assert_eq!(summary.files_copied, 13); // 0.txt, 3x bar/(1.txt, 2.txt, 3.txt), baz/(4.txt, 5.txt, 6.txt)
5430        assert_eq!(summary.symlinks_created, 0); // dereference is set
5431        assert_eq!(summary.directories_created, 5);
5432        // check_dirs_identical doesn't handle dereference so let's do it manually
5433        tokio::process::Command::new("cp")
5434            .args(["-r", "-L"])
5435            .arg(tmp_dir.join("foo"))
5436            .arg(tmp_dir.join("bar-cp"))
5437            .output()
5438            .await?;
5439        testutils::check_dirs_identical(
5440            &tmp_dir.join("bar"),
5441            &tmp_dir.join("bar-cp"),
5442            testutils::FileEqualityCheck::Basic,
5443        )
5444        .await?;
5445        Ok(())
5446    }
5447
5448    /// Tests to verify error messages include root causes for debugging
5449    mod error_message_tests {
5450        use super::*;
5451
5452        /// Helper to extract full error message with chain
5453        fn get_full_error_message(error: &Error) -> String {
5454            format!("{:#}", error.source)
5455        }
5456
5457        #[tokio::test]
5458        #[traced_test]
5459        async fn test_nonexistent_source_includes_root_cause() -> Result<(), anyhow::Error> {
5460            let tmp_dir = testutils::create_temp_dir().await?;
5461
5462            let result = copy(
5463                &PROGRESS,
5464                &tmp_dir.join("does_not_exist.txt"),
5465                &tmp_dir.join("dest.txt"),
5466                &Settings {
5467                    reflink: Default::default(),
5468                    local_copy_handoff: Default::default(),
5469                    dereference: false,
5470                    fail_early: false,
5471                    overwrite: false,
5472                    overwrite_compare: Default::default(),
5473                    overwrite_filter: None,
5474                    ignore_existing: false,
5475                    chunk_size: 0,
5476                    skip_specials: false,
5477                    remote_copy_buffer_size: 0,
5478                    filter: None,
5479                    dry_run: None,
5480                    delete: None,
5481                },
5482                &NO_PRESERVE_SETTINGS,
5483                false,
5484            )
5485            .await;
5486
5487            assert!(result.is_err());
5488            let err_msg = get_full_error_message(&result.unwrap_err());
5489
5490            assert!(
5491                err_msg.to_lowercase().contains("no such file")
5492                    || err_msg.to_lowercase().contains("not found")
5493                    || err_msg.contains("ENOENT"),
5494                "Error message must include file not found text. Got: {}",
5495                err_msg
5496            );
5497            Ok(())
5498        }
5499
5500        #[tokio::test]
5501        #[traced_test]
5502        async fn test_unreadable_directory_includes_root_cause() -> Result<(), anyhow::Error> {
5503            let tmp_dir = testutils::create_temp_dir().await?;
5504            let unreadable_dir = tmp_dir.join("unreadable_dir");
5505            tokio::fs::create_dir(&unreadable_dir).await?;
5506            tokio::fs::set_permissions(&unreadable_dir, std::fs::Permissions::from_mode(0o000))
5507                .await?;
5508
5509            let result = copy(
5510                &PROGRESS,
5511                &unreadable_dir,
5512                &tmp_dir.join("dest"),
5513                &Settings {
5514                    reflink: Default::default(),
5515                    local_copy_handoff: Default::default(),
5516                    dereference: false,
5517                    fail_early: true,
5518                    overwrite: false,
5519                    overwrite_compare: Default::default(),
5520                    overwrite_filter: None,
5521                    ignore_existing: false,
5522                    chunk_size: 0,
5523                    skip_specials: false,
5524                    remote_copy_buffer_size: 0,
5525                    filter: None,
5526                    dry_run: None,
5527                    delete: None,
5528                },
5529                &NO_PRESERVE_SETTINGS,
5530                false,
5531            )
5532            .await;
5533
5534            assert!(result.is_err());
5535            let err_msg = get_full_error_message(&result.unwrap_err());
5536
5537            assert!(
5538                err_msg.to_lowercase().contains("permission")
5539                    || err_msg.contains("EACCES")
5540                    || err_msg.contains("denied"),
5541                "Error message must include permission-related text. Got: {}",
5542                err_msg
5543            );
5544
5545            // Clean up - restore permissions so cleanup can remove it
5546            tokio::fs::set_permissions(&unreadable_dir, std::fs::Permissions::from_mode(0o700))
5547                .await?;
5548            Ok(())
5549        }
5550
5551        #[tokio::test]
5552        #[traced_test]
5553        async fn test_destination_permission_error_includes_root_cause() -> Result<(), anyhow::Error>
5554        {
5555            let tmp_dir = testutils::setup_test_dir().await?;
5556            let test_path = tmp_dir.as_path();
5557            let readonly_parent = test_path.join("readonly_dest");
5558            tokio::fs::create_dir(&readonly_parent).await?;
5559            tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
5560                .await?;
5561
5562            let result = copy(
5563                &PROGRESS,
5564                &test_path.join("foo"),
5565                &readonly_parent.join("copy"),
5566                &Settings {
5567                    reflink: Default::default(),
5568                    local_copy_handoff: Default::default(),
5569                    dereference: false,
5570                    fail_early: true,
5571                    overwrite: false,
5572                    overwrite_compare: Default::default(),
5573                    overwrite_filter: None,
5574                    ignore_existing: false,
5575                    chunk_size: 0,
5576                    skip_specials: false,
5577                    remote_copy_buffer_size: 0,
5578                    filter: None,
5579                    dry_run: None,
5580                    delete: None,
5581                },
5582                &NO_PRESERVE_SETTINGS,
5583                false,
5584            )
5585            .await;
5586
5587            // restore permissions so cleanup succeeds even when copy fails
5588            tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
5589                .await?;
5590
5591            assert!(result.is_err(), "copy into read-only parent should fail");
5592            let err_msg = get_full_error_message(&result.unwrap_err());
5593
5594            assert!(
5595                err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
5596                "Error message must include permission denied text. Got: {}",
5597                err_msg
5598            );
5599            Ok(())
5600        }
5601
5602        // Regression guard for the reused-directory lockdown: WITHOUT --require-toctou-safe the
5603        // reuse branch leaves a pre-existing destination directory exactly as-is, so copying into a
5604        // read-only reused directory still fails EACCES. The lockdown that makes such a directory
5605        // writable for the copy is strict-mode only (exercised in common/tests/strict_resolution.rs);
5606        // this pins that the default path is unchanged.
5607        #[tokio::test]
5608        #[traced_test]
5609        async fn default_reused_readonly_dir_still_fails_eacces() -> Result<(), anyhow::Error> {
5610            let tmp_dir = testutils::setup_test_dir().await?;
5611            let test_path = tmp_dir.as_path();
5612            // reused destination directory: exists, owned by us, read-only
5613            let dst = test_path.join("dst");
5614            tokio::fs::create_dir(&dst).await?;
5615            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o500)).await?;
5616            let result = copy(
5617                &PROGRESS,
5618                &test_path.join("foo"),
5619                &dst,
5620                &Settings {
5621                    reflink: Default::default(),
5622                    local_copy_handoff: Default::default(),
5623                    dereference: false,
5624                    fail_early: true,
5625                    overwrite: true,
5626                    overwrite_compare: Default::default(),
5627                    overwrite_filter: None,
5628                    ignore_existing: false,
5629                    chunk_size: 0,
5630                    skip_specials: false,
5631                    remote_copy_buffer_size: 0,
5632                    filter: None,
5633                    dry_run: None,
5634                    delete: None,
5635                },
5636                &NO_PRESERVE_SETTINGS,
5637                false,
5638            )
5639            .await;
5640            // restore permissions so the tempdir cleanup can remove the directory
5641            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
5642            assert!(
5643                result.is_err(),
5644                "copy into a read-only reused directory must fail without strict mode"
5645            );
5646            let err_msg = get_full_error_message(&result.unwrap_err());
5647            assert!(
5648                err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
5649                "error must be a permission error. Got: {}",
5650                err_msg
5651            );
5652            Ok(())
5653        }
5654    }
5655
5656    mod empty_dir_cleanup_tests {
5657        use super::*;
5658        use crate::filter::FilterSettings;
5659        use std::path::Path;
5660        #[test]
5661        fn test_check_empty_dir_cleanup_no_filter() {
5662            // when no filter, always keep
5663            assert_eq!(
5664                check_empty_dir_cleanup(None, true, false, Path::new("any"), false),
5665                EmptyDirAction::Keep
5666            );
5667        }
5668        #[test]
5669        fn test_check_empty_dir_cleanup_something_copied() {
5670            // when content was copied, keep
5671            let mut filter = crate::filter::FilterSettings::new();
5672            filter.add_include("*.txt").unwrap();
5673            assert_eq!(
5674                check_empty_dir_cleanup(Some(&filter), true, true, Path::new("any"), false),
5675                EmptyDirAction::Keep
5676            );
5677        }
5678        #[test]
5679        fn test_check_empty_dir_cleanup_not_created() {
5680            // when we didn't create the directory, keep
5681            let mut filter = FilterSettings::new();
5682            filter.add_include("*.txt").unwrap();
5683            assert_eq!(
5684                check_empty_dir_cleanup(Some(&filter), false, false, Path::new("any"), false),
5685                EmptyDirAction::Keep
5686            );
5687        }
5688        #[test]
5689        fn test_check_empty_dir_cleanup_directly_matched() {
5690            // when directory directly matches include pattern, keep
5691            let mut filter = FilterSettings::new();
5692            filter.add_include("target/").unwrap();
5693            assert_eq!(
5694                check_empty_dir_cleanup(Some(&filter), true, false, Path::new("target"), false),
5695                EmptyDirAction::Keep
5696            );
5697        }
5698        #[test]
5699        fn test_check_empty_dir_cleanup_traversed_only() {
5700            // when directory was only traversed, remove
5701            let mut filter = FilterSettings::new();
5702            filter.add_include("*.txt").unwrap();
5703            assert_eq!(
5704                check_empty_dir_cleanup(Some(&filter), true, false, Path::new("src"), false),
5705                EmptyDirAction::Remove
5706            );
5707        }
5708        #[test]
5709        fn test_check_empty_dir_cleanup_dry_run() {
5710            // in dry-run mode, skip instead of remove
5711            let mut filter = FilterSettings::new();
5712            filter.add_include("*.txt").unwrap();
5713            assert_eq!(
5714                check_empty_dir_cleanup(Some(&filter), true, false, Path::new("src"), true),
5715                EmptyDirAction::DryRunSkip
5716            );
5717        }
5718        #[test]
5719        fn test_check_empty_dir_cleanup_root_always_kept() {
5720            // root directory is never removed, even with filter and nothing copied
5721            let mut filter = FilterSettings::new();
5722            filter.add_include("*.txt").unwrap();
5723            assert_eq!(
5724                check_empty_dir_cleanup(Some(&filter), true, false, Path::new(""), false),
5725                EmptyDirAction::Keep
5726            );
5727        }
5728        #[test]
5729        fn test_check_empty_dir_cleanup_root_kept_in_dry_run() {
5730            // root directory is kept even in dry-run mode
5731            let mut filter = FilterSettings::new();
5732            filter.add_include("*.txt").unwrap();
5733            assert_eq!(
5734                check_empty_dir_cleanup(Some(&filter), true, false, Path::new(""), true),
5735                EmptyDirAction::Keep
5736            );
5737        }
5738    }
5739
5740    /// Verify that directory metadata is applied even when child operations fail.
5741    /// This is a regression test for a bug where directory permissions were not preserved
5742    /// when copying with fail_early=false and some children failed to copy.
5743    #[tokio::test]
5744    #[traced_test]
5745    async fn test_directory_metadata_applied_on_child_error() -> Result<(), anyhow::Error> {
5746        let tmp_dir = testutils::create_temp_dir().await?;
5747        let test_path = tmp_dir.as_path();
5748        // create source directory with specific permissions
5749        let src_dir = test_path.join("src");
5750        tokio::fs::create_dir(&src_dir).await?;
5751        tokio::fs::set_permissions(&src_dir, std::fs::Permissions::from_mode(0o750)).await?;
5752        // create a readable file and an unreadable file inside
5753        let readable_file = src_dir.join("readable.txt");
5754        tokio::fs::write(&readable_file, "content").await?;
5755        let unreadable_file = src_dir.join("unreadable.txt");
5756        tokio::fs::write(&unreadable_file, "secret").await?;
5757        tokio::fs::set_permissions(&unreadable_file, std::fs::Permissions::from_mode(0o000))
5758            .await?;
5759        let dst_dir = test_path.join("dst");
5760        // copy with fail_early=false and preserve=all
5761        let result = copy(
5762            &PROGRESS,
5763            &src_dir,
5764            &dst_dir,
5765            &Settings {
5766                reflink: Default::default(),
5767                local_copy_handoff: Default::default(),
5768                dereference: false,
5769                fail_early: false,
5770                overwrite: false,
5771                overwrite_compare: Default::default(),
5772                overwrite_filter: None,
5773                ignore_existing: false,
5774                chunk_size: 0,
5775                skip_specials: false,
5776                remote_copy_buffer_size: 0,
5777                filter: None,
5778                dry_run: None,
5779                delete: None,
5780            },
5781            &DO_PRESERVE_SETTINGS,
5782            false,
5783        )
5784        .await;
5785        // restore permissions so cleanup can succeed
5786        tokio::fs::set_permissions(&unreadable_file, std::fs::Permissions::from_mode(0o644))
5787            .await?;
5788        // verify the operation returned an error (unreadable file should fail)
5789        assert!(result.is_err(), "copy should fail due to unreadable file");
5790        let error = result.unwrap_err();
5791        // verify some files were copied (the readable one)
5792        assert_eq!(error.summary.files_copied, 1);
5793        assert_eq!(error.summary.directories_created, 1);
5794        // verify the destination directory exists and has the correct permissions
5795        let dst_metadata = tokio::fs::metadata(&dst_dir).await?;
5796        assert!(dst_metadata.is_dir());
5797        let actual_mode = dst_metadata.permissions().mode() & 0o7777;
5798        assert_eq!(
5799            actual_mode, 0o750,
5800            "directory should have preserved source permissions (0o750), got {:o}",
5801            actual_mode
5802        );
5803        Ok(())
5804    }
5805
5806    /// A child copy failure inside a filter-traversal-only directory must surface as an overall
5807    /// error even though the now-empty directory is pruned (regression: the empty-dir cleanup path
5808    /// returned Ok and swallowed the collected child error, so a failed copy looked successful).
5809    #[tokio::test]
5810    #[traced_test]
5811    async fn pruned_empty_traversal_dir_still_surfaces_child_error() -> Result<(), anyhow::Error> {
5812        let tmp_dir = testutils::create_temp_dir().await?;
5813        let test_path = tmp_dir.as_path();
5814        let src_dir = test_path.join("src");
5815        let sub = src_dir.join("sub");
5816        tokio::fs::create_dir_all(&sub).await?;
5817        // the only entry under `sub` is unreadable, so its copy fails and nothing lands in `sub`,
5818        // leaving it an empty traversal-only directory that the filter cleanup prunes.
5819        let unreadable = sub.join("file.txt");
5820        tokio::fs::write(&unreadable, "secret").await?;
5821        tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
5822        let dst_dir = test_path.join("dst");
5823        let mut filter = crate::filter::FilterSettings::new();
5824        filter.add_include("*.txt").unwrap();
5825        let result = copy(
5826            &PROGRESS,
5827            &src_dir,
5828            &dst_dir,
5829            &Settings {
5830                reflink: Default::default(),
5831                local_copy_handoff: Default::default(),
5832                dereference: false,
5833                fail_early: false,
5834                overwrite: false,
5835                overwrite_compare: Default::default(),
5836                overwrite_filter: None,
5837                ignore_existing: false,
5838                chunk_size: 0,
5839                skip_specials: false,
5840                remote_copy_buffer_size: 0,
5841                filter: Some(filter),
5842                dry_run: None,
5843                delete: None,
5844            },
5845            &DO_PRESERVE_SETTINGS,
5846            false,
5847        )
5848        .await;
5849        // restore permissions so the temp dir can be cleaned up
5850        tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o644)).await?;
5851        assert!(
5852            result.is_err(),
5853            "the failed child copy must surface even though the empty traversal dir was pruned"
5854        );
5855        // the empty traversal directory itself was still cleaned up (count adjustment preserved).
5856        assert!(
5857            !dst_dir.join("sub").exists(),
5858            "empty traversal directory should have been removed"
5859        );
5860        Ok(())
5861    }
5862
5863    /// Verify that fail-early does not apply parent directory metadata after a child fails.
5864    #[tokio::test]
5865    #[traced_test]
5866    async fn test_fail_early_does_not_apply_parent_directory_metadata_after_child_error()
5867    -> Result<(), anyhow::Error> {
5868        let tmp_dir = testutils::create_temp_dir().await?;
5869        let test_path = tmp_dir.as_path();
5870        let src_dir = test_path.join("src");
5871        tokio::fs::create_dir(&src_dir).await?;
5872        tokio::fs::write(src_dir.join("readable.txt"), "content").await?;
5873        let unreadable_file = src_dir.join("unreadable.txt");
5874        tokio::fs::write(&unreadable_file, "secret").await?;
5875        tokio::fs::set_permissions(&unreadable_file, std::fs::Permissions::from_mode(0o000))
5876            .await?;
5877        let fixed_secs = 946684800;
5878        let fixed_nsec = 123_456_789;
5879        let fixed_time = nix::sys::time::TimeSpec::new(fixed_secs, fixed_nsec);
5880        nix::sys::stat::utimensat(
5881            nix::fcntl::AT_FDCWD,
5882            &src_dir,
5883            &fixed_time,
5884            &fixed_time,
5885            nix::sys::stat::UtimensatFlags::NoFollowSymlink,
5886        )?;
5887        let src_metadata = tokio::fs::metadata(&src_dir).await?;
5888        let dst_dir = test_path.join("dst");
5889        let result = copy(
5890            &PROGRESS,
5891            &src_dir,
5892            &dst_dir,
5893            &Settings {
5894                reflink: Default::default(),
5895                local_copy_handoff: Default::default(),
5896                dereference: false,
5897                fail_early: true,
5898                overwrite: false,
5899                overwrite_compare: Default::default(),
5900                overwrite_filter: None,
5901                ignore_existing: false,
5902                chunk_size: 0,
5903                skip_specials: false,
5904                remote_copy_buffer_size: 0,
5905                filter: None,
5906                dry_run: None,
5907                delete: None,
5908            },
5909            &DO_PRESERVE_SETTINGS,
5910            false,
5911        )
5912        .await;
5913        tokio::fs::set_permissions(&unreadable_file, std::fs::Permissions::from_mode(0o644))
5914            .await?;
5915        assert!(result.is_err(), "copy should fail due to unreadable file");
5916        let dst_metadata = tokio::fs::metadata(&dst_dir).await?;
5917        assert!(dst_metadata.is_dir());
5918        assert_ne!(
5919            (dst_metadata.mtime(), dst_metadata.mtime_nsec()),
5920            (src_metadata.mtime(), src_metadata.mtime_nsec()),
5921            "fail-early should return before applying preserved directory timestamps"
5922        );
5923        Ok(())
5924    }
5925    mod filter_tests {
5926        use super::*;
5927        use crate::filter::FilterSettings;
5928        /// Test that path-based patterns (with /) work correctly with nested paths.
5929        /// This test exposes the bug where only entry_name is passed to the filter
5930        /// instead of the relative path.
5931        #[tokio::test]
5932        #[traced_test]
5933        async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
5934            let tmp_dir = testutils::setup_test_dir().await?;
5935            let test_path = tmp_dir.as_path();
5936            // test directory structure from setup_test_dir:
5937            // foo/
5938            //   0.txt
5939            //   bar/
5940            //     1.txt
5941            //     2.txt
5942            //   baz/
5943            //     3.txt -> ../0.txt (symlink)
5944            //     4.txt
5945            //     5 -> ../bar (symlink)
5946            // create filter that should match bar/*.txt (files in bar directory)
5947            let mut filter = FilterSettings::new();
5948            filter.add_include("bar/*.txt").unwrap();
5949            let summary = copy(
5950                &PROGRESS,
5951                &test_path.join("foo"),
5952                &test_path.join("dst"),
5953                &Settings {
5954                    reflink: Default::default(),
5955                    local_copy_handoff: Default::default(),
5956                    dereference: false,
5957                    fail_early: false,
5958                    overwrite: false,
5959                    overwrite_compare: Default::default(),
5960                    overwrite_filter: None,
5961                    ignore_existing: false,
5962                    chunk_size: 0,
5963                    skip_specials: false,
5964                    remote_copy_buffer_size: 0,
5965                    filter: Some(filter),
5966                    dry_run: None,
5967                    delete: None,
5968                },
5969                &NO_PRESERVE_SETTINGS,
5970                false,
5971            )
5972            .await?;
5973            // should only copy files matching bar/*.txt pattern
5974            // bar/1.txt, bar/2.txt, and bar/3.txt should be copied
5975            assert_eq!(
5976                summary.files_copied, 3,
5977                "should copy 3 files matching bar/*.txt"
5978            );
5979            // verify the right files exist
5980            assert!(
5981                test_path.join("dst/bar/1.txt").exists(),
5982                "bar/1.txt should be copied"
5983            );
5984            assert!(
5985                test_path.join("dst/bar/2.txt").exists(),
5986                "bar/2.txt should be copied"
5987            );
5988            assert!(
5989                test_path.join("dst/bar/3.txt").exists(),
5990                "bar/3.txt should be copied"
5991            );
5992            // verify files outside the pattern don't exist
5993            assert!(
5994                !test_path.join("dst/0.txt").exists(),
5995                "0.txt should not be copied"
5996            );
5997            Ok(())
5998        }
5999        #[tokio::test]
6000        async fn anchored_nested_include_preserves_selection_and_dry_run_counts()
6001        -> anyhow::Result<()> {
6002            let root = testutils::create_temp_dir().await?;
6003            let src = root.join("source");
6004            tokio::fs::create_dir_all(src.join("sub")).await?;
6005            tokio::fs::write(src.join("keep.txt"), b"root decoy").await?;
6006            tokio::fs::write(src.join("sub/keep.txt"), b"nested match").await?;
6007            tokio::fs::write(src.join("sub/drop.txt"), b"nested decoy").await?;
6008            let mut filter = FilterSettings::new();
6009            filter.add_include("/sub/keep.txt")?;
6010            for dry_run in [false, true] {
6011                let dst = root.join(if dry_run { "preview" } else { "destination" });
6012                let mut settings = settings_with_delete(None);
6013                settings.filter = Some(filter.clone());
6014                settings.dry_run = dry_run.then_some(DryRunMode::Brief);
6015                let summary = copy(
6016                    &PROGRESS,
6017                    &src,
6018                    &dst,
6019                    &settings,
6020                    &NO_PRESERVE_SETTINGS,
6021                    false,
6022                )
6023                .await?;
6024                assert_eq!(summary.files_copied, 1);
6025                assert_eq!(summary.files_skipped, 2);
6026                assert_eq!(summary.directories_created, 2);
6027                if dry_run {
6028                    assert!(!dst.exists());
6029                } else {
6030                    assert_eq!(
6031                        tokio::fs::read(dst.join("sub/keep.txt")).await?,
6032                        b"nested match"
6033                    );
6034                    assert!(!dst.join("keep.txt").exists());
6035                    assert!(!dst.join("sub/drop.txt").exists());
6036                }
6037            }
6038            Ok(())
6039        }
6040
6041        /// Test that anchored patterns (starting with /) match only at root.
6042        #[tokio::test]
6043        #[traced_test]
6044        async fn test_anchored_pattern_matches_only_at_root() -> Result<(), anyhow::Error> {
6045            let tmp_dir = testutils::setup_test_dir().await?;
6046            let test_path = tmp_dir.as_path();
6047            // create filter that should match /bar/** (bar directory and all its contents)
6048            let mut filter = FilterSettings::new();
6049            filter.add_include("/bar/**").unwrap();
6050            let summary = copy(
6051                &PROGRESS,
6052                &test_path.join("foo"),
6053                &test_path.join("dst"),
6054                &Settings {
6055                    reflink: Default::default(),
6056                    local_copy_handoff: Default::default(),
6057                    dereference: false,
6058                    fail_early: false,
6059                    overwrite: false,
6060                    overwrite_compare: Default::default(),
6061                    overwrite_filter: None,
6062                    ignore_existing: false,
6063                    chunk_size: 0,
6064                    skip_specials: false,
6065                    remote_copy_buffer_size: 0,
6066                    filter: Some(filter),
6067                    dry_run: None,
6068                    delete: None,
6069                },
6070                &NO_PRESERVE_SETTINGS,
6071                false,
6072            )
6073            .await?;
6074            // should only copy bar directory and its contents
6075            assert!(
6076                test_path.join("dst/bar").exists(),
6077                "bar directory should be copied"
6078            );
6079            assert!(
6080                !test_path.join("dst/baz").exists(),
6081                "baz directory should not be copied"
6082            );
6083            assert!(
6084                !test_path.join("dst/0.txt").exists(),
6085                "0.txt should not be copied"
6086            );
6087            // verify summary counts
6088            assert_eq!(
6089                summary.files_copied, 3,
6090                "should copy 3 files in bar (1.txt, 2.txt, 3.txt)"
6091            );
6092            assert_eq!(
6093                summary.directories_created, 2,
6094                "should create 2 directories (root dst + bar)"
6095            );
6096            // skipped: 0.txt (file) and baz (directory) - baz contents not counted since dir is skipped
6097            assert_eq!(summary.files_skipped, 1, "should skip 1 file (0.txt)");
6098            assert_eq!(
6099                summary.directories_skipped, 1,
6100                "should skip 1 directory (baz)"
6101            );
6102            Ok(())
6103        }
6104        /// Test that double-star patterns (**) match across directories.
6105        #[tokio::test]
6106        #[traced_test]
6107        async fn test_double_star_pattern_matches_nested() -> Result<(), anyhow::Error> {
6108            let tmp_dir = testutils::setup_test_dir().await?;
6109            let test_path = tmp_dir.as_path();
6110            // create filter that should match all .txt files at any depth
6111            let mut filter = FilterSettings::new();
6112            filter.add_include("**/*.txt").unwrap();
6113            let summary = copy(
6114                &PROGRESS,
6115                &test_path.join("foo"),
6116                &test_path.join("dst"),
6117                &Settings {
6118                    reflink: Default::default(),
6119                    local_copy_handoff: Default::default(),
6120                    dereference: false,
6121                    fail_early: false,
6122                    overwrite: false,
6123                    overwrite_compare: Default::default(),
6124                    overwrite_filter: None,
6125                    ignore_existing: false,
6126                    chunk_size: 0,
6127                    skip_specials: false,
6128                    remote_copy_buffer_size: 0,
6129                    filter: Some(filter),
6130                    dry_run: None,
6131                    delete: None,
6132                },
6133                &NO_PRESERVE_SETTINGS,
6134                false,
6135            )
6136            .await?;
6137            // should copy all .txt files: 0.txt, bar/1.txt, bar/2.txt, bar/3.txt, baz/4.txt
6138            assert_eq!(
6139                summary.files_copied, 5,
6140                "should copy all 5 .txt files with **/*.txt pattern"
6141            );
6142            Ok(())
6143        }
6144        /// Test that filters are applied to top-level file arguments.
6145        #[tokio::test]
6146        #[traced_test]
6147        async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
6148            let tmp_dir = testutils::setup_test_dir().await?;
6149            let test_path = tmp_dir.as_path();
6150            // create filter that excludes .txt files
6151            let mut filter = FilterSettings::new();
6152            filter.add_exclude("*.txt").unwrap();
6153            let result = copy(
6154                &PROGRESS,
6155                &test_path.join("foo/0.txt"), // single file source
6156                &test_path.join("dst.txt"),
6157                &Settings {
6158                    reflink: Default::default(),
6159                    local_copy_handoff: Default::default(),
6160                    dereference: false,
6161                    fail_early: false,
6162                    overwrite: false,
6163                    overwrite_compare: Default::default(),
6164                    overwrite_filter: None,
6165                    ignore_existing: false,
6166                    chunk_size: 0,
6167                    skip_specials: false,
6168                    remote_copy_buffer_size: 0,
6169                    filter: Some(filter),
6170                    dry_run: None,
6171                    delete: None,
6172                },
6173                &NO_PRESERVE_SETTINGS,
6174                false,
6175            )
6176            .await?;
6177            // the file should NOT be copied because it matches the exclude pattern
6178            assert_eq!(
6179                result.files_copied, 0,
6180                "file matching exclude pattern should not be copied"
6181            );
6182            assert!(
6183                !test_path.join("dst.txt").exists(),
6184                "excluded file should not exist at destination"
6185            );
6186            Ok(())
6187        }
6188        /// Test that filters apply to root directories with simple exclude patterns.
6189        #[tokio::test]
6190        #[traced_test]
6191        async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
6192            let test_path = testutils::create_temp_dir().await?;
6193            // create a directory that should be excluded
6194            tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
6195            tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
6196            // create filter that excludes *_dir/ directories
6197            let mut filter = FilterSettings::new();
6198            filter.add_exclude("*_dir/").unwrap();
6199            let result = copy(
6200                &PROGRESS,
6201                &test_path.join("excluded_dir"),
6202                &test_path.join("dst"),
6203                &Settings {
6204                    reflink: Default::default(),
6205                    local_copy_handoff: Default::default(),
6206                    dereference: false,
6207                    fail_early: false,
6208                    overwrite: false,
6209                    overwrite_compare: Default::default(),
6210                    overwrite_filter: None,
6211                    ignore_existing: false,
6212                    chunk_size: 0,
6213                    skip_specials: false,
6214                    remote_copy_buffer_size: 0,
6215                    filter: Some(filter),
6216                    dry_run: None,
6217                    delete: None,
6218                },
6219                &NO_PRESERVE_SETTINGS,
6220                false,
6221            )
6222            .await?;
6223            // directory should NOT be copied because it matches exclude pattern
6224            assert_eq!(
6225                result.directories_created, 0,
6226                "root directory matching exclude should not be created"
6227            );
6228            assert!(
6229                !test_path.join("dst").exists(),
6230                "excluded root directory should not exist at destination"
6231            );
6232            Ok(())
6233        }
6234
6235        /// A root file admitted after the cheap filter cannot materialize an excluded replacement
6236        /// directory; the exact authoritative entry must make the final filter decision.
6237        #[tokio::test]
6238        #[traced_test]
6239        async fn root_file_swap_to_excluded_directory_is_rechecked_authoritatively()
6240        -> Result<(), anyhow::Error> {
6241            let root = testutils::create_temp_dir().await?;
6242            let src = root.join("source");
6243            let dst = root.join("destination");
6244            tokio::fs::write(&src, "INITIAL-FILE").await?;
6245
6246            let mut filter = FilterSettings::new();
6247            filter.add_exclude("source/")?;
6248            assert!(matches!(
6249                filter.should_include_root_item(std::path::Path::new("source"), false),
6250                crate::filter::FilterResult::Included
6251            ));
6252            assert!(!matches!(
6253                filter.should_include_root_item(std::path::Path::new("source"), true),
6254                crate::filter::FilterResult::Included
6255            ));
6256
6257            let admission = testutils::AdmissionLimit::new().await;
6258            admission.set_files_in_flight(1);
6259            let src_parent = Arc::new(
6260                Dir::open_parent_dir(&root, congestion::Side::Source)
6261                    .await?
6262                    .into_tree(),
6263            );
6264            let dst_parent = Arc::new(
6265                Dir::open_parent_dir(&root, congestion::Side::Destination)
6266                    .await?
6267                    .into_tree(),
6268            );
6269
6270            // the cheap root check above saw a file. replace it before the admitted final check.
6271            tokio::fs::remove_file(&src).await?;
6272            tokio::fs::create_dir(&src).await?;
6273            tokio::fs::write(src.join("replacement.txt"), "EXCLUDED").await?;
6274            let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
6275            let entry = crate::walk::classify_admitted_entry(
6276                &src_parent,
6277                std::ffi::OsStr::new("source"),
6278                permit,
6279            )
6280            .await?;
6281            assert_eq!(entry.kind(), EntryKind::Dir);
6282
6283            let mut settings = settings_with_delete(None);
6284            settings.filter = Some(filter);
6285            let summary = run_with_open_file_cleanup(
6286                &admission,
6287                run_copy_root(
6288                    &PROGRESS,
6289                    &src_parent,
6290                    Some(dst_parent),
6291                    std::ffi::OsStr::new("source"),
6292                    &src,
6293                    &dst,
6294                    &settings,
6295                    &NO_PRESERVE_SETTINGS,
6296                    false,
6297                    DestinationContext::new(&dst),
6298                    CopyEntryAdmission::Admitted(entry),
6299                ),
6300            )
6301            .await??;
6302
6303            assert_eq!(summary.directories_skipped, 1);
6304            assert_eq!(summary.directories_created, 0);
6305            assert!(
6306                !dst.exists(),
6307                "an excluded replacement directory must not be materialized"
6308            );
6309            Ok(())
6310        }
6311
6312        /// A nested reliable file hint may pass the cheap filter, but a replacement directory must
6313        /// be rechecked under admission and excluded before the exact entry reaches dispatch.
6314        #[tokio::test(flavor = "current_thread")]
6315        #[traced_test]
6316        async fn nested_file_swap_to_excluded_directory_is_rechecked_authoritatively()
6317        -> Result<(), anyhow::Error> {
6318            let root = testutils::create_temp_dir().await?;
6319            let src = root.join("source");
6320            let dst = root.join("destination");
6321            let node = src.join("node");
6322            tokio::fs::create_dir(&src).await?;
6323            tokio::fs::write(&node, "INITIAL-FILE").await?;
6324
6325            let mut filter = FilterSettings::new();
6326            filter.add_exclude("node/")?;
6327            assert!(matches!(
6328                filter.should_include(std::path::Path::new("node"), false),
6329                crate::filter::FilterResult::Included
6330            ));
6331            assert!(!matches!(
6332                filter.should_include(std::path::Path::new("node"), true),
6333                crate::filter::FilterResult::Included
6334            ));
6335
6336            // inject the reliable file hint captured before this replacement, so the boundary is
6337            // deterministic without depending on a scheduler race or filesystem-specific d_type.
6338            tokio::fs::remove_file(&node).await?;
6339            tokio::fs::create_dir(&node).await?;
6340            tokio::fs::write(node.join("replacement.txt"), "EXCLUDED").await?;
6341            tokio::fs::create_dir(&dst).await?;
6342            let admission = testutils::AdmissionLimit::new().await;
6343            admission.set_files_in_flight(1);
6344            let src_dir =
6345                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6346            let dst_dir =
6347                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
6348            for delete in [None, delete_on()] {
6349                let collect_names = delete.is_some();
6350                let visitor = Arc::new(CopyVisitor {
6351                    prog_track: &PROGRESS,
6352                    dst_root: dst.clone(),
6353                    destination: DestinationContext::new(&dst),
6354                    settings: {
6355                        let mut settings = settings_with_delete(delete);
6356                        settings.filter = Some(filter.clone());
6357                        settings
6358                    },
6359                    preserve: *NO_PRESERVE_SETTINGS,
6360                    dst_parent: None,
6361                    root_is_fresh: false,
6362                });
6363                let root_cx = EntryCx::root(
6364                    Arc::clone(&src_dir),
6365                    std::ffi::OsString::from("source"),
6366                    src.clone(),
6367                    &PROGRESS,
6368                );
6369                let child_ctx = CopyDirContext {
6370                    destination: DestinationContext::parent(None),
6371                    dst_dir: Some(Arc::clone(&dst_dir)),
6372                    is_fresh: true,
6373                };
6374                let (summary, processed) = run_with_open_file_cleanup(
6375                    &admission,
6376                    crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
6377                        Arc::clone(&visitor),
6378                        Arc::clone(&src_dir),
6379                        &root_cx,
6380                        &child_ctx,
6381                        vec![(std::ffi::OsString::from("node"), Some(EntryKind::File))],
6382                    )),
6383                )
6384                .await?
6385                .map_err(|error| error.source)?;
6386
6387                assert_eq!(summary.directories_skipped, 1);
6388                if collect_names {
6389                    assert!(processed.names().expect("delete collects names").is_empty());
6390                } else {
6391                    assert!(processed.names().is_none());
6392                }
6393                assert!(
6394                    !dst.join("node").exists(),
6395                    "an excluded nested replacement directory must not be materialized"
6396                );
6397            }
6398            Ok(())
6399        }
6400
6401        /// A stale directory hint cannot hide an included source file from `--delete`'s keep-set.
6402        #[tokio::test(flavor = "current_thread")]
6403        #[traced_test]
6404        async fn delete_rechecks_a_directory_hint_before_pruning_an_included_file()
6405        -> Result<(), anyhow::Error> {
6406            let root = testutils::create_temp_dir().await?;
6407            let src = root.join("source");
6408            let dst = root.join("destination");
6409            tokio::fs::create_dir(&src).await?;
6410            tokio::fs::create_dir(&dst).await?;
6411            tokio::fs::write(src.join("node"), "CURRENT-SOURCE-CONTENT").await?;
6412            tokio::fs::write(dst.join("node"), "OLD").await?;
6413
6414            let mut filter = FilterSettings::new();
6415            filter.add_exclude("node/")?;
6416            assert!(!matches!(
6417                filter.should_include(std::path::Path::new("node"), true),
6418                crate::filter::FilterResult::Included
6419            ));
6420            assert!(matches!(
6421                filter.should_include(std::path::Path::new("node"), false),
6422                crate::filter::FilterResult::Included
6423            ));
6424            let mut settings = settings_with_delete(delete_on());
6425            settings.filter = Some(filter);
6426
6427            let admission = testutils::AdmissionLimit::new().await;
6428            admission.set_files_in_flight(1);
6429            let src_dir =
6430                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6431            let dst_dir =
6432                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
6433            let visitor = Arc::new(CopyVisitor {
6434                prog_track: &PROGRESS,
6435                dst_root: dst.clone(),
6436                destination: DestinationContext::new(&dst),
6437                settings,
6438                preserve: *NO_PRESERVE_SETTINGS,
6439                dst_parent: None,
6440                root_is_fresh: false,
6441            });
6442            let root_cx = EntryCx::root(
6443                Arc::clone(&src_dir),
6444                std::ffi::OsString::from("source"),
6445                src.clone(),
6446                &PROGRESS,
6447            );
6448            let child_ctx = CopyDirContext {
6449                destination: DestinationContext::parent(None),
6450                dst_dir: Some(Arc::clone(&dst_dir)),
6451                is_fresh: false,
6452            };
6453
6454            // inject a stale directory hint for the real source file, then run the same post-order
6455            // prune that consumes the driver's processed-child keep-set.
6456            let (summary, processed) = run_with_open_file_cleanup(&admission, async {
6457                let (mut summary, processed) =
6458                    crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
6459                        Arc::clone(&visitor),
6460                        Arc::clone(&src_dir),
6461                        &root_cx,
6462                        &child_ctx,
6463                        vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
6464                    ))
6465                    .await
6466                    .map_err(|error| error.source)?;
6467                visitor
6468                    .prune_finished_dir(
6469                        &mut summary,
6470                        &crate::delete::DeleteDecision::from_processed(
6471                            visitor.settings.delete.as_ref().unwrap(),
6472                            Some(&processed),
6473                        )
6474                        .into_ready(&dst)
6475                        .expect("delete traversal completed"),
6476                        &src_dir,
6477                        &dst_dir,
6478                        &root_cx.rel_path,
6479                    )
6480                    .await?;
6481                Ok::<_, anyhow::Error>((summary, processed))
6482            })
6483            .await??;
6484
6485            assert_eq!(
6486                processed.names().expect("delete collects names"),
6487                &[std::ffi::OsString::from("node")]
6488            );
6489            assert_eq!(summary.files_copied, 1);
6490            assert_eq!(summary.rm_summary.files_removed, 1);
6491            assert_eq!(
6492                tokio::fs::read_to_string(dst.join("node")).await?,
6493                "CURRENT-SOURCE-CONTENT"
6494            );
6495            Ok(())
6496        }
6497
6498        /// A dry-run preview is authoritative even without `--delete`: a stale directory hint must
6499        /// not suppress the included regular file that now occupies the name.
6500        #[tokio::test(flavor = "current_thread")]
6501        #[traced_test]
6502        async fn dry_run_rechecks_a_directory_hint_before_previewing_an_included_file()
6503        -> Result<(), anyhow::Error> {
6504            let root = testutils::create_temp_dir().await?;
6505            let src = root.join("source");
6506            let dst = root.join("destination");
6507            tokio::fs::create_dir(&src).await?;
6508            tokio::fs::write(src.join("node"), "CURRENT-SOURCE-CONTENT").await?;
6509            let mut filter = FilterSettings::new();
6510            filter.add_exclude("node/")?;
6511            assert!(!matches!(
6512                filter.should_include(std::path::Path::new("node"), true),
6513                crate::filter::FilterResult::Included
6514            ));
6515            assert!(matches!(
6516                filter.should_include(std::path::Path::new("node"), false),
6517                crate::filter::FilterResult::Included
6518            ));
6519            let mut settings = settings_with_delete(None);
6520            settings.filter = Some(filter);
6521            settings.dry_run = Some(crate::config::DryRunMode::Brief);
6522            let admission = testutils::AdmissionLimit::new().await;
6523            admission.set_files_in_flight(1);
6524            let src_dir =
6525                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6526            let visitor = Arc::new(CopyVisitor {
6527                prog_track: &PROGRESS,
6528                dst_root: dst.clone(),
6529                destination: DestinationContext::new(&dst),
6530                settings,
6531                preserve: *NO_PRESERVE_SETTINGS,
6532                dst_parent: None,
6533                root_is_fresh: false,
6534            });
6535            let root_cx = EntryCx::root(
6536                Arc::clone(&src_dir),
6537                std::ffi::OsString::from("source"),
6538                src.clone(),
6539                &PROGRESS,
6540            );
6541            let (summary, processed) = run_with_open_file_cleanup(
6542                &admission,
6543                crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
6544                    visitor,
6545                    src_dir,
6546                    &root_cx,
6547                    &CopyDirContext {
6548                        destination: DestinationContext::parent(None),
6549                        dst_dir: None,
6550                        is_fresh: false,
6551                    },
6552                    vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
6553                )),
6554            )
6555            .await??;
6556            assert!(
6557                processed.names().is_none(),
6558                "copy without --delete does not retain names"
6559            );
6560            assert_eq!(summary.files_copied, 1);
6561            assert_eq!(summary.directories_skipped, 0);
6562            Ok(())
6563        }
6564
6565        /// Test that filters apply to root symlinks with simple exclude patterns.
6566        #[tokio::test]
6567        #[traced_test]
6568        async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
6569            let test_path = testutils::create_temp_dir().await?;
6570            // create a target file and a symlink to it
6571            tokio::fs::write(test_path.join("target.txt"), "content").await?;
6572            tokio::fs::symlink(
6573                test_path.join("target.txt"),
6574                test_path.join("excluded_link"),
6575            )
6576            .await?;
6577            // create filter that excludes *_link
6578            let mut filter = FilterSettings::new();
6579            filter.add_exclude("*_link").unwrap();
6580            let result = copy(
6581                &PROGRESS,
6582                &test_path.join("excluded_link"),
6583                &test_path.join("dst"),
6584                &Settings {
6585                    reflink: Default::default(),
6586                    local_copy_handoff: Default::default(),
6587                    dereference: false,
6588                    fail_early: false,
6589                    overwrite: false,
6590                    overwrite_compare: Default::default(),
6591                    overwrite_filter: None,
6592                    ignore_existing: false,
6593                    chunk_size: 0,
6594                    skip_specials: false,
6595                    remote_copy_buffer_size: 0,
6596                    filter: Some(filter),
6597                    dry_run: None,
6598                    delete: None,
6599                },
6600                &NO_PRESERVE_SETTINGS,
6601                false,
6602            )
6603            .await?;
6604            // symlink should NOT be copied because it matches exclude pattern
6605            assert_eq!(
6606                result.symlinks_created, 0,
6607                "root symlink matching exclude should not be created"
6608            );
6609            assert!(
6610                !test_path.join("dst").exists(),
6611                "excluded root symlink should not exist at destination"
6612            );
6613            Ok(())
6614        }
6615        /// Test combined include and exclude patterns (exclude takes precedence).
6616        #[tokio::test]
6617        #[traced_test]
6618        async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
6619            let tmp_dir = testutils::setup_test_dir().await?;
6620            let test_path = tmp_dir.as_path();
6621            // test structure from setup_test_dir:
6622            // foo/
6623            //   0.txt
6624            //   bar/ (1.txt, 2.txt, 3.txt)
6625            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
6626            // include all .txt files, but exclude bar/2.txt specifically
6627            let mut filter = FilterSettings::new();
6628            filter.add_include("**/*.txt").unwrap();
6629            filter.add_exclude("bar/2.txt").unwrap();
6630            let summary = copy(
6631                &PROGRESS,
6632                &test_path.join("foo"),
6633                &test_path.join("dst"),
6634                &Settings {
6635                    reflink: Default::default(),
6636                    local_copy_handoff: Default::default(),
6637                    dereference: false,
6638                    fail_early: false,
6639                    overwrite: false,
6640                    overwrite_compare: Default::default(),
6641                    overwrite_filter: None,
6642                    ignore_existing: false,
6643                    chunk_size: 0,
6644                    skip_specials: false,
6645                    remote_copy_buffer_size: 0,
6646                    filter: Some(filter),
6647                    dry_run: None,
6648                    delete: None,
6649                },
6650                &NO_PRESERVE_SETTINGS,
6651                false,
6652            )
6653            .await?;
6654            // should copy: 0.txt, bar/1.txt, bar/3.txt, baz/4.txt = 4 files
6655            // should skip: bar/2.txt (excluded by pattern) = 1 file
6656            // symlinks 5.txt and 6.txt don't match *.txt include pattern (symlinks, not files)
6657            assert_eq!(summary.files_copied, 4, "should copy 4 .txt files");
6658            assert_eq!(
6659                summary.files_skipped, 1,
6660                "should skip 1 file (bar/2.txt excluded)"
6661            );
6662            // verify specific files
6663            assert!(
6664                test_path.join("dst/bar/1.txt").exists(),
6665                "bar/1.txt should be copied"
6666            );
6667            assert!(
6668                !test_path.join("dst/bar/2.txt").exists(),
6669                "bar/2.txt should be excluded"
6670            );
6671            assert!(
6672                test_path.join("dst/bar/3.txt").exists(),
6673                "bar/3.txt should be copied"
6674            );
6675            Ok(())
6676        }
6677        /// Test that skipped counts accurately reflect what was filtered.
6678        #[tokio::test]
6679        #[traced_test]
6680        async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
6681            let tmp_dir = testutils::setup_test_dir().await?;
6682            let test_path = tmp_dir.as_path();
6683            // test structure from setup_test_dir:
6684            // foo/
6685            //   0.txt
6686            //   bar/ (1.txt, 2.txt, 3.txt)
6687            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
6688            // exclude bar/ directory entirely
6689            let mut filter = FilterSettings::new();
6690            filter.add_exclude("bar/").unwrap();
6691            let summary = copy(
6692                &PROGRESS,
6693                &test_path.join("foo"),
6694                &test_path.join("dst"),
6695                &Settings {
6696                    reflink: Default::default(),
6697                    local_copy_handoff: Default::default(),
6698                    dereference: false,
6699                    fail_early: false,
6700                    overwrite: false,
6701                    overwrite_compare: Default::default(),
6702                    overwrite_filter: None,
6703                    ignore_existing: false,
6704                    chunk_size: 0,
6705                    skip_specials: false,
6706                    remote_copy_buffer_size: 0,
6707                    filter: Some(filter),
6708                    dry_run: None,
6709                    delete: None,
6710                },
6711                &NO_PRESERVE_SETTINGS,
6712                false,
6713            )
6714            .await?;
6715            // copied: 0.txt (1 file), baz/4.txt (1 file), 5.txt symlink, 6.txt symlink
6716            // skipped: bar directory (1 dir) - contents not counted since whole dir skipped
6717            // directories: foo (root), baz = 2
6718            assert_eq!(summary.files_copied, 2, "should copy 2 files");
6719            assert_eq!(summary.symlinks_created, 2, "should copy 2 symlinks");
6720            assert_eq!(
6721                summary.directories_created, 2,
6722                "should create 2 directories"
6723            );
6724            assert_eq!(
6725                summary.directories_skipped, 1,
6726                "should skip 1 directory (bar)"
6727            );
6728            assert_eq!(
6729                summary.files_skipped, 0,
6730                "no files skipped (bar contents not counted)"
6731            );
6732            Ok(())
6733        }
6734        /// Test that empty directories are not created when they were only traversed to look
6735        /// for matches (regression test for bug where --include='foo' would create empty dir baz).
6736        #[tokio::test]
6737        #[traced_test]
6738        async fn test_empty_dir_not_created_when_only_traversed() -> Result<(), anyhow::Error> {
6739            let test_path = testutils::create_temp_dir().await?;
6740            // create structure:
6741            // src/
6742            //   foo (file)
6743            //   bar (file)
6744            //   baz/ (empty directory)
6745            let src_path = test_path.join("src");
6746            tokio::fs::create_dir(&src_path).await?;
6747            tokio::fs::write(src_path.join("foo"), "content").await?;
6748            tokio::fs::write(src_path.join("bar"), "content").await?;
6749            tokio::fs::create_dir(src_path.join("baz")).await?;
6750            // include only 'foo' file
6751            let mut filter = FilterSettings::new();
6752            filter.add_include("foo").unwrap();
6753            let summary = copy(
6754                &PROGRESS,
6755                &src_path,
6756                &test_path.join("dst"),
6757                &Settings {
6758                    reflink: Default::default(),
6759                    local_copy_handoff: Default::default(),
6760                    dereference: false,
6761                    fail_early: false,
6762                    overwrite: false,
6763                    overwrite_compare: Default::default(),
6764                    overwrite_filter: None,
6765                    ignore_existing: false,
6766                    chunk_size: 0,
6767                    skip_specials: false,
6768                    remote_copy_buffer_size: 0,
6769                    filter: Some(filter),
6770                    dry_run: None,
6771                    delete: None,
6772                },
6773                &NO_PRESERVE_SETTINGS,
6774                false,
6775            )
6776            .await?;
6777            // only 'foo' should be copied
6778            assert_eq!(summary.files_copied, 1, "should copy only 'foo' file");
6779            assert_eq!(
6780                summary.directories_created, 1,
6781                "should create only root directory (not empty 'baz')"
6782            );
6783            // verify foo was copied
6784            assert!(
6785                test_path.join("dst").join("foo").exists(),
6786                "foo should be copied"
6787            );
6788            // verify bar was not copied (not matching include pattern)
6789            assert!(
6790                !test_path.join("dst").join("bar").exists(),
6791                "bar should not be copied"
6792            );
6793            // verify empty baz directory was NOT created
6794            assert!(
6795                !test_path.join("dst").join("baz").exists(),
6796                "empty baz directory should NOT be created"
6797            );
6798            Ok(())
6799        }
6800        /// Test that directories with only non-matching content are not created at destination.
6801        /// This is different from empty directories - the source dir has content but none matches.
6802        #[tokio::test]
6803        #[traced_test]
6804        async fn test_dir_with_nonmatching_content_not_created() -> Result<(), anyhow::Error> {
6805            let test_path = testutils::create_temp_dir().await?;
6806            // create structure:
6807            // src/
6808            //   foo (file)
6809            //   baz/
6810            //     qux (file - doesn't match 'foo')
6811            //     quux (file - doesn't match 'foo')
6812            let src_path = test_path.join("src");
6813            tokio::fs::create_dir(&src_path).await?;
6814            tokio::fs::write(src_path.join("foo"), "content").await?;
6815            tokio::fs::create_dir(src_path.join("baz")).await?;
6816            tokio::fs::write(src_path.join("baz").join("qux"), "content").await?;
6817            tokio::fs::write(src_path.join("baz").join("quux"), "content").await?;
6818            // include only 'foo' file
6819            let mut filter = FilterSettings::new();
6820            filter.add_include("foo").unwrap();
6821            let summary = copy(
6822                &PROGRESS,
6823                &src_path,
6824                &test_path.join("dst"),
6825                &Settings {
6826                    reflink: Default::default(),
6827                    local_copy_handoff: Default::default(),
6828                    dereference: false,
6829                    fail_early: false,
6830                    overwrite: false,
6831                    overwrite_compare: Default::default(),
6832                    overwrite_filter: None,
6833                    ignore_existing: false,
6834                    chunk_size: 0,
6835                    skip_specials: false,
6836                    remote_copy_buffer_size: 0,
6837                    filter: Some(filter),
6838                    dry_run: None,
6839                    delete: None,
6840                },
6841                &NO_PRESERVE_SETTINGS,
6842                false,
6843            )
6844            .await?;
6845            // only 'foo' should be copied
6846            assert_eq!(summary.files_copied, 1, "should copy only 'foo' file");
6847            assert_eq!(
6848                summary.files_skipped, 2,
6849                "should skip 2 files (qux and quux)"
6850            );
6851            assert_eq!(
6852                summary.directories_created, 1,
6853                "should create only root directory (not 'baz' with non-matching content)"
6854            );
6855            // verify foo was copied
6856            assert!(
6857                test_path.join("dst").join("foo").exists(),
6858                "foo should be copied"
6859            );
6860            // verify baz directory was NOT created (even though source baz has content)
6861            assert!(
6862                !test_path.join("dst").join("baz").exists(),
6863                "baz directory should NOT be created (no matching content inside)"
6864            );
6865            Ok(())
6866        }
6867        /// Test that empty directories are not reported as created in dry-run mode
6868        /// when they were only traversed.
6869        #[tokio::test]
6870        #[traced_test]
6871        async fn test_dry_run_empty_dir_not_reported_as_created() -> Result<(), anyhow::Error> {
6872            let test_path = testutils::create_temp_dir().await?;
6873            // create structure:
6874            // src/
6875            //   foo (file)
6876            //   bar (file)
6877            //   baz/ (empty directory)
6878            let src_path = test_path.join("src");
6879            tokio::fs::create_dir(&src_path).await?;
6880            tokio::fs::write(src_path.join("foo"), "content").await?;
6881            tokio::fs::write(src_path.join("bar"), "content").await?;
6882            tokio::fs::create_dir(src_path.join("baz")).await?;
6883            // include only 'foo' file
6884            let mut filter = FilterSettings::new();
6885            filter.add_include("foo").unwrap();
6886            let summary = copy(
6887                &PROGRESS,
6888                &src_path,
6889                &test_path.join("dst"),
6890                &Settings {
6891                    reflink: Default::default(),
6892                    local_copy_handoff: Default::default(),
6893                    dereference: false,
6894                    fail_early: false,
6895                    overwrite: false,
6896                    overwrite_compare: Default::default(),
6897                    overwrite_filter: None,
6898                    ignore_existing: false,
6899                    chunk_size: 0,
6900                    skip_specials: false,
6901                    remote_copy_buffer_size: 0,
6902                    filter: Some(filter),
6903                    dry_run: Some(crate::config::DryRunMode::Explain),
6904                    delete: None,
6905                },
6906                &NO_PRESERVE_SETTINGS,
6907                false,
6908            )
6909            .await?;
6910            // only 'foo' should be reported as would-be-copied
6911            assert_eq!(
6912                summary.files_copied, 1,
6913                "should report only 'foo' would be copied"
6914            );
6915            assert_eq!(
6916                summary.directories_created, 1,
6917                "should report only root directory would be created (not empty 'baz')"
6918            );
6919            // verify nothing was actually created (dry-run mode)
6920            assert!(
6921                !test_path.join("dst").exists(),
6922                "dst should not exist in dry-run"
6923            );
6924            Ok(())
6925        }
6926        /// Test that existing directories are NOT removed when using --overwrite,
6927        /// even if nothing is copied into them due to filters.
6928        #[tokio::test]
6929        #[traced_test]
6930        async fn test_existing_dir_not_removed_with_overwrite() -> Result<(), anyhow::Error> {
6931            let test_path = testutils::create_temp_dir().await?;
6932            // create source structure:
6933            // src/
6934            //   foo (file)
6935            //   bar (file)
6936            //   baz/ (empty directory)
6937            let src_path = test_path.join("src");
6938            tokio::fs::create_dir(&src_path).await?;
6939            tokio::fs::write(src_path.join("foo"), "content").await?;
6940            tokio::fs::write(src_path.join("bar"), "content").await?;
6941            tokio::fs::create_dir(src_path.join("baz")).await?;
6942            // create destination with baz directory already existing
6943            let dst_path = test_path.join("dst");
6944            tokio::fs::create_dir(&dst_path).await?;
6945            tokio::fs::create_dir(dst_path.join("baz")).await?;
6946            // add a marker file inside dst/baz to verify we don't touch it
6947            tokio::fs::write(dst_path.join("baz").join("marker.txt"), "existing").await?;
6948            // include only 'foo' file - baz should not match
6949            let mut filter = FilterSettings::new();
6950            filter.add_include("foo").unwrap();
6951            let summary = copy(
6952                &PROGRESS,
6953                &src_path,
6954                &dst_path,
6955                &Settings {
6956                    reflink: Default::default(),
6957                    local_copy_handoff: Default::default(),
6958                    dereference: false,
6959                    fail_early: false,
6960                    overwrite: true, // enable overwrite mode
6961                    overwrite_compare: Default::default(),
6962                    overwrite_filter: None,
6963                    ignore_existing: false,
6964                    chunk_size: 0,
6965                    skip_specials: false,
6966                    remote_copy_buffer_size: 0,
6967                    filter: Some(filter),
6968                    dry_run: None,
6969                    delete: None,
6970                },
6971                &NO_PRESERVE_SETTINGS,
6972                false,
6973            )
6974            .await?;
6975            // foo should be copied
6976            assert_eq!(summary.files_copied, 1, "should copy only 'foo' file");
6977            // dst and baz should be unchanged (both already existed)
6978            assert_eq!(
6979                summary.directories_unchanged, 2,
6980                "root dst and baz directories should be unchanged"
6981            );
6982            assert_eq!(
6983                summary.directories_created, 0,
6984                "should not create any directories"
6985            );
6986            // verify foo was copied
6987            assert!(dst_path.join("foo").exists(), "foo should be copied");
6988            // verify bar was NOT copied
6989            assert!(!dst_path.join("bar").exists(), "bar should not be copied");
6990            // verify existing baz directory still exists with its content
6991            assert!(
6992                dst_path.join("baz").exists(),
6993                "existing baz directory should still exist"
6994            );
6995            assert!(
6996                dst_path.join("baz").join("marker.txt").exists(),
6997                "existing content in baz should still exist"
6998            );
6999            Ok(())
7000        }
7001    }
7002    mod dry_run_tests {
7003        use super::*;
7004        use crate::filter::FilterSettings;
7005        /// Test that dry-run mode for directories doesn't create the destination
7006        /// and doesn't try to set metadata on non-existent directories.
7007        #[tokio::test]
7008        #[traced_test]
7009        async fn test_dry_run_directory_does_not_create_destination() -> Result<(), anyhow::Error> {
7010            let tmp_dir = testutils::setup_test_dir().await?;
7011            let test_path = tmp_dir.as_path();
7012            let dst_path = test_path.join("nonexistent_dst");
7013            // verify destination doesn't exist
7014            assert!(
7015                !dst_path.exists(),
7016                "destination should not exist before dry-run"
7017            );
7018            let summary = copy(
7019                &PROGRESS,
7020                &test_path.join("foo"),
7021                &dst_path,
7022                &Settings {
7023                    reflink: Default::default(),
7024                    local_copy_handoff: Default::default(),
7025                    dereference: false,
7026                    fail_early: false,
7027                    overwrite: false,
7028                    overwrite_compare: Default::default(),
7029                    overwrite_filter: None,
7030                    ignore_existing: false,
7031                    chunk_size: 0,
7032                    skip_specials: false,
7033                    remote_copy_buffer_size: 0,
7034                    filter: None,
7035                    dry_run: Some(crate::config::DryRunMode::Brief),
7036                    delete: None,
7037                },
7038                &NO_PRESERVE_SETTINGS,
7039                false,
7040            )
7041            .await?;
7042            // verify destination still doesn't exist
7043            assert!(
7044                !dst_path.exists(),
7045                "dry-run should not create destination directory"
7046            );
7047            // verify summary reports what would be created
7048            assert!(
7049                summary.directories_created > 0,
7050                "dry-run should report directories that would be created"
7051            );
7052            assert!(
7053                summary.files_copied > 0,
7054                "dry-run should report files that would be copied"
7055            );
7056            Ok(())
7057        }
7058        /// Regression: in dry-run, `--ignore-existing` must report an existing destination file as
7059        /// skipped (files_unchanged), not as a would-be copy. The dry-run signal is `dst_parent ==
7060        /// None`, so the skip must probe existence by path rather than via a held dst fd.
7061        #[tokio::test]
7062        async fn dry_run_ignore_existing_reports_file_as_skipped() -> Result<(), anyhow::Error> {
7063            let tmp = testutils::create_temp_dir().await?;
7064            let src = tmp.join("src.txt");
7065            let dst = tmp.join("dst.txt");
7066            tokio::fs::write(&src, "new").await?;
7067            tokio::fs::write(&dst, "old").await?; // destination already exists and differs
7068            let summary = copy(
7069                &PROGRESS,
7070                &src,
7071                &dst,
7072                &Settings {
7073                    reflink: Default::default(),
7074                    local_copy_handoff: Default::default(),
7075                    dereference: false,
7076                    fail_early: false,
7077                    overwrite: false,
7078                    overwrite_compare: Default::default(),
7079                    overwrite_filter: None,
7080                    ignore_existing: true,
7081                    chunk_size: 0,
7082                    skip_specials: false,
7083                    remote_copy_buffer_size: 0,
7084                    filter: None,
7085                    dry_run: Some(crate::config::DryRunMode::Brief),
7086                    delete: None,
7087                },
7088                &NO_PRESERVE_SETTINGS,
7089                false,
7090            )
7091            .await?;
7092            assert_eq!(
7093                summary.files_unchanged, 1,
7094                "existing file must be reported skipped in dry-run under --ignore-existing"
7095            );
7096            assert_eq!(
7097                summary.files_copied, 0,
7098                "must not report a would-be copy when --ignore-existing skips"
7099            );
7100            assert_eq!(
7101                tokio::fs::read_to_string(&dst).await?,
7102                "old",
7103                "dry-run must not mutate the destination"
7104            );
7105            Ok(())
7106        }
7107        /// Regression: the symlink counterpart of `dry_run_ignore_existing_reports_file_as_skipped`
7108        /// — an existing destination must be reported as `symlinks_unchanged`, not `symlinks_created`.
7109        #[tokio::test]
7110        async fn dry_run_ignore_existing_reports_symlink_as_skipped() -> Result<(), anyhow::Error> {
7111            let tmp = testutils::create_temp_dir().await?;
7112            let src = tmp.join("src_link");
7113            let dst = tmp.join("dst_link");
7114            tokio::fs::symlink("some/target", &src).await?;
7115            tokio::fs::write(&dst, "existing").await?; // destination already exists (any type)
7116            let summary = copy(
7117                &PROGRESS,
7118                &src,
7119                &dst,
7120                &Settings {
7121                    reflink: Default::default(),
7122                    local_copy_handoff: Default::default(),
7123                    dereference: false,
7124                    fail_early: false,
7125                    overwrite: false,
7126                    overwrite_compare: Default::default(),
7127                    overwrite_filter: None,
7128                    ignore_existing: true,
7129                    chunk_size: 0,
7130                    skip_specials: false,
7131                    remote_copy_buffer_size: 0,
7132                    filter: None,
7133                    dry_run: Some(crate::config::DryRunMode::Brief),
7134                    delete: None,
7135                },
7136                &NO_PRESERVE_SETTINGS,
7137                false,
7138            )
7139            .await?;
7140            assert_eq!(
7141                summary.symlinks_unchanged, 1,
7142                "existing symlink dst must be reported skipped in dry-run under --ignore-existing"
7143            );
7144            assert_eq!(
7145                summary.symlinks_created, 0,
7146                "must not report a would-be symlink creation when --ignore-existing skips"
7147            );
7148            Ok(())
7149        }
7150        /// A destination SYMLINK is a non-directory to `--ignore-existing`, even when it points at a
7151        /// directory, so the whole subtree is skipped — and the dry run must predict that.
7152        ///
7153        /// Dry-run and real execution both classify the final component without following it. A
7154        /// path-based `Path::is_dir()` probe would follow the link and incorrectly predict that the
7155        /// subtree is copied instead of skipped.
7156        #[tokio::test]
7157        #[traced_test]
7158        async fn dry_run_ignore_existing_reports_dir_behind_a_symlink_as_skipped()
7159        -> Result<(), anyhow::Error> {
7160            let tmp = testutils::create_temp_dir().await?;
7161            let src = tmp.join("src_dir");
7162            tokio::fs::create_dir(&src).await?;
7163            tokio::fs::write(src.join("child.txt"), "content").await?;
7164            // the destination is a SYMLINK pointing at a real directory
7165            let link_target = tmp.join("elsewhere");
7166            tokio::fs::create_dir(&link_target).await?;
7167            let dst = tmp.join("dst_dir");
7168            tokio::fs::symlink(&link_target, &dst).await?;
7169            let summary = copy(
7170                &PROGRESS,
7171                &src,
7172                &dst,
7173                &Settings {
7174                    reflink: Default::default(),
7175                    local_copy_handoff: Default::default(),
7176                    dereference: false,
7177                    fail_early: false,
7178                    overwrite: false,
7179                    overwrite_compare: Default::default(),
7180                    overwrite_filter: None,
7181                    ignore_existing: true,
7182                    chunk_size: 0,
7183                    skip_specials: false,
7184                    remote_copy_buffer_size: 0,
7185                    filter: None,
7186                    dry_run: Some(crate::config::DryRunMode::Brief),
7187                    delete: None,
7188                },
7189                &NO_PRESERVE_SETTINGS,
7190                false,
7191            )
7192            .await?;
7193            assert_eq!(
7194                summary.directories_unchanged, 1,
7195                "a destination symlink is a non-directory, so --ignore-existing skips the subtree; \
7196                 dry-run must report that rather than following the link"
7197            );
7198            assert_eq!(
7199                summary.directories_created, 0,
7200                "must not report a would-be directory creation when --ignore-existing skips"
7201            );
7202            assert_eq!(
7203                summary.files_copied, 0,
7204                "the skipped subtree's children must not be reported as would-be-copied"
7205            );
7206            Ok(())
7207        }
7208
7209        /// A destination lookup that FAILS is not a vacant destination: `--dry-run` must report the
7210        /// failure rather than predicting a copy the real run cannot perform.
7211        ///
7212        /// The unprobeable destination has to be a NESTED one for this to isolate the probe. Sealing
7213        /// the destination's own parent would exercise the root operand's `open_parent_dir` instead
7214        /// of the child probe. The destination ROOT is therefore a directory the copy can find but
7215        /// not traverse (`0o600` — readable, not searchable), which only the path-based child probe
7216        /// touches: a dry run creates and opens no destination directories, so nothing else in the
7217        /// copy needs to traverse it.
7218        ///
7219        /// Skipped for root, which ignores the permission bits this relies on.
7220        #[tokio::test]
7221        #[traced_test]
7222        async fn dry_run_ignore_existing_reports_an_unprobeable_destination_as_an_error()
7223        -> Result<(), anyhow::Error> {
7224            if nix::unistd::geteuid().is_root() {
7225                eprintln!("skipping: root bypasses the directory permissions this test relies on");
7226                return Ok(());
7227            }
7228            let tmp = testutils::create_temp_dir().await?;
7229            let src = tmp.join("src_dir");
7230            tokio::fs::create_dir(&src).await?;
7231            // EMPTY, deliberately: a file inside it would be caught by the FILE probe
7232            // ([`dry_run_dst_exists`]) instead, and the test would pass without the directory probe
7233            // ever mattering. With nothing under `sub`, the directory probe is the only thing that can
7234            // notice; it is therefore the only probe capable of observing the EACCES.
7235            tokio::fs::create_dir(src.join("sub")).await?;
7236            // the destination root exists but is NOT searchable, so probing `dst/sub` inside it gets
7237            // EACCES — "could not look", not "nothing is there"
7238            let sealed = tmp.join("dst_dir");
7239            tokio::fs::create_dir(&sealed).await?;
7240            tokio::fs::set_permissions(&sealed, std::fs::Permissions::from_mode(0o600)).await?;
7241            let result = copy(
7242                &PROGRESS,
7243                &src,
7244                &sealed,
7245                &Settings {
7246                    reflink: Default::default(),
7247                    local_copy_handoff: Default::default(),
7248                    dereference: false,
7249                    fail_early: false,
7250                    overwrite: false,
7251                    overwrite_compare: Default::default(),
7252                    overwrite_filter: None,
7253                    ignore_existing: true,
7254                    chunk_size: 0,
7255                    skip_specials: false,
7256                    remote_copy_buffer_size: 0,
7257                    filter: None,
7258                    dry_run: Some(crate::config::DryRunMode::Brief),
7259                    delete: None,
7260                },
7261                &NO_PRESERVE_SETTINGS,
7262                false,
7263            )
7264            .await;
7265            // restore permissions so the temp dir can be cleaned up
7266            tokio::fs::set_permissions(&sealed, std::fs::Permissions::from_mode(0o700)).await?;
7267            let error = result.expect_err(
7268                "an unprobeable destination must be reported, not treated as vacant and predicted \
7269                 as a copy",
7270            );
7271            let rendered = format!("{:#}", error.source);
7272            assert!(
7273                rendered.contains("Permission denied"),
7274                "the error must keep the real cause; got: {rendered}"
7275            );
7276            Ok(())
7277        }
7278
7279        /// Test that root directory is always created even when nothing matches
7280        /// the include pattern. The root is the user-specified source — it should
7281        /// never be removed/skipped due to empty-dir cleanup.
7282        #[tokio::test]
7283        #[traced_test]
7284        async fn test_root_dir_preserved_when_nothing_matches() -> Result<(), anyhow::Error> {
7285            let test_path = testutils::create_temp_dir().await?;
7286            // create structure:
7287            // src/
7288            //   bar.log (doesn't match *.txt)
7289            //   baz/ (empty directory)
7290            let src_path = test_path.join("src");
7291            tokio::fs::create_dir(&src_path).await?;
7292            tokio::fs::write(src_path.join("bar.log"), "content").await?;
7293            tokio::fs::create_dir(src_path.join("baz")).await?;
7294            // include only *.txt - nothing in source matches
7295            let mut filter = FilterSettings::new();
7296            filter.add_include("*.txt").unwrap();
7297            let dst_path = test_path.join("dst");
7298            let summary = copy(
7299                &PROGRESS,
7300                &src_path,
7301                &dst_path,
7302                &Settings {
7303                    reflink: Default::default(),
7304                    local_copy_handoff: Default::default(),
7305                    dereference: false,
7306                    fail_early: false,
7307                    overwrite: false,
7308                    overwrite_compare: Default::default(),
7309                    overwrite_filter: None,
7310                    ignore_existing: false,
7311                    chunk_size: 0,
7312                    skip_specials: false,
7313                    remote_copy_buffer_size: 0,
7314                    filter: Some(filter),
7315                    dry_run: None,
7316                    delete: None,
7317                },
7318                &NO_PRESERVE_SETTINGS,
7319                false,
7320            )
7321            .await?;
7322            // no files should be copied
7323            assert_eq!(summary.files_copied, 0, "no files match *.txt");
7324            // root directory should still be created
7325            assert_eq!(
7326                summary.directories_created, 1,
7327                "root directory should always be created"
7328            );
7329            assert!(dst_path.exists(), "root destination directory should exist");
7330            // non-matching subdirectories should not be created
7331            assert!(
7332                !dst_path.join("baz").exists(),
7333                "empty baz should not be created"
7334            );
7335            Ok(())
7336        }
7337        /// Test that root directory is counted in dry-run even when nothing matches.
7338        #[tokio::test]
7339        #[traced_test]
7340        async fn test_root_dir_counted_in_dry_run_when_nothing_matches() -> Result<(), anyhow::Error>
7341        {
7342            let test_path = testutils::create_temp_dir().await?;
7343            let src_path = test_path.join("src");
7344            tokio::fs::create_dir(&src_path).await?;
7345            tokio::fs::write(src_path.join("bar.log"), "content").await?;
7346            // include only *.txt - nothing matches
7347            let mut filter = FilterSettings::new();
7348            filter.add_include("*.txt").unwrap();
7349            let dst_path = test_path.join("dst");
7350            let summary = copy(
7351                &PROGRESS,
7352                &src_path,
7353                &dst_path,
7354                &Settings {
7355                    reflink: Default::default(),
7356                    local_copy_handoff: Default::default(),
7357                    dereference: false,
7358                    fail_early: false,
7359                    overwrite: false,
7360                    overwrite_compare: Default::default(),
7361                    overwrite_filter: None,
7362                    ignore_existing: false,
7363                    chunk_size: 0,
7364                    skip_specials: false,
7365                    remote_copy_buffer_size: 0,
7366                    filter: Some(filter),
7367                    dry_run: Some(crate::config::DryRunMode::Explain),
7368                    delete: None,
7369                },
7370                &NO_PRESERVE_SETTINGS,
7371                false,
7372            )
7373            .await?;
7374            assert_eq!(summary.files_copied, 0, "no files match *.txt");
7375            assert_eq!(
7376                summary.directories_created, 1,
7377                "root directory should be counted in dry-run"
7378            );
7379            assert!(
7380                !dst_path.exists(),
7381                "nothing should be created in dry-run mode"
7382            );
7383            Ok(())
7384        }
7385    }
7386
7387    /// Stress tests exercise max-files-in-flight saturation during copy.
7388    mod max_files_in_flight_tests {
7389        use super::*;
7390
7391        /// Public root setup must reserve open-file capacity before opening operand parents or
7392        /// performing an fd-based filter probe.
7393        #[tokio::test]
7394        async fn filtered_public_root_waits_for_admission_before_setup() -> anyhow::Result<()> {
7395            let root = testutils::create_temp_dir().await?;
7396            let src = root.join("src");
7397            let dst = root.join("dst");
7398            tokio::fs::write(&src, b"x").await?;
7399            let mut filter = crate::filter::FilterSettings::new();
7400            filter.add_exclude("src")?;
7401            let mut settings = settings_with_delete(None);
7402            settings.filter = Some(filter);
7403            let admission = testutils::AdmissionLimit::new().await;
7404            admission.set_files_in_flight(1);
7405            let stat_resource =
7406                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7407            admission.set_max_ops_in_flight(stat_resource, 1);
7408            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7409            let operation = copy(
7410                &PROGRESS,
7411                &src,
7412                &dst,
7413                &settings,
7414                &NO_PRESERVE_SETTINGS,
7415                false,
7416            );
7417            tokio::pin!(operation);
7418            let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
7419            let mut second_permit = Box::pin(throttle::open_file_permit());
7420            let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
7421            drop(second_permit);
7422            drop(held_stat);
7423            let result = admission
7424                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7425                .await;
7426            assert!(
7427                stopped_at_stat_gate,
7428                "copy root did not reach the held stat gate"
7429            );
7430            let summary =
7431                result.context("copy root did not resume after stat capacity was released")??;
7432            assert!(
7433                !setup_bypassed_admission,
7434                "copy performed root setup before open-file admission"
7435            );
7436            assert_eq!(summary.files_skipped, 1);
7437            Ok(())
7438        }
7439
7440        /// An entry with no `d_type` hint reserves open-file capacity under the shared
7441        /// pre-spawn policy.
7442        #[tokio::test]
7443        async fn unknown_type_reserves_max_files_in_flight_capacity() {
7444            let admission = testutils::AdmissionLimit::new().await;
7445            admission.set_files_in_flight(1);
7446            let held_permit = throttle::open_file_permit().await;
7447            let visitor = CopyVisitor {
7448                prog_track: &PROGRESS,
7449                dst_root: PathBuf::new(),
7450                destination: DestinationContext::new(std::path::Path::new("dst")),
7451                settings: settings_with_delete(None),
7452                preserve: *NO_PRESERVE_SETTINGS,
7453                dst_parent: None,
7454                root_is_fresh: false,
7455            };
7456            let acquire = crate::walk::preacquire_leaf_permit(visitor.permit_kind(), None);
7457            tokio::pin!(acquire);
7458            assert!(
7459                futures::poll!(acquire.as_mut()).is_pending(),
7460                "DT_UNKNOWN must not bypass pre-spawn open-file backpressure"
7461            );
7462            drop(held_permit);
7463            let permit = acquire.await;
7464            assert!(
7465                permit.is_some(),
7466                "DT_UNKNOWN must reserve capacity for authoritative classification"
7467            );
7468        }
7469
7470        /// A non-dereferenced symlink must retain its admission permit through the
7471        /// fd-bearing readlink/create work, not release it immediately after classification.
7472        #[tokio::test]
7473        async fn symlink_holds_open_file_capacity_until_copy_finishes() -> anyhow::Result<()> {
7474            let root = testutils::create_temp_dir().await?;
7475            let src_name = std::ffi::OsStr::new("src-link");
7476            let dst_name = std::ffi::OsStr::new("dst-link");
7477            tokio::fs::symlink("target", root.join(src_name)).await?;
7478            let admission = testutils::AdmissionLimit::new().await;
7479            let src_parent = Arc::new(
7480                Dir::open_parent_dir(&root, congestion::Side::Source)
7481                    .await?
7482                    .into_tree(),
7483            );
7484            let dst_parent = Arc::new(
7485                Dir::open_parent_dir(&root, congestion::Side::Destination)
7486                    .await?
7487                    .into_tree(),
7488            );
7489            let handle = src_parent.child(src_name).await?;
7490            assert_eq!(handle.kind(), EntryKind::Symlink);
7491            let dst_root = root.join(dst_name);
7492            let visitor = CopyVisitor {
7493                prog_track: &PROGRESS,
7494                dst_root: dst_root.clone(),
7495                destination: DestinationContext::new(&dst_root),
7496                settings: settings_with_delete(None),
7497                preserve: *NO_PRESERVE_SETTINGS,
7498                dst_parent: Some(Arc::clone(&dst_parent)),
7499                root_is_fresh: true,
7500            };
7501            let cx = EntryCx::root(
7502                src_parent,
7503                src_name.to_owned(),
7504                root.join(src_name),
7505                &PROGRESS,
7506            );
7507            let parent_ctx = CopyDirContext {
7508                destination: DestinationContext::parent(None),
7509                dst_dir: Some(dst_parent),
7510                is_fresh: true,
7511            };
7512            admission.set_files_in_flight(1);
7513            let permit = Some(LeafPermit::OpenFile(throttle::open_file_permit().await));
7514            let readlink_resource =
7515                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::ReadLink);
7516            admission.set_max_ops_in_flight(readlink_resource, 1);
7517            let held_readlink = throttle::ops_in_flight_permit(readlink_resource).await;
7518            let leaf = AdmittedLeaf::try_new(handle, permit)
7519                .map_err(|_| anyhow::anyhow!("symlink classification returned a directory"))?;
7520            let visit = visitor.visit_leaf(&cx, &parent_ctx, leaf);
7521            tokio::pin!(visit);
7522            let stopped_at_readlink_gate = futures::poll!(visit.as_mut()).is_pending();
7523            let mut second_permit = Box::pin(throttle::open_file_permit());
7524            let released_before_copy_finished = futures::poll!(second_permit.as_mut()).is_ready();
7525            drop(second_permit);
7526            drop(held_readlink);
7527            let result = admission
7528                .run_with_timeout(std::time::Duration::from_secs(20), visit.as_mut())
7529                .await;
7530            assert!(
7531                stopped_at_readlink_gate,
7532                "symlink copy did not reach the held readlink gate"
7533            );
7534            assert!(
7535                !released_before_copy_finished,
7536                "symlink released its open-file permit while fd-bearing work was still pending"
7537            );
7538            let summary = result
7539                .context("symlink copy did not resume after readlink capacity was released")?
7540                .map_err(|error| error.source)?;
7541            assert_eq!(summary.symlinks_created, 1);
7542            assert_eq!(
7543                tokio::fs::read_link(root.join(dst_name)).await?,
7544                std::path::Path::new("target")
7545            );
7546            Ok(())
7547        }
7548
7549        /// A dereferenced symlink must transfer its admission guard into the target copy. Releasing
7550        /// it before `canonicalize` lets a wide directory of symlinks spawn unbounded target walks
7551        /// which open parent/entry fds before reacquiring capacity.
7552        #[tokio::test]
7553        async fn dereferenced_symlink_transfers_open_file_capacity_to_target_copy()
7554        -> anyhow::Result<()> {
7555            let root = testutils::create_temp_dir().await?;
7556            let src_name = std::ffi::OsStr::new("src-link");
7557            tokio::fs::write(root.join("target"), b"payload").await?;
7558            tokio::fs::symlink("target", root.join(src_name)).await?;
7559            let admission = testutils::AdmissionLimit::new().await;
7560            let src_parent = Arc::new(
7561                Dir::open_parent_dir(&root, congestion::Side::Source)
7562                    .await?
7563                    .into_tree(),
7564            );
7565            let handle = src_parent.child(src_name).await?;
7566            let mut settings = settings_with_delete(None);
7567            settings.dereference = true;
7568            settings.dry_run = Some(crate::config::DryRunMode::Brief);
7569            let dst_root = root.join("dst");
7570            let visitor = CopyVisitor {
7571                prog_track: &PROGRESS,
7572                dst_root: dst_root.clone(),
7573                destination: DestinationContext::new(&dst_root),
7574                settings,
7575                preserve: *NO_PRESERVE_SETTINGS,
7576                dst_parent: None,
7577                root_is_fresh: false,
7578            };
7579            let cx = EntryCx::root(
7580                src_parent,
7581                src_name.to_owned(),
7582                root.join(src_name),
7583                &PROGRESS,
7584            );
7585            let parent_ctx = CopyDirContext {
7586                destination: DestinationContext::parent(None),
7587                dst_dir: None,
7588                is_fresh: false,
7589            };
7590            admission.set_files_in_flight(1);
7591            let permit = Some(LeafPermit::OpenFile(throttle::open_file_permit().await));
7592            let stat_resource =
7593                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7594            admission.set_max_ops_in_flight(stat_resource, 1);
7595            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7596            let leaf = AdmittedLeaf::try_new(handle, permit)
7597                .map_err(|_| anyhow::anyhow!("symlink classification returned a directory"))?;
7598            let visit = visitor.visit_leaf(&cx, &parent_ctx, leaf);
7599            tokio::pin!(visit);
7600            let stopped_at_canonicalize_gate = futures::poll!(visit.as_mut()).is_pending();
7601            // Queue a test waiter immediately behind canonicalize. Once canonicalize releases its
7602            // Stat slot, FIFO semaphore ordering gives that slot to this waiter before the target
7603            // root setup can acquire its next Stat slot. Holding it therefore pins `visit` inside
7604            // target setup, on the far side of the guard-transfer boundary.
7605            let mut target_setup_gate = Box::pin(throttle::ops_in_flight_permit(stat_resource));
7606            let target_setup_waiter_queued =
7607                futures::poll!(target_setup_gate.as_mut()).is_pending();
7608            drop(held_stat);
7609            let gate_race = tokio::time::timeout(std::time::Duration::from_secs(20), async {
7610                tokio::select! {
7611                    permit = target_setup_gate.as_mut() => Ok(permit),
7612                    result = visit.as_mut() => Err(result),
7613                }
7614            })
7615            .await;
7616            let mut setup_guard = None;
7617            let mut early_visit_result = None;
7618            let gate_timed_out = match gate_race {
7619                Ok(Ok(guard)) => {
7620                    setup_guard = Some(guard);
7621                    false
7622                }
7623                Ok(Err(result)) => {
7624                    early_visit_result = Some(result);
7625                    false
7626                }
7627                Err(_) => true,
7628            };
7629            drop(target_setup_gate);
7630            let finished_before_target_setup = early_visit_result.is_some();
7631            let mut second_permit = Box::pin(throttle::open_file_permit());
7632            let released_inside_target_setup = futures::poll!(second_permit.as_mut()).is_ready();
7633            drop(second_permit);
7634            drop(setup_guard);
7635            let result = match early_visit_result {
7636                Some(result) => Ok(result),
7637                None => {
7638                    admission
7639                        .run_with_timeout(std::time::Duration::from_secs(20), visit.as_mut())
7640                        .await
7641                }
7642            };
7643            assert!(
7644                stopped_at_canonicalize_gate,
7645                "dereference did not reach the held canonicalize Stat gate"
7646            );
7647            assert!(
7648                target_setup_waiter_queued,
7649                "target-setup test waiter did not queue behind canonicalize"
7650            );
7651            assert!(
7652                !gate_timed_out,
7653                "canonicalize did not release its Stat slot"
7654            );
7655            assert!(
7656                !finished_before_target_setup,
7657                "dereferenced copy finished before reaching target setup"
7658            );
7659            assert!(
7660                !released_inside_target_setup,
7661                "dereference released admission instead of transferring it into target setup"
7662            );
7663            let summary = result
7664                .context("dereferenced copy did not resume after target setup was released")?
7665                .map_err(|error| error.source)?;
7666            assert_eq!(summary.files_copied, 1);
7667            Ok(())
7668        }
7669
7670        /// A dereferenced symlink whose target is a directory must release the transferred guard
7671        /// after authoritative target classification. Any strong ambient admission retained by the
7672        /// outer symlink visitor would make the first descendant wait forever at a limit of one.
7673        #[tokio::test]
7674        async fn dereferenced_symlink_directory_releases_capacity_before_descent()
7675        -> anyhow::Result<()> {
7676            let root = testutils::create_temp_dir().await?;
7677            let target = root.join("target");
7678            let src = root.join("src-link");
7679            let dst = root.join("dst");
7680            tokio::fs::create_dir(&target).await?;
7681            tokio::fs::write(target.join("child"), b"payload").await?;
7682            tokio::fs::symlink("target", &src).await?;
7683            let mut settings = settings_with_delete(None);
7684            settings.dereference = true;
7685            let admission = testutils::AdmissionLimit::new().await;
7686            admission.set_files_in_flight(1);
7687            let result = admission
7688                .run_with_timeout(
7689                    std::time::Duration::from_secs(20),
7690                    copy(
7691                        &PROGRESS,
7692                        &src,
7693                        &dst,
7694                        &settings,
7695                        &NO_PRESERVE_SETTINGS,
7696                        false,
7697                    ),
7698                )
7699                .await;
7700            let summary = result.context(
7701                "dereferenced directory copy retained admission across recursive descent",
7702            )??;
7703            assert_eq!(summary.files_copied, 1);
7704            assert_eq!(tokio::fs::read(dst.join("child")).await?, b"payload");
7705            Ok(())
7706        }
7707
7708        /// Cancelling the real local data-copy boundary must retain admission until its
7709        /// non-cancellable fd-owning job and abandoned output have both dropped.
7710        #[tokio::test]
7711        async fn cancelled_copy_file_fd_retains_capacity_until_its_fds_close() -> anyhow::Result<()>
7712        {
7713            use std::os::unix::fs::PermissionsExt as _;
7714            let root = testutils::create_temp_dir().await?;
7715            let src = root.join("source");
7716            let dst = root.join("destination");
7717            if let Err(error) = tokio::fs::write(&src, vec![b'x'; 4096]).await {
7718                let _ = tokio::fs::remove_dir_all(&root).await;
7719                return Err(error.into());
7720            }
7721            if let Err(error) =
7722                tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o755)).await
7723            {
7724                let _ = tokio::fs::remove_dir_all(&root).await;
7725                return Err(error.into());
7726            }
7727            let observed_dst = dst.clone();
7728            let gate = testutils::BlockingPathGate::install(dst.clone());
7729            let admission = testutils::AdmissionLimit::new().await;
7730            admission.set_files_in_flight(1);
7731            let timeout = std::time::Duration::from_secs(20);
7732            let settings = settings_with_delete(None);
7733            let task = tokio::spawn(async move {
7734                copy(
7735                    &PROGRESS,
7736                    &src,
7737                    &dst,
7738                    &settings,
7739                    &NO_PRESERVE_SETTINGS,
7740                    false,
7741                )
7742                .await
7743            });
7744            let observations =
7745                testutils::cancel_at_blocking_path(admission, gate, task, timeout, |_| {
7746                    std::fs::metadata(&observed_dst).map(|meta| meta.permissions().mode() & 0o7777)
7747                })
7748                .await;
7749            let final_mode =
7750                std::fs::metadata(&observed_dst).map(|meta| meta.permissions().mode() & 0o7777);
7751            let cleanup_result = tokio::fs::remove_dir_all(root).await;
7752            let (observations, mode_while_gated) = observations?;
7753            cleanup_result?;
7754            assert_eq!(mode_while_gated?, 0o600);
7755            assert_eq!(final_mode?, 0o600);
7756
7757            assert!(observations.waiter_was_cancelled);
7758            assert!(
7759                observations.admission_was_retained_while_work_gated,
7760                "cancelling copy_file_fd released capacity while its fd-owning job was live"
7761            );
7762            assert!(
7763                observations.fd_was_open_while_work_gated,
7764                "copy_file_fd closed its fd while the job was gated"
7765            );
7766            assert_eq!(observations.hit_count_before_release, 1);
7767            assert!(
7768                observations.fd_was_closed_at_output_drop_start,
7769                "copy_file_fd reached its output-drop boundary before its destination fd closed"
7770            );
7771            assert!(
7772                observations.admission_was_retained_at_output_drop_start,
7773                "copy_file_fd released capacity before its abandoned output dropped"
7774            );
7775            assert_eq!(observations.final_hit_count, 1);
7776            Ok(())
7777        }
7778
7779        /// Wide copy: many files with a very low files-in-flight limit.
7780        /// Verifies all files are copied correctly under permit saturation.
7781        #[tokio::test]
7782        #[traced_test]
7783        async fn wide_copy_under_files_in_flight_saturation() -> Result<(), anyhow::Error> {
7784            let tmp_dir = testutils::create_temp_dir().await?;
7785            let src = tmp_dir.join("src");
7786            let dst = tmp_dir.join("dst");
7787            tokio::fs::create_dir(&src).await?;
7788            let file_count = 200;
7789            for i in 0..file_count {
7790                tokio::fs::write(src.join(format!("{}.txt", i)), format!("content-{}", i)).await?;
7791            }
7792            // set a very low limit to force permit contention
7793            let admission = testutils::AdmissionLimit::new().await;
7794            admission.set_files_in_flight(4);
7795            let summary = admission
7796                .run_with_timeout(
7797                    std::time::Duration::from_secs(30),
7798                    copy(
7799                        &PROGRESS,
7800                        &src,
7801                        &dst,
7802                        &Settings {
7803                            reflink: Default::default(),
7804                            local_copy_handoff: Default::default(),
7805                            dereference: false,
7806                            fail_early: true,
7807                            overwrite: false,
7808                            overwrite_compare: Default::default(),
7809                            overwrite_filter: None,
7810                            ignore_existing: false,
7811                            chunk_size: 0,
7812                            skip_specials: false,
7813                            remote_copy_buffer_size: 0,
7814                            filter: None,
7815                            dry_run: None,
7816                            delete: None,
7817                        },
7818                        &NO_PRESERVE_SETTINGS,
7819                        false,
7820                    ),
7821                )
7822                .await
7823                .context("copy timed out — possible deadlock")??;
7824            assert_eq!(summary.files_copied, file_count);
7825            assert_eq!(summary.directories_created, 1);
7826            for i in 0..file_count {
7827                let content = tokio::fs::read_to_string(dst.join(format!("{}.txt", i))).await?;
7828                assert_eq!(content, format!("content-{}", i));
7829            }
7830            Ok(())
7831        }
7832
7833        /// Deep + wide copy: a directory tree deeper than the files-in-flight limit, with files at
7834        /// every level. Verifies directories do not retain leaf admission across recursion.
7835        #[tokio::test]
7836        #[traced_test]
7837        async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
7838        -> Result<(), anyhow::Error> {
7839            let tmp_dir = testutils::create_temp_dir().await?;
7840            let src = tmp_dir.join("src");
7841            let dst = tmp_dir.join("dst");
7842            let depth = 20;
7843            let files_per_level = 5;
7844            let limit = 1;
7845            // create a directory chain deeper than the permit limit, with files at each level
7846            let mut dir = src.clone();
7847            for level in 0..depth {
7848                tokio::fs::create_dir_all(&dir).await?;
7849                for f in 0..files_per_level {
7850                    tokio::fs::write(
7851                        dir.join(format!("f{}_{}.txt", level, f)),
7852                        format!("L{}F{}", level, f),
7853                    )
7854                    .await?;
7855                }
7856                dir = dir.join(format!("d{}", level));
7857            }
7858            let admission = testutils::AdmissionLimit::new().await;
7859            admission.set_files_in_flight(limit);
7860            let summary = admission
7861                .run_with_timeout(
7862                    std::time::Duration::from_secs(30),
7863                    copy(
7864                        &PROGRESS,
7865                        &src,
7866                        &dst,
7867                        &Settings {
7868                            reflink: Default::default(),
7869                            local_copy_handoff: Default::default(),
7870                            dereference: false,
7871                            fail_early: true,
7872                            overwrite: false,
7873                            overwrite_compare: Default::default(),
7874                            overwrite_filter: None,
7875                            ignore_existing: false,
7876                            chunk_size: 0,
7877                            skip_specials: false,
7878                            remote_copy_buffer_size: 0,
7879                            filter: None,
7880                            dry_run: None,
7881                            delete: None,
7882                        },
7883                        &NO_PRESERVE_SETTINGS,
7884                        false,
7885                    ),
7886                )
7887                .await
7888                .context("copy timed out — possible deadlock")?
7889                .context("copy failed")?;
7890            assert_eq!(summary.files_copied, depth * files_per_level);
7891            assert_eq!(summary.directories_created, depth);
7892            // spot-check content at a few levels
7893            let mut check_dir = dst.clone();
7894            for level in 0..depth {
7895                let content =
7896                    tokio::fs::read_to_string(check_dir.join(format!("f{}_0.txt", level))).await?;
7897                assert_eq!(content, format!("L{}F0", level));
7898                check_dir = check_dir.join(format!("d{}", level));
7899            }
7900            Ok(())
7901        }
7902
7903        /// Regression: copy-file overwrite removal must use the separate rm pool.
7904        ///
7905        /// Scenario: many parallel copies overwrite destinations that are directories. Each
7906        /// `copy_child` / `copy_file_fd` path retains OpenFile admission while `remove_existing`
7907        /// invokes recursive `rm_child`. If rm also drew from OpenFile, a saturated pool would
7908        /// deadlock — every permit would be held by a copy task waiting for rm to release one. The
7909        /// separate PendingMeta pool avoids that cycle.
7910        #[tokio::test]
7911        #[traced_test]
7912        async fn parallel_overwrite_dir_with_file_no_deadlock() -> Result<(), anyhow::Error> {
7913            let tmp_dir = testutils::create_temp_dir().await?;
7914            let src = tmp_dir.join("src");
7915            let dst = tmp_dir.join("dst");
7916            tokio::fs::create_dir(&src).await?;
7917            tokio::fs::create_dir(&dst).await?;
7918            // 8 sources are regular files; the 8 corresponding destinations
7919            // are directories with nested files — copy with --overwrite
7920            // forces rm of each dst directory tree from inside copy_file_fd.
7921            let n = 8;
7922            for i in 0..n {
7923                tokio::fs::write(src.join(format!("e{}", i)), format!("file-{}", i)).await?;
7924                let dst_subdir = dst.join(format!("e{}", i));
7925                tokio::fs::create_dir(&dst_subdir).await?;
7926                for j in 0..3 {
7927                    tokio::fs::write(
7928                        dst_subdir.join(format!("inner_{}.txt", j)),
7929                        format!("inner-{}-{}", i, j),
7930                    )
7931                    .await?;
7932                }
7933            }
7934            // saturate the OpenFile pool: if rm shared it, the outer copy tasks would hold every
7935            // permit and their inner rm recursions would block forever.
7936            let admission = testutils::AdmissionLimit::new().await;
7937            admission.set_files_in_flight(2);
7938            let summary = admission
7939                .run_with_timeout(
7940                    std::time::Duration::from_secs(30),
7941                    copy(
7942                        &PROGRESS,
7943                        &src,
7944                        &dst,
7945                        &Settings {
7946                            reflink: Default::default(),
7947                            local_copy_handoff: Default::default(),
7948                            dereference: false,
7949                            fail_early: true,
7950                            overwrite: true,
7951                            overwrite_compare: Default::default(),
7952                            overwrite_filter: None,
7953                            ignore_existing: false,
7954                            chunk_size: 0,
7955                            skip_specials: false,
7956                            remote_copy_buffer_size: 0,
7957                            filter: None,
7958                            dry_run: None,
7959                            delete: None,
7960                        },
7961                        &NO_PRESERVE_SETTINGS,
7962                        false,
7963                    ),
7964                )
7965                .await
7966                .context(
7967                    "copy timed out — deadlock between copy_file_fd's OpenFile permit and inner rm",
7968                )?
7969                .context("copy failed")?;
7970            assert_eq!(summary.files_copied, n);
7971            assert_eq!(summary.rm_summary.files_removed, n * 3);
7972            assert_eq!(summary.rm_summary.directories_removed, n);
7973            for i in 0..n {
7974                let path = dst.join(format!("e{}", i));
7975                let content = tokio::fs::read_to_string(&path).await?;
7976                assert_eq!(content, format!("file-{}", i));
7977            }
7978            Ok(())
7979        }
7980    }
7981
7982    mod skip_specials_tests {
7983        use super::*;
7984
7985        #[tokio::test]
7986        #[traced_test]
7987        async fn skip_specials_skips_socket_in_directory() -> Result<(), anyhow::Error> {
7988            let tmp_dir = testutils::setup_test_dir().await?;
7989            let test_path = tmp_dir.as_path();
7990            let src = test_path.join("src_dir");
7991            let dst = test_path.join("dst_dir");
7992            tokio::fs::create_dir(&src).await?;
7993            tokio::fs::write(src.join("file.txt"), "hello").await?;
7994            // create a unix socket inside the source directory
7995            let _listener = std::os::unix::net::UnixListener::bind(src.join("test.sock"))?;
7996            let summary = copy(
7997                &PROGRESS,
7998                &src,
7999                &dst,
8000                &Settings {
8001                    reflink: Default::default(),
8002                    local_copy_handoff: Default::default(),
8003                    dereference: false,
8004                    fail_early: false,
8005                    overwrite: false,
8006                    overwrite_compare: Default::default(),
8007                    overwrite_filter: None,
8008                    ignore_existing: false,
8009                    chunk_size: 0,
8010                    skip_specials: true,
8011                    remote_copy_buffer_size: 0,
8012                    filter: None,
8013                    dry_run: None,
8014                    delete: None,
8015                },
8016                &NO_PRESERVE_SETTINGS,
8017                false,
8018            )
8019            .await?;
8020            assert_eq!(summary.files_copied, 1);
8021            assert_eq!(summary.specials_skipped, 1);
8022            assert!(dst.join("file.txt").exists());
8023            assert!(!dst.join("test.sock").exists());
8024            Ok(())
8025        }
8026
8027        #[tokio::test]
8028        #[traced_test]
8029        async fn skip_specials_skips_fifo_in_directory() -> Result<(), anyhow::Error> {
8030            let tmp_dir = testutils::setup_test_dir().await?;
8031            let test_path = tmp_dir.as_path();
8032            let src = test_path.join("src_dir");
8033            let dst = test_path.join("dst_dir");
8034            tokio::fs::create_dir(&src).await?;
8035            tokio::fs::write(src.join("file.txt"), "hello").await?;
8036            // create a FIFO inside the source directory
8037            nix::unistd::mkfifo(
8038                &src.join("test.fifo"),
8039                nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
8040            )?;
8041            let summary = copy(
8042                &PROGRESS,
8043                &src,
8044                &dst,
8045                &Settings {
8046                    reflink: Default::default(),
8047                    local_copy_handoff: Default::default(),
8048                    dereference: false,
8049                    fail_early: false,
8050                    overwrite: false,
8051                    overwrite_compare: Default::default(),
8052                    overwrite_filter: None,
8053                    ignore_existing: false,
8054                    chunk_size: 0,
8055                    skip_specials: true,
8056                    remote_copy_buffer_size: 0,
8057                    filter: None,
8058                    dry_run: None,
8059                    delete: None,
8060                },
8061                &NO_PRESERVE_SETTINGS,
8062                false,
8063            )
8064            .await?;
8065            assert_eq!(summary.files_copied, 1);
8066            assert_eq!(summary.specials_skipped, 1);
8067            assert!(dst.join("file.txt").exists());
8068            assert!(!dst.join("test.fifo").exists());
8069            Ok(())
8070        }
8071
8072        #[tokio::test]
8073        #[traced_test]
8074        async fn special_file_errors_without_skip_specials() -> Result<(), anyhow::Error> {
8075            let tmp_dir = testutils::setup_test_dir().await?;
8076            let test_path = tmp_dir.as_path();
8077            let src = test_path.join("src_dir");
8078            let dst = test_path.join("dst_dir");
8079            tokio::fs::create_dir(&src).await?;
8080            tokio::fs::write(src.join("file.txt"), "hello").await?;
8081            let _listener = std::os::unix::net::UnixListener::bind(src.join("test.sock"))?;
8082            let result = copy(
8083                &PROGRESS,
8084                &src,
8085                &dst,
8086                &Settings {
8087                    reflink: Default::default(),
8088                    local_copy_handoff: Default::default(),
8089                    dereference: false,
8090                    fail_early: false,
8091                    overwrite: false,
8092                    overwrite_compare: Default::default(),
8093                    overwrite_filter: None,
8094                    ignore_existing: false,
8095                    chunk_size: 0,
8096                    skip_specials: false,
8097                    remote_copy_buffer_size: 0,
8098                    filter: None,
8099                    dry_run: None,
8100                    delete: None,
8101                },
8102                &NO_PRESERVE_SETTINGS,
8103                false,
8104            )
8105            .await;
8106            assert!(result.is_err());
8107            let err = result.unwrap_err();
8108            assert!(
8109                format!("{:#}", err).contains("unsupported src file type"),
8110                "error should mention unsupported file type, got: {:#}",
8111                err
8112            );
8113            Ok(())
8114        }
8115
8116        #[tokio::test]
8117        #[traced_test]
8118        async fn skip_specials_top_level_socket() -> Result<(), anyhow::Error> {
8119            let tmp_dir = testutils::setup_test_dir().await?;
8120            let test_path = tmp_dir.as_path();
8121            let src_socket = test_path.join("test.sock");
8122            let dst = test_path.join("dst.sock");
8123            let _listener = std::os::unix::net::UnixListener::bind(&src_socket)?;
8124            let summary = copy(
8125                &PROGRESS,
8126                &src_socket,
8127                &dst,
8128                &Settings {
8129                    reflink: Default::default(),
8130                    local_copy_handoff: Default::default(),
8131                    dereference: false,
8132                    fail_early: false,
8133                    overwrite: false,
8134                    overwrite_compare: Default::default(),
8135                    overwrite_filter: None,
8136                    ignore_existing: false,
8137                    chunk_size: 0,
8138                    skip_specials: true,
8139                    remote_copy_buffer_size: 0,
8140                    filter: None,
8141                    dry_run: None,
8142                    delete: None,
8143                },
8144                &NO_PRESERVE_SETTINGS,
8145                false,
8146            )
8147            .await?;
8148            assert_eq!(summary.specials_skipped, 1);
8149            assert_eq!(summary.files_copied, 0);
8150            assert!(!dst.exists());
8151            Ok(())
8152        }
8153    }
8154
8155    #[tokio::test]
8156    #[traced_test]
8157    async fn delete_protects_excluded_then_removes_with_delete_excluded()
8158    -> Result<(), anyhow::Error> {
8159        let tmp_dir = testutils::setup_test_dir().await?;
8160        let test_path = tmp_dir.as_path();
8161        let src = test_path.join("foo");
8162        let dst = test_path.join("bar");
8163        copy(
8164            &PROGRESS,
8165            &src,
8166            &dst,
8167            &settings_with_delete(None),
8168            &DO_PRESERVE_SETTINGS,
8169            false,
8170        )
8171        .await?;
8172        // a destination-only file that matches an exclude pattern
8173        tokio::fs::write(dst.join("keep.log"), b"protected").await?;
8174
8175        let mut filter = crate::filter::FilterSettings::new();
8176        filter.add_exclude("*.log")?;
8177
8178        // default --delete: keep.log is protected
8179        let mut settings = settings_with_delete(delete_on());
8180        settings.filter = Some(filter.clone());
8181        copy(
8182            &PROGRESS,
8183            &src,
8184            &dst,
8185            &settings,
8186            &DO_PRESERVE_SETTINGS,
8187            false,
8188        )
8189        .await?;
8190        assert!(
8191            dst.join("keep.log").exists(),
8192            "*.log must be protected by default"
8193        );
8194
8195        // --delete-excluded: keep.log is removed
8196        let mut settings = settings_with_delete(Some(DeleteSettings {
8197            delete_excluded: true,
8198        }));
8199        settings.filter = Some(filter);
8200        copy(
8201            &PROGRESS,
8202            &src,
8203            &dst,
8204            &settings,
8205            &DO_PRESERVE_SETTINGS,
8206            false,
8207        )
8208        .await?;
8209        assert!(!dst.join("keep.log").exists());
8210        Ok(())
8211    }
8212
8213    #[tokio::test]
8214    #[traced_test]
8215    async fn delete_dry_run_reports_without_removing() -> Result<(), anyhow::Error> {
8216        let tmp_dir = testutils::setup_test_dir().await?;
8217        let test_path = tmp_dir.as_path();
8218        let src = test_path.join("foo");
8219        let dst = test_path.join("bar");
8220        copy(
8221            &PROGRESS,
8222            &src,
8223            &dst,
8224            &settings_with_delete(None),
8225            &DO_PRESERVE_SETTINGS,
8226            false,
8227        )
8228        .await?;
8229        tokio::fs::write(dst.join("stale.txt"), b"junk").await?;
8230
8231        let mut settings = settings_with_delete(delete_on());
8232        settings.dry_run = Some(crate::config::DryRunMode::Brief);
8233        let summary = copy(
8234            &PROGRESS,
8235            &src,
8236            &dst,
8237            &settings,
8238            &DO_PRESERVE_SETTINGS,
8239            false,
8240        )
8241        .await?;
8242
8243        // the key invariant: dry-run must NOT remove anything
8244        assert!(
8245            dst.join("stale.txt").exists(),
8246            "dry-run must not remove anything"
8247        );
8248        // rm's dry-run does count would-be removals in files_removed
8249        assert_eq!(summary.rm_summary.files_removed, 1);
8250        Ok(())
8251    }
8252
8253    #[tokio::test]
8254    #[traced_test]
8255    async fn delete_dry_run_does_not_scan_through_named_destination_symlink()
8256    -> Result<(), anyhow::Error> {
8257        let root = testutils::create_temp_dir().await?;
8258        let src = root.join("src");
8259        let outside = root.join("outside");
8260        let dst = root.join("dst");
8261        tokio::fs::create_dir_all(src.join("sub")).await?;
8262        tokio::fs::create_dir_all(outside.join("sub")).await?;
8263        tokio::fs::write(outside.join("sub/stale"), "OUTSIDE").await?;
8264        tokio::fs::symlink(&outside, &dst).await?;
8265        let mut settings = settings_with_delete(delete_on());
8266        settings.dry_run = Some(crate::config::DryRunMode::Brief);
8267        let summary = copy(
8268            &PROGRESS,
8269            &src,
8270            &dst,
8271            &settings,
8272            &NO_PRESERVE_SETTINGS,
8273            false,
8274        )
8275        .await?;
8276        assert_eq!(summary.rm_summary.files_removed, 0);
8277        assert_eq!(
8278            tokio::fs::read_to_string(outside.join("sub/stale")).await?,
8279            "OUTSIDE"
8280        );
8281        Ok(())
8282    }
8283
8284    #[tokio::test]
8285    #[traced_test]
8286    async fn dereferenced_delete_dry_run_scans_its_destination_subtree() -> Result<(), anyhow::Error>
8287    {
8288        let root = testutils::create_temp_dir().await?;
8289        let src = root.join("src");
8290        let target = root.join("target");
8291        let dst = root.join("dst");
8292        tokio::fs::create_dir_all(&src).await?;
8293        tokio::fs::create_dir_all(&target).await?;
8294        tokio::fs::write(target.join("kept"), "SOURCE").await?;
8295        tokio::fs::symlink(&target, src.join("node")).await?;
8296        tokio::fs::create_dir_all(dst.join("node")).await?;
8297        tokio::fs::write(dst.join("node/stale"), "STALE").await?;
8298        let mut settings = settings_with_delete(delete_on());
8299        settings.dry_run = Some(crate::config::DryRunMode::Brief);
8300        settings.dereference = true;
8301
8302        let summary = copy(
8303            &PROGRESS,
8304            &src,
8305            &dst,
8306            &settings,
8307            &NO_PRESERVE_SETTINGS,
8308            false,
8309        )
8310        .await?;
8311
8312        assert_eq!(summary.rm_summary.files_removed, 1);
8313        assert_eq!(summary.rm_summary.directories_removed, 0);
8314        assert!(dst.join("node/stale").exists());
8315        Ok(())
8316    }
8317
8318    #[tokio::test]
8319    #[traced_test]
8320    async fn delete_does_not_prune_when_source_unreadable() -> Result<(), anyhow::Error> {
8321        let tmp_dir = testutils::setup_test_dir().await?;
8322        let test_path = tmp_dir.as_path();
8323        let src = test_path.join("foo");
8324        let dst = test_path.join("bar");
8325        copy(
8326            &PROGRESS,
8327            &src,
8328            &dst,
8329            &settings_with_delete(None),
8330            &DO_PRESERVE_SETTINGS,
8331            false,
8332        )
8333        .await?;
8334        tokio::fs::write(dst.join("stale.txt"), b"junk").await?;
8335        // make the source directory unreadable so enumeration fails
8336        let original = tokio::fs::metadata(&src).await?.permissions();
8337        tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).await?;
8338
8339        let result = copy(
8340            &PROGRESS,
8341            &src,
8342            &dst,
8343            &settings_with_delete(delete_on()),
8344            &DO_PRESERVE_SETTINGS,
8345            false,
8346        )
8347        .await;
8348
8349        // restore permissions before asserting (so the temp dir cleans up)
8350        tokio::fs::set_permissions(&src, original).await?;
8351
8352        assert!(result.is_err(), "unreadable source must error");
8353        assert!(
8354            dst.join("stale.txt").exists(),
8355            "destination must not be pruned when source enumeration fails"
8356        );
8357        Ok(())
8358    }
8359
8360    // overwriting an existing regular file goes through fd-relative removal: the destination file
8361    // is removed (counted as a single `files_removed`) and recreated with the source content. This
8362    // exercises `remove_existing`'s `unlink_at` branch through the fd-based copy walk.
8363    #[tokio::test]
8364    #[traced_test]
8365    async fn overwrite_regular_file_removes_and_recreates_via_fd() -> Result<(), anyhow::Error> {
8366        let tmp_dir = testutils::create_temp_dir().await?;
8367        let test_path = tmp_dir.as_path();
8368        let src_file = test_path.join("src.txt");
8369        let dst_file = test_path.join("dst.txt");
8370        // distinct sizes so the metadata comparison treats them as different and overwrite proceeds.
8371        tokio::fs::write(&src_file, "fresh source content").await?;
8372        tokio::fs::write(&dst_file, "old").await?;
8373        let summary = copy(
8374            &PROGRESS,
8375            &src_file,
8376            &dst_file,
8377            &Settings {
8378                reflink: Default::default(),
8379                local_copy_handoff: Default::default(),
8380                dereference: false,
8381                fail_early: false,
8382                overwrite: true, // <- exercises the overwrite removal path
8383                overwrite_compare: filecmp::MetadataCmpSettings {
8384                    size: true,
8385                    mtime: true,
8386                    ..Default::default()
8387                },
8388                overwrite_filter: None,
8389                ignore_existing: false,
8390                chunk_size: 0,
8391                skip_specials: false,
8392                remote_copy_buffer_size: 0,
8393                filter: None,
8394                dry_run: None,
8395                delete: None,
8396            },
8397            &NO_PRESERVE_SETTINGS,
8398            false,
8399        )
8400        .await?;
8401        // the existing regular file was removed (fd-relative unlink_at) and the source recreated.
8402        assert_eq!(summary.files_copied, 1);
8403        assert_eq!(summary.rm_summary.files_removed, 1);
8404        assert_eq!(summary.rm_summary.symlinks_removed, 0);
8405        assert_eq!(summary.rm_summary.directories_removed, 0);
8406        let content = tokio::fs::read_to_string(&dst_file).await?;
8407        assert_eq!(content, "fresh source content");
8408        Ok(())
8409    }
8410
8411    /// The admitted handle is the approved point-in-time metadata snapshot. A later same-type
8412    /// replacement does not force work when that snapshot already matches the destination.
8413    #[tokio::test]
8414    #[traced_test]
8415    async fn admitted_file_replacement_matching_destination_does_not_force_work()
8416    -> Result<(), anyhow::Error> {
8417        let root = testutils::create_temp_dir().await?;
8418        let src = root.join("source");
8419        let dst = root.join("destination");
8420        tokio::fs::write(&src, "SELECTED-A").await?;
8421        tokio::fs::hard_link(&src, &dst).await?;
8422
8423        let admission = testutils::AdmissionLimit::new().await;
8424        admission.set_files_in_flight(1);
8425        let src_parent = Arc::new(
8426            Dir::open_parent_dir(&root, congestion::Side::Source)
8427                .await?
8428                .into_tree(),
8429        );
8430        let dst_parent = Arc::new(
8431            Dir::open_parent_dir(&root, congestion::Side::Destination)
8432                .await?
8433                .into_tree(),
8434        );
8435        let selected = src_parent.child(std::ffi::OsStr::new("source")).await?;
8436        assert_eq!(selected.kind(), EntryKind::File);
8437        let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
8438        let entry = AdmittedEntry::new(selected, permit);
8439
8440        tokio::fs::remove_file(&src).await?;
8441        tokio::fs::write(&src, "CURRENT-BY-NAME-REPLACEMENT").await?;
8442        let mut settings = settings_with_delete(None);
8443        settings.overwrite = true;
8444        settings.overwrite_compare = filecmp::MetadataCmpSettings {
8445            size: true,
8446            ..Default::default()
8447        };
8448
8449        let summary = admission
8450            .run_with_timeout(
8451                std::time::Duration::from_secs(20),
8452                copy_child(
8453                    &PROGRESS,
8454                    &src_parent,
8455                    Some(&dst_parent),
8456                    std::ffi::OsStr::new("source"),
8457                    &src,
8458                    &dst,
8459                    std::path::Path::new(""),
8460                    &settings,
8461                    &NO_PRESERVE_SETTINGS,
8462                    false,
8463                    DestinationContext::new(&dst),
8464                    entry,
8465                ),
8466            )
8467            .await
8468            .context("admitted replacement copy did not finish at a limit of one")??;
8469        let returned = admission
8470            .run_with_timeout(
8471                std::time::Duration::from_secs(20),
8472                throttle::open_file_permit(),
8473            )
8474            .await
8475            .context("admitted replacement copy did not return open-file capacity")?;
8476        drop(returned);
8477
8478        assert_eq!(summary.files_unchanged, 1);
8479        assert_eq!(summary.files_copied, 0);
8480        assert_eq!(summary.rm_summary.files_removed, 0);
8481        assert_eq!(tokio::fs::read_to_string(&dst).await?, "SELECTED-A");
8482        Ok(())
8483    }
8484
8485    /// An action planned from the admitted snapshot must be reconsidered when the opened payload
8486    /// has another identity. The payload fd's paired metadata can turn that replace into a skip.
8487    #[tokio::test]
8488    #[traced_test]
8489    async fn actionable_admitted_file_replacement_replans_against_opened_payload()
8490    -> Result<(), anyhow::Error> {
8491        let root = testutils::create_temp_dir().await?;
8492        let src = root.join("source");
8493        let dst = root.join("destination");
8494        tokio::fs::write(&src, "SELECTED-A").await?;
8495        tokio::fs::write(&dst, "KEEP-ME").await?;
8496
8497        let admission = testutils::AdmissionLimit::new().await;
8498        admission.set_files_in_flight(1);
8499        let src_parent = Arc::new(
8500            Dir::open_parent_dir(&root, congestion::Side::Source)
8501                .await?
8502                .into_tree(),
8503        );
8504        let dst_parent = Arc::new(
8505            Dir::open_parent_dir(&root, congestion::Side::Destination)
8506                .await?
8507                .into_tree(),
8508        );
8509        let selected = src_parent.child(std::ffi::OsStr::new("source")).await?;
8510        assert_eq!(selected.kind(), EntryKind::File);
8511        let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
8512        let entry = AdmittedEntry::new(selected, permit);
8513
8514        tokio::fs::remove_file(&src).await?;
8515        tokio::fs::write(&src, "PAYLOAD").await?;
8516        let mut settings = settings_with_delete(None);
8517        settings.overwrite = true;
8518        settings.overwrite_compare = filecmp::MetadataCmpSettings {
8519            size: true,
8520            ..Default::default()
8521        };
8522
8523        let summary = admission
8524            .run_with_timeout(
8525                std::time::Duration::from_secs(20),
8526                copy_child(
8527                    &PROGRESS,
8528                    &src_parent,
8529                    Some(&dst_parent),
8530                    std::ffi::OsStr::new("source"),
8531                    &src,
8532                    &dst,
8533                    std::path::Path::new(""),
8534                    &settings,
8535                    &NO_PRESERVE_SETTINGS,
8536                    false,
8537                    DestinationContext::new(&dst),
8538                    entry,
8539                ),
8540            )
8541            .await
8542            .context("actionable admitted replacement did not finish at a limit of one")??;
8543        let returned = admission
8544            .run_with_timeout(
8545                std::time::Duration::from_secs(20),
8546                throttle::open_file_permit(),
8547            )
8548            .await
8549            .context("actionable admitted replacement did not return open-file capacity")?;
8550        drop(returned);
8551
8552        assert_eq!(summary.files_unchanged, 1);
8553        assert_eq!(summary.files_copied, 0);
8554        assert_eq!(summary.rm_summary.files_removed, 0);
8555        assert_eq!(tokio::fs::read_to_string(&dst).await?, "KEEP-ME");
8556        Ok(())
8557    }
8558
8559    // ── TOCTOU hardening: -L separability, swap-loop races, fd-budget ────────────────
8560
8561    /// An included dry-run regular file needs only metadata: even when its payload cannot be
8562    /// opened, the preview reports the copy and its snapshotted size without error.
8563    #[tokio::test]
8564    #[traced_test]
8565    async fn dry_run_previews_an_included_unreadable_regular_file() -> Result<(), anyhow::Error> {
8566        let root = testutils::create_temp_dir().await?;
8567        let src = root.join("source");
8568        let dst = root.join("destination");
8569        let contents = b"metadata is enough";
8570        tokio::fs::write(&src, contents).await?;
8571        tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).await?;
8572        let mut filter = crate::filter::FilterSettings::new();
8573        filter.add_include("source")?;
8574        let result = copy(
8575            &PROGRESS,
8576            &src,
8577            &dst,
8578            &Settings {
8579                filter: Some(filter),
8580                dry_run: Some(DryRunMode::Brief),
8581                ..settings_with_delete(None)
8582            },
8583            &NO_PRESERVE_SETTINGS,
8584            false,
8585        )
8586        .await;
8587        tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o600)).await?;
8588        let summary = result?;
8589        assert_eq!(summary.files_copied, 1);
8590        assert_eq!(summary.bytes_copied, contents.len() as u64);
8591        assert!(!dst.exists(), "dry-run must not create the destination");
8592        Ok(())
8593    }
8594
8595    /// An identical overwrite is a metadata-only no-op: an unreadable payload must not turn the
8596    /// skip into an error or disturb the destination.
8597    #[tokio::test]
8598    #[traced_test]
8599    async fn identical_overwrite_skips_an_unreadable_regular_file() -> Result<(), anyhow::Error> {
8600        let root = testutils::create_temp_dir().await?;
8601        let src = root.join("source");
8602        let dst = root.join("destination");
8603        tokio::fs::write(&src, "SRC-NEW").await?;
8604        tokio::fs::write(&dst, "KEEP-ME").await?;
8605        tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).await?;
8606        let result = copy(
8607            &PROGRESS,
8608            &src,
8609            &dst,
8610            &Settings {
8611                overwrite: true,
8612                overwrite_compare: filecmp::MetadataCmpSettings {
8613                    size: true,
8614                    ..Default::default()
8615                },
8616                ..settings_with_delete(None)
8617            },
8618            &NO_PRESERVE_SETTINGS,
8619            false,
8620        )
8621        .await;
8622        tokio::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o600)).await?;
8623        let summary = result?;
8624        assert_eq!(summary.files_unchanged, 1);
8625        assert_eq!(summary.files_copied, 0);
8626        assert_eq!(summary.rm_summary.files_removed, 0);
8627        assert_eq!(tokio::fs::read_to_string(&dst).await?, "KEEP-ME");
8628        Ok(())
8629    }
8630
8631    /// `--ignore-existing` is a destination-only no-op: an admitted source that disappears after
8632    /// selection must not turn the skip into a source-open error.
8633    #[tokio::test]
8634    #[traced_test]
8635    async fn ignore_existing_skips_before_reopening_an_admitted_missing_source()
8636    -> Result<(), anyhow::Error> {
8637        let root = testutils::create_temp_dir().await?;
8638        let src = root.join("source");
8639        let dst = root.join("destination");
8640        tokio::fs::write(&src, "SOURCE").await?;
8641        tokio::fs::write(&dst, "PRECIOUS").await?;
8642
8643        let admission = testutils::AdmissionLimit::new().await;
8644        admission.set_files_in_flight(1);
8645        let src_parent = Arc::new(
8646            Dir::open_parent_dir(&root, congestion::Side::Source)
8647                .await?
8648                .into_tree(),
8649        );
8650        let dst_parent = Arc::new(
8651            Dir::open_parent_dir(&root, congestion::Side::Destination)
8652                .await?
8653                .into_tree(),
8654        );
8655        let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
8656        let entry = crate::walk::classify_admitted_entry(
8657            &src_parent,
8658            std::ffi::OsStr::new("source"),
8659            permit,
8660        )
8661        .await?;
8662        tokio::fs::remove_file(&src).await?;
8663
8664        let summary = run_with_open_file_cleanup(
8665            &admission,
8666            copy_child(
8667                &PROGRESS,
8668                &src_parent,
8669                Some(&dst_parent),
8670                std::ffi::OsStr::new("source"),
8671                &src,
8672                &dst,
8673                std::path::Path::new(""),
8674                &Settings {
8675                    ignore_existing: true,
8676                    ..settings_with_delete(None)
8677                },
8678                &NO_PRESERVE_SETTINGS,
8679                false,
8680                DestinationContext::new(&dst),
8681                entry,
8682            ),
8683        )
8684        .await??;
8685
8686        assert_eq!(summary.files_unchanged, 1);
8687        assert_eq!(summary.files_copied, 0);
8688        assert_eq!(tokio::fs::read_to_string(&dst).await?, "PRECIOUS");
8689        Ok(())
8690    }
8691
8692    /// A destination conflict is diagnosed before reopening an admitted source that has vanished.
8693    #[tokio::test]
8694    #[traced_test]
8695    async fn no_overwrite_reports_destination_conflict_before_an_admitted_missing_source()
8696    -> Result<(), anyhow::Error> {
8697        let root = testutils::create_temp_dir().await?;
8698        let src = root.join("source");
8699        let dst = root.join("destination");
8700        tokio::fs::write(&src, "SOURCE").await?;
8701        tokio::fs::write(&dst, "PRECIOUS").await?;
8702
8703        let admission = testutils::AdmissionLimit::new().await;
8704        admission.set_files_in_flight(1);
8705        let src_parent = Arc::new(
8706            Dir::open_parent_dir(&root, congestion::Side::Source)
8707                .await?
8708                .into_tree(),
8709        );
8710        let dst_parent = Arc::new(
8711            Dir::open_parent_dir(&root, congestion::Side::Destination)
8712                .await?
8713                .into_tree(),
8714        );
8715        let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
8716        let entry = crate::walk::classify_admitted_entry(
8717            &src_parent,
8718            std::ffi::OsStr::new("source"),
8719            permit,
8720        )
8721        .await?;
8722        tokio::fs::remove_file(&src).await?;
8723
8724        let error = run_with_open_file_cleanup(
8725            &admission,
8726            copy_child(
8727                &PROGRESS,
8728                &src_parent,
8729                Some(&dst_parent),
8730                std::ffi::OsStr::new("source"),
8731                &src,
8732                &dst,
8733                std::path::Path::new(""),
8734                &settings_with_delete(None),
8735                &NO_PRESERVE_SETTINGS,
8736                false,
8737                DestinationContext::new(&dst),
8738                entry,
8739            ),
8740        )
8741        .await?
8742        .expect_err("an existing destination without --overwrite must fail");
8743
8744        let message = format!("{:#}", &error.source);
8745        assert!(
8746            message.contains("did you intend to specify --overwrite?"),
8747            "destination conflict lost precedence: {message}"
8748        );
8749        assert!(
8750            !message.contains("failed opening src file"),
8751            "source acquisition masked the destination conflict: {message}"
8752        );
8753        assert_eq!(tokio::fs::read_to_string(&dst).await?, "PRECIOUS");
8754        Ok(())
8755    }
8756
8757    /// Dry-run `--ignore-existing` also decides the no-op before reopening an admitted source.
8758    #[tokio::test]
8759    #[traced_test]
8760    async fn dry_run_ignore_existing_skips_before_reopening_an_admitted_missing_source()
8761    -> Result<(), anyhow::Error> {
8762        let root = testutils::create_temp_dir().await?;
8763        let src = root.join("source");
8764        let dst = root.join("destination");
8765        tokio::fs::write(&src, "SOURCE").await?;
8766        tokio::fs::write(&dst, "PRECIOUS").await?;
8767
8768        let admission = testutils::AdmissionLimit::new().await;
8769        admission.set_files_in_flight(1);
8770        let src_parent = Arc::new(
8771            Dir::open_parent_dir(&root, congestion::Side::Source)
8772                .await?
8773                .into_tree(),
8774        );
8775        let permit = crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
8776        let entry = crate::walk::classify_admitted_entry(
8777            &src_parent,
8778            std::ffi::OsStr::new("source"),
8779            permit,
8780        )
8781        .await?;
8782        tokio::fs::remove_file(&src).await?;
8783
8784        let summary = run_with_open_file_cleanup(
8785            &admission,
8786            copy_child(
8787                &PROGRESS,
8788                &src_parent,
8789                None,
8790                std::ffi::OsStr::new("source"),
8791                &src,
8792                &dst,
8793                std::path::Path::new(""),
8794                &Settings {
8795                    ignore_existing: true,
8796                    dry_run: Some(DryRunMode::Brief),
8797                    ..settings_with_delete(None)
8798                },
8799                &NO_PRESERVE_SETTINGS,
8800                false,
8801                DestinationContext::new(&dst),
8802                entry,
8803            ),
8804        )
8805        .await??;
8806
8807        assert_eq!(summary.files_unchanged, 1);
8808        assert_eq!(summary.files_copied, 0);
8809        assert_eq!(tokio::fs::read_to_string(&dst).await?, "PRECIOUS");
8810        Ok(())
8811    }
8812
8813    /// Default non-dereference copy settings used by the TOCTOU/fd-budget tests below.
8814    /// `overwrite` is on so a fresh destination per iteration is never required to be empty.
8815    fn toctou_settings() -> Settings {
8816        Settings {
8817            reflink: Default::default(),
8818            local_copy_handoff: Default::default(),
8819            dereference: false,
8820            fail_early: false,
8821            overwrite: true,
8822            overwrite_compare: filecmp::MetadataCmpSettings {
8823                size: true,
8824                mtime: true,
8825                ..Default::default()
8826            },
8827            overwrite_filter: None,
8828            ignore_existing: false,
8829            chunk_size: 0,
8830            skip_specials: false,
8831            remote_copy_buffer_size: 0,
8832            filter: None,
8833            dry_run: None,
8834            delete: None,
8835        }
8836    }
8837
8838    // Task 1.4: with `dereference == false`, a symlink in the source is copied as a symlink — the
8839    // non-dereference (fd-based) path is taken and `canonicalize` is never invoked. The
8840    // `debug_assert!(settings.dereference, ...)` guarding the canonicalize call is the actual
8841    // invariant guard (it would fire in debug/tests if a refactor reached it); this test exercises
8842    // that non-dereference symlink path end-to-end and proves the link is preserved as a link.
8843    #[tokio::test]
8844    #[traced_test]
8845    async fn non_dereference_copy_never_canonicalizes() -> Result<(), anyhow::Error> {
8846        let tmp_dir = testutils::create_temp_dir().await?;
8847        let test_path = tmp_dir.as_path();
8848        let src = test_path.join("src");
8849        let dst = test_path.join("dst");
8850        tokio::fs::create_dir(&src).await?;
8851        // a real file plus a symlink to it living inside the source tree.
8852        tokio::fs::write(src.join("real.txt"), "REAL_CONTENT").await?;
8853        tokio::fs::symlink("real.txt", src.join("link")).await?;
8854        let summary = copy(
8855            &PROGRESS,
8856            &src,
8857            &dst,
8858            &toctou_settings(),
8859            &NO_PRESERVE_SETTINGS,
8860            false,
8861        )
8862        .await?;
8863        assert_eq!(summary.files_copied, 1);
8864        assert_eq!(
8865            summary.symlinks_created, 1,
8866            "symlink must be copied as a symlink"
8867        );
8868        // the destination entry must itself be a symlink (non-deref path), not a dereferenced file.
8869        let link_md = tokio::fs::symlink_metadata(dst.join("link")).await?;
8870        assert!(
8871            link_md.file_type().is_symlink(),
8872            "with dereference == false the source symlink must remain a symlink in the destination"
8873        );
8874        // and its target text is preserved verbatim (it was never resolved/canonicalized).
8875        let target = tokio::fs::read_link(dst.join("link")).await?;
8876        assert_eq!(target, std::path::Path::new("real.txt"));
8877        Ok(())
8878    }
8879
8880    #[tokio::test]
8881    async fn non_dereference_copy_preserves_outside_sentinel_symlink() -> anyhow::Result<()> {
8882        let tmp = testutils::create_temp_dir().await?;
8883        let sentinel = tmp.join("sentinel_secret");
8884        tokio::fs::write(&sentinel, "SENTINEL_SECRET_CONTENT").await?;
8885        let src = tmp.join("src");
8886        let dst = tmp.join("dst");
8887        tokio::fs::create_dir(&src).await?;
8888        tokio::fs::symlink(&sentinel, src.join("entry")).await?;
8889        let summary = copy(
8890            &PROGRESS,
8891            &src,
8892            &dst,
8893            &toctou_settings(),
8894            &NO_PRESERVE_SETTINGS,
8895            false,
8896        )
8897        .await?;
8898        let entry = dst.join("entry");
8899        assert!(tokio::fs::symlink_metadata(&entry).await?.is_symlink());
8900        assert_eq!(tokio::fs::read_link(&entry).await?, sentinel);
8901        assert_eq!(summary.files_copied, 0);
8902        assert_eq!(summary.bytes_copied, 0);
8903        assert_eq!(summary.symlinks_created, 1);
8904        Ok(())
8905    }
8906
8907    #[tokio::test]
8908    async fn admitted_regular_source_replaced_by_symlink_fails_before_copy() -> anyhow::Result<()> {
8909        let root = testutils::create_temp_dir().await?;
8910        let src = root.join("source");
8911        let dst = root.join("destination");
8912        let sentinel = root.join("sentinel");
8913        tokio::fs::write(&src, "REAL_CONTENT").await?;
8914        tokio::fs::write(&sentinel, "SENTINEL_SECRET_CONTENT").await?;
8915        let admission = testutils::AdmissionLimit::new().await;
8916        admission.set_files_in_flight(1);
8917        let src_parent = Arc::new(
8918            Dir::open_parent_dir(&root, congestion::Side::Source)
8919                .await?
8920                .into_tree(),
8921        );
8922        let dst_parent = Arc::new(
8923            Dir::open_parent_dir(&root, congestion::Side::Destination)
8924                .await?
8925                .into_tree(),
8926        );
8927        let entry = crate::walk::classify_admitted_entry(
8928            &src_parent,
8929            std::ffi::OsStr::new("source"),
8930            crate::walk::ensure_leaf_permit(PermitKind::OpenFile, None).await,
8931        )
8932        .await?;
8933        // force the classification/open race rather than relying on swapper scheduling
8934        tokio::fs::remove_file(&src).await?;
8935        tokio::fs::symlink(&sentinel, &src).await?;
8936        let error = run_with_open_file_cleanup(
8937            &admission,
8938            copy_child(
8939                &PROGRESS,
8940                &src_parent,
8941                Some(&dst_parent),
8942                std::ffi::OsStr::new("source"),
8943                &src,
8944                &dst,
8945                std::path::Path::new(""),
8946                &toctou_settings(),
8947                &NO_PRESERVE_SETTINGS,
8948                false,
8949                DestinationContext::new(&dst),
8950                entry,
8951            ),
8952        )
8953        .await?
8954        .expect_err("the admitted regular-file open must reject a symlink");
8955        assert_eq!(
8956            error
8957                .source
8958                .root_cause()
8959                .downcast_ref::<std::io::Error>()
8960                .and_then(std::io::Error::raw_os_error),
8961            Some(libc::ELOOP),
8962            "the failure must come from the nofollow source open"
8963        );
8964        assert!(!dst.exists(), "no destination payload may be created");
8965        assert_eq!(
8966            tokio::fs::read_to_string(&sentinel).await?,
8967            "SENTINEL_SECRET_CONTENT"
8968        );
8969        Ok(())
8970    }
8971
8972    // Task 1.5 helper: repeatedly swap `path` between a real regular file (content `REAL_CONTENT`)
8973    // and a symlink pointing at `sentinel`, using rename so each individual state is atomic. Two
8974    // staging names (a prepared symlink and the real file) live alongside `path` and are renamed
8975    // over it in a tight loop until `stop` is set. Runs on a dedicated OS thread (std::thread), so
8976    // it makes progress regardless of the tokio runtime's scheduling.
8977    fn spawn_file_symlink_swapper(
8978        dir: std::path::PathBuf,
8979        entry_name: &'static str,
8980        sentinel: std::path::PathBuf,
8981    ) -> crate::testutils::SwapperGuard {
8982        crate::testutils::SwapperGuard::spawn(move |stop| {
8983            let entry = dir.join(entry_name);
8984            let staged_real = dir.join("__staged_real");
8985            let staged_link = dir.join("__staged_link");
8986            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
8987                // prepare the real file at a staging name, then rename it over `entry`.
8988                let _ = std::fs::remove_file(&staged_real);
8989                if std::fs::write(&staged_real, b"REAL_CONTENT").is_err() {
8990                    continue;
8991                }
8992                let _ = std::fs::rename(&staged_real, &entry);
8993                // prepare a symlink-to-sentinel at the other staging name, then rename it over.
8994                let _ = std::fs::remove_file(&staged_link);
8995                let _ = std::os::unix::fs::symlink(&sentinel, &staged_link);
8996                let _ = std::fs::rename(&staged_link, &entry);
8997            }
8998        })
8999    }
9000
9001    // Task 1.5 (a): final-component file<->symlink swap. While the copy runs, `src/sub/entry` is
9002    // rapidly flipped between a real regular file and a symlink to a sentinel outside the tree. The
9003    // copy may grab the real file, preserve the symlink itself, or catch a swap (error or skip),
9004    // but the sentinel's secret content must NEVER end up in the destination as data.
9005    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9006    async fn file_symlink_swap_never_leaks_sentinel() -> Result<(), anyhow::Error> {
9007        let tmp_dir = testutils::create_temp_dir().await?;
9008        let test_path = tmp_dir.as_path();
9009        // sentinel lives OUTSIDE the source tree with distinctive content.
9010        let sentinel = test_path.join("sentinel_secret");
9011        tokio::fs::write(&sentinel, "SENTINEL_SECRET_CONTENT").await?;
9012        let src = test_path.join("src");
9013        let sub = src.join("sub");
9014        tokio::fs::create_dir(&src).await?;
9015        tokio::fs::create_dir(&sub).await?;
9016        tokio::fs::write(sub.join("entry"), "REAL_CONTENT").await?;
9017
9018        let mut swapper = None;
9019
9020        let settings = toctou_settings();
9021        let mut caught_swaps = 0usize;
9022        let mut copied_real = 0usize;
9023        let mut copied_symlinks = 0usize;
9024        for i in 0..200 {
9025            // establish a real-file control before the 199 concurrent swap attempts
9026            // the deterministic admitted-source test exercises the exact unsafe boundary
9027            if i == 1 {
9028                swapper = Some(spawn_file_symlink_swapper(
9029                    sub.clone(),
9030                    "entry",
9031                    sentinel.clone(),
9032                ));
9033            }
9034            let dst = test_path.join(format!("dst_{i}"));
9035            let result = tokio::time::timeout(
9036                std::time::Duration::from_secs(30),
9037                copy(
9038                    &PROGRESS,
9039                    &src,
9040                    &dst,
9041                    &settings,
9042                    &NO_PRESERVE_SETTINGS,
9043                    false,
9044                ),
9045            )
9046            .await
9047            .expect("copy must not hang under concurrent swapping");
9048            if i == 0 {
9049                result
9050                    .as_ref()
9051                    .expect("the stable regular-file control must succeed");
9052                assert_eq!(
9053                    tokio::fs::read(dst.join("sub/entry")).await?,
9054                    b"REAL_CONTENT"
9055                );
9056            }
9057            match result {
9058                Ok(_) => {}
9059                Err(_) => caught_swaps += 1, // a swap was caught mid-copy (failed closed)
9060            }
9061            // CORE ASSERTION: if a regular file landed at the destination, it is the real content —
9062            // never the sentinel's secret. The entry may instead be absent or a symlink.
9063            let entry_dst = dst.join("sub").join("entry");
9064            if let Ok(md) = tokio::fs::symlink_metadata(&entry_dst).await {
9065                if md.file_type().is_file() {
9066                    let content = tokio::fs::read_to_string(&entry_dst).await?;
9067                    assert_ne!(
9068                        content, "SENTINEL_SECRET_CONTENT",
9069                        "iteration {i}: sentinel content leaked into the destination as a regular file"
9070                    );
9071                    assert_eq!(
9072                        content, "REAL_CONTENT",
9073                        "iteration {i}: a regular destination file must hold the real content"
9074                    );
9075                    copied_real += 1;
9076                } else if md.file_type().is_symlink() {
9077                    assert_eq!(
9078                        tokio::fs::read_link(&entry_dst).await?,
9079                        sentinel,
9080                        "iteration {i}: a destination symlink must preserve the literal target"
9081                    );
9082                    copied_symlinks += 1;
9083                }
9084            }
9085            let _ = tokio::fs::remove_dir_all(&dst).await;
9086        }
9087
9088        drop(swapper);
9089        // concurrent outcomes are diagnostic; the separate admitted-source test proves the boundary
9090        tracing::info!(
9091            "file/symlink swap: caught_swaps={caught_swaps}, copied_real={copied_real}, \
9092             copied_symlinks={copied_symlinks}"
9093        );
9094        Ok(())
9095    }
9096
9097    // Task 1.5 (b): intermediate-directory swap. While the copy runs, `src/sub` is flipped between a
9098    // real directory (containing a real file) and a symlink to a directory outside the tree holding
9099    // a sentinel. open_dir uses O_NOFOLLOW, so the walk either descends the real directory or fails
9100    // closed — it must never follow the symlink and copy the outside sentinel.
9101    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9102    async fn intermediate_dir_swap_never_follows_symlink() -> Result<(), anyhow::Error> {
9103        let tmp_dir = testutils::create_temp_dir().await?;
9104        let test_path = tmp_dir.as_path();
9105        // an "outside" directory tree holding a sentinel file, reachable only via a symlink.
9106        let outside = test_path.join("outside_dir");
9107        tokio::fs::create_dir(&outside).await?;
9108        tokio::fs::write(outside.join("sentinel.txt"), "SENTINEL_SECRET_CONTENT").await?;
9109        let src = test_path.join("src");
9110        tokio::fs::create_dir(&src).await?;
9111        // the real `sub` directory with a real file inside.
9112        let real_sub = src.join("sub");
9113        tokio::fs::create_dir(&real_sub).await?;
9114        tokio::fs::write(real_sub.join("real.txt"), "REAL_CONTENT").await?;
9115
9116        let swapper = {
9117            let src = src.clone();
9118            let outside = outside.clone();
9119            crate::testutils::SwapperGuard::spawn(move |stop| {
9120                let sub = src.join("sub");
9121                let staged_dir = src.join("__staged_sub_dir");
9122                let staged_link = src.join("__staged_sub_link");
9123                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
9124                    // stage a real directory (with the real file) then rename it over `sub`.
9125                    let _ = std::fs::remove_dir_all(&staged_dir);
9126                    if std::fs::create_dir(&staged_dir).is_ok() {
9127                        let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL_CONTENT");
9128                        // RENAME_EXCHANGE isn't available portably here; remove-then-rename. The
9129                        // window where `sub` is briefly absent is fine — the copy may error, which
9130                        // is an accepted failed-closed outcome.
9131                        let _ = std::fs::remove_dir_all(&sub);
9132                        let _ = std::fs::remove_file(&sub);
9133                        let _ = std::fs::rename(&staged_dir, &sub);
9134                    }
9135                    // stage a symlink to the outside dir, then swap it in over `sub`.
9136                    let _ = std::fs::remove_file(&staged_link);
9137                    if std::os::unix::fs::symlink(&outside, &staged_link).is_ok() {
9138                        let _ = std::fs::remove_dir_all(&sub);
9139                        let _ = std::fs::remove_file(&sub);
9140                        let _ = std::fs::rename(&staged_link, &sub);
9141                    }
9142                }
9143            })
9144        };
9145
9146        let settings = toctou_settings();
9147        for i in 0..200 {
9148            let dst = test_path.join(format!("dst_{i}"));
9149            let _ = tokio::time::timeout(
9150                std::time::Duration::from_secs(30),
9151                copy(
9152                    &PROGRESS,
9153                    &src,
9154                    &dst,
9155                    &settings,
9156                    &NO_PRESERVE_SETTINGS,
9157                    false,
9158                ),
9159            )
9160            .await
9161            .expect("copy must not hang under concurrent dir swapping");
9162            // CORE ASSERTION: the walk must never DESCEND through the symlink and copy the outside
9163            // tree's contents as data. Classify `dst/sub` WITHOUT following symlinks: if it is a
9164            // symlink, the link was copied verbatim (safe — `outside` was never read); if it is a
9165            // real directory, the copy descended a real `sub`, and the sentinel — which only ever
9166            // lived in `outside`, reachable solely via the symlink — must NOT have been reproduced
9167            // inside it. (`Path::exists` follows symlinks, so it would falsely "see" the sentinel
9168            // through a verbatim-copied symlink; `symlink_metadata` is the correct probe here.)
9169            // when `dst/sub` is a symlink it was copied verbatim (accepted failed-closed outcome,
9170            // `outside` was never read); only a REAL destination directory means the walk descended,
9171            // and then it must have descended the real `sub` — never the symlink into `outside`.
9172            let sub_dst = dst.join("sub");
9173            if let Ok(sub_md) = tokio::fs::symlink_metadata(&sub_dst).await
9174                && sub_md.file_type().is_dir()
9175            {
9176                let leaked = sub_dst.join("sentinel.txt");
9177                let leaked_is_real_file = tokio::fs::symlink_metadata(&leaked)
9178                    .await
9179                    .map(|m| m.file_type().is_file())
9180                    .unwrap_or(false);
9181                assert!(
9182                    !leaked_is_real_file,
9183                    "iteration {i}: intermediate-dir symlink was followed; the outside \
9184                     sentinel was copied into a real destination directory"
9185                );
9186                // a real `sub` directory copied from the real source holds the real file.
9187                let real_dst = sub_dst.join("real.txt");
9188                if let Ok(content) = tokio::fs::read_to_string(&real_dst).await {
9189                    assert_eq!(
9190                        content, "REAL_CONTENT",
9191                        "iteration {i}: copied file must hold real content"
9192                    );
9193                }
9194            }
9195            let _ = tokio::fs::remove_dir_all(&dst).await;
9196        }
9197
9198        drop(swapper);
9199        Ok(())
9200    }
9201
9202    // Task 1.5 (d): destination NON-EMPTY-directory overwrite removal under an intermediate-component
9203    // swap — the racy mirror of `test_remote_dest_overwrite_replaces_intermediate_symlink_in_tree`,
9204    // targeting the removal path B1 hardened. The source has regular files at `src/mid/deeper/subK`,
9205    // while the destination has NON-EMPTY directories at `dst/mid/deeper/subK`. A `--overwrite` copy
9206    // must therefore REMOVE those non-empty directories (`remove_existing` → ENOTEMPTY →
9207    // `rm::rm_child`) before creating the files. Concurrently, a swapper flips the INTERMEDIATE
9208    // component `dst/mid` between a real directory (holding `deeper/subK`) and a symlink to an
9209    // out-of-tree directory mirroring `deeper/subK/`, whose `subK/` each hold a sentinel.
9210    //
9211    // This is a fail-closed STRESS test: under the fd code the copy either descends a real `dst/mid`
9212    // and removes through the pinned `deeper` fd, or fails closed at the intermediate `make_dir`
9213    // O_NOFOLLOW when it observes the symlink — never escaping. CORE ASSERTION: no out-of-tree
9214    // sentinel is ever deleted, and the copy never hangs. (Because the walk fails closed at the
9215    // intermediate `make_dir` whenever it sees the symlink, this racy form rarely even reaches the
9216    // removal branch and does NOT reliably reproduce the path-based escape; the deterministic
9217    // `nonempty_dir_overwrite_removal_uses_pinned_fd_not_path` below is the regression-catcher that
9218    // FAILS when the branch is reverted to `rm::rm`.)
9219    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9220    async fn dest_nonempty_dir_overwrite_removal_contained_under_intermediate_swap()
9221    -> Result<(), anyhow::Error> {
9222        const N: usize = 8;
9223        let tmp_dir = testutils::create_temp_dir().await?;
9224        let test_path = tmp_dir.as_path();
9225        // an out-of-tree tree mirroring `deeper/`, holding several non-empty `subK/` each guarding a
9226        // sentinel. A path-based rm(dst/mid/deeper/subK) through a `mid`->out_of_tree symlink would
9227        // delete out_of_tree/deeper/subK. Several targets widen the window: once `mid` flips
9228        // to a symlink mid-copy (after `deeper` was opened), every remaining path-based rm escapes.
9229        let out_of_tree = test_path.join("out_of_tree");
9230        let oot_deeper = out_of_tree.join("deeper");
9231        for k in 0..N {
9232            let oot_sub = oot_deeper.join(format!("sub{k}"));
9233            tokio::fs::create_dir_all(&oot_sub).await?;
9234            tokio::fs::write(oot_sub.join("sentinel.txt"), "SENTINEL").await?;
9235        }
9236
9237        // source: src/mid/deeper/subK are regular FILES (so the copy must replace the dst dirs).
9238        let src = test_path.join("src");
9239        let src_deeper = src.join("mid").join("deeper");
9240        tokio::fs::create_dir_all(&src_deeper).await?;
9241        for k in 0..N {
9242            tokio::fs::write(src_deeper.join(format!("sub{k}")), "REAL_FILE_CONTENT").await?;
9243        }
9244
9245        // destination root persists; the swapper owns the intermediate `dst/mid`.
9246        let dst = test_path.join("dst");
9247        tokio::fs::create_dir(&dst).await?;
9248
9249        let swapper = {
9250            let dst = dst.clone();
9251            let out_of_tree = out_of_tree.clone();
9252            crate::testutils::SwapperGuard::spawn(move |stop| {
9253                let mid = dst.join("mid");
9254                let staged_dir = dst.join("__staged_mid_dir");
9255                let staged_link = dst.join("__staged_mid_link");
9256                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
9257                    // stage a real `mid` directory holding `deeper/subK` as NON-EMPTY directories,
9258                    // then rename it over `mid`. This is the state in which the overwrite-removal
9259                    // branch fires (src has FILES at mid/deeper/subK, dst has non-empty dirs).
9260                    let _ = std::fs::remove_dir_all(&staged_dir);
9261                    let staged_deeper = staged_dir.join("deeper");
9262                    if std::fs::create_dir_all(&staged_deeper).is_ok() {
9263                        for k in 0..N {
9264                            let s = staged_deeper.join(format!("sub{k}"));
9265                            if std::fs::create_dir(&s).is_ok() {
9266                                let _ = std::fs::write(s.join("inner.txt"), b"INNER_CONTENT");
9267                            }
9268                        }
9269                        let _ = std::fs::remove_dir_all(&mid);
9270                        let _ = std::fs::remove_file(&mid);
9271                        let _ = std::fs::rename(&staged_dir, &mid);
9272                    }
9273                    // stage a symlink to the out-of-tree directory, then swap it in over `mid`.
9274                    let _ = std::fs::remove_file(&staged_link);
9275                    if std::os::unix::fs::symlink(&out_of_tree, &staged_link).is_ok() {
9276                        let _ = std::fs::remove_dir_all(&mid);
9277                        let _ = std::fs::remove_file(&mid);
9278                        let _ = std::fs::rename(&staged_link, &mid);
9279                    }
9280                }
9281            })
9282        };
9283
9284        let settings = toctou_settings();
9285        for i in 0..200 {
9286            let _ = tokio::time::timeout(
9287                std::time::Duration::from_secs(30),
9288                copy(
9289                    &PROGRESS,
9290                    &src,
9291                    &dst,
9292                    &settings,
9293                    &NO_PRESERVE_SETTINGS,
9294                    false,
9295                ),
9296            )
9297            .await
9298            .expect("copy must not hang under concurrent intermediate-component swapping");
9299            // CORE ASSERTION (every iteration, regardless of timing): no out-of-tree sentinel is
9300            // ever deleted. The fd-relative removal is contained to the pinned `dst/mid/deeper` fd
9301            // and its O_NOFOLLOW descent fails closed on a swapped-in symlink — it can never
9302            // re-resolve `dst/mid/deeper/subK` through a `mid`->out_of_tree symlink and delete
9303            // `out_of_tree/deeper/subK`.
9304            for k in 0..N {
9305                assert!(
9306                    oot_deeper
9307                        .join(format!("sub{k}"))
9308                        .join("sentinel.txt")
9309                        .exists(),
9310                    "iteration {i}: out-of-tree sentinel sub{k} was deleted — the non-empty-\
9311                     directory overwrite removal escaped the destination tree through a swapped \
9312                     intermediate symlink (path-based rm regression)"
9313                );
9314            }
9315        }
9316
9317        drop(swapper);
9318        // sanity: the out-of-tree subtree itself also survived intact.
9319        assert!(
9320            oot_deeper.join("sub0").is_dir(),
9321            "out-of-tree sub directory must survive"
9322        );
9323        Ok(())
9324    }
9325
9326    // deterministic companion to the racy test above: non-empty-directory overwrite removal acts
9327    // through the pinned parent fd, never by re-resolving the display path. We open the real parent
9328    // directory as `dst_parent`, classify its non-empty child, but pass a `dst_path` whose
9329    // intermediate component is an out-of-tree symlink. The fd-relative `rm_child` removes the real
9330    // child through the held fd and leaves the out-of-tree tree untouched; a path-based
9331    // `rm::rm(dst_path)` would follow the display path and delete the out-of-tree subtree.
9332    #[tokio::test]
9333    #[traced_test]
9334    async fn nonempty_dir_overwrite_removal_uses_pinned_fd_not_path() -> Result<(), anyhow::Error> {
9335        let tmp_dir = testutils::create_temp_dir().await?;
9336        let test_path = tmp_dir.as_path();
9337
9338        // the REAL destination tree: base/realdeeper/victim is a NON-EMPTY directory.
9339        let real_deeper = test_path.join("base").join("realdeeper");
9340        let real_victim = real_deeper.join("victim");
9341        tokio::fs::create_dir_all(&real_victim).await?;
9342        tokio::fs::write(real_victim.join("inner.txt"), "INNER").await?;
9343
9344        // an out-of-tree tree the stale display path would resolve into. Its `victim/` holds a
9345        // sentinel; a path-based rm of the redirected path would delete it.
9346        let out_of_tree = test_path.join("out_of_tree");
9347        let oot_victim = out_of_tree.join("realdeeper").join("victim");
9348        tokio::fs::create_dir_all(&oot_victim).await?;
9349        tokio::fs::write(oot_victim.join("sentinel.txt"), "SENTINEL").await?;
9350
9351        // the redirected display path: base/mid -> out_of_tree, so `mid/realdeeper/victim`
9352        // resolves to out_of_tree/realdeeper/victim by PATH, but the pinned fd points at the real
9353        // base/realdeeper.
9354        let mid_link = test_path.join("base").join("mid");
9355        tokio::fs::symlink(&out_of_tree, &mid_link).await?;
9356        let stale_dst_path = mid_link.join("realdeeper").join("victim");
9357
9358        // open the REAL parent fd and classify the real non-empty child through it.
9359        let dst_parent =
9360            Arc::new(Dir::open_root_dir(&real_deeper, false, congestion::Side::Destination).await?);
9361        let victim_name: &OsStr = OsStr::new("victim");
9362        let dst_handle = dst_parent.child(victim_name).await?;
9363        assert_eq!(dst_handle.kind(), EntryKind::Dir);
9364
9365        let settings = toctou_settings();
9366        let summary = remove_existing(
9367            &PROGRESS,
9368            &dst_parent,
9369            victim_name,
9370            &stale_dst_path,
9371            dst_handle.into_removal_snapshot(),
9372            &settings,
9373        )
9374        .await?;
9375        assert_eq!(
9376            summary.directories_removed, 1,
9377            "the real non-empty victim directory should have been removed via the pinned fd"
9378        );
9379
9380        // the real child was removed through the held fd...
9381        assert!(
9382            !real_victim.exists(),
9383            "the real non-empty victim should have been removed through the pinned parent fd"
9384        );
9385        // ...and the out-of-tree subtree (which the stale path resolves into) was NOT touched.
9386        assert!(
9387            oot_victim.join("sentinel.txt").exists(),
9388            "out-of-tree sentinel was deleted — removal re-resolved the display path through the \
9389             intermediate symlink instead of using the pinned fd (path-based rm regression)"
9390        );
9391        Ok(())
9392    }
9393
9394    // regression: `is_fresh` is an optimization hint ("we just created the parent directory, so it
9395    // must be empty"), not an enforceable invariant. a concurrent writer can populate a directory we
9396    // believe we just created: another source operand of the SAME invocation whose destination
9397    // aliases ours (`rcp A/x B/x dst/` maps both operands to `dst/x` and dispatches them
9398    // concurrently), a second `rcp` process, or a destination filesystem that folds two source names
9399    // onto one. passing `is_fresh = true` below while `dst`/`dst/sub` already exist reproduces that
9400    // race deterministically, without needing actual concurrency.
9401    #[tokio::test]
9402    async fn copies_into_a_fresh_marked_destination_another_writer_populated()
9403    -> Result<(), anyhow::Error> {
9404        let tmp = testutils::create_temp_dir().await?;
9405        let src = tmp.join("src");
9406        tokio::fs::create_dir(&src).await?;
9407        tokio::fs::create_dir(src.join("sub")).await?;
9408        tokio::fs::write(src.join("sub").join("a.txt"), "a").await?;
9409        // dst and dst/sub already exist (someone got there first).
9410        let dst = tmp.join("dst");
9411        tokio::fs::create_dir(&dst).await?;
9412        tokio::fs::create_dir(dst.join("sub")).await?;
9413        let summary = copy(
9414            &PROGRESS,
9415            &src,
9416            &dst,
9417            &settings_with_delete(None),
9418            &NO_PRESERVE_SETTINGS,
9419            true, // caller believes it is fresh
9420        )
9421        .await?;
9422        assert_eq!(summary.directories_created, 0);
9423        assert_eq!(summary.directories_unchanged, 2);
9424        assert_eq!(summary.files_copied, 1);
9425        assert_eq!(
9426            tokio::fs::read_to_string(dst.join("sub").join("a.txt")).await?,
9427            "a"
9428        );
9429        Ok(())
9430    }
9431
9432    // a reused directory's children must receive `is_fresh: false` rather than inheriting the
9433    // caller's stale belief. This becomes observable when a child leaf already conflicts with the
9434    // source: with `dst/sub/a.txt` pre-existing here, a leaked `is_fresh == true` would skip the
9435    // conflict-check/overwrite block in `copy_file_fd` and fail on `create_file`'s `O_EXCL` instead
9436    // of overwriting.
9437    #[tokio::test]
9438    async fn stale_fresh_hint_overwrites_preexisting_file() -> Result<(), anyhow::Error> {
9439        let tmp = testutils::create_temp_dir().await?;
9440        let src = tmp.join("src");
9441        tokio::fs::create_dir(&src).await?;
9442        tokio::fs::create_dir(src.join("sub")).await?;
9443        tokio::fs::write(src.join("sub").join("a.txt"), "new").await?;
9444        let dst = tmp.join("dst");
9445        tokio::fs::create_dir(&dst).await?;
9446        tokio::fs::create_dir(dst.join("sub")).await?;
9447        tokio::fs::write(dst.join("sub").join("a.txt"), "old-content-differs").await?;
9448        let summary = copy(
9449            &PROGRESS,
9450            &src,
9451            &dst,
9452            &settings_with_delete(delete_on()), // --delete implies --overwrite
9453            &NO_PRESERVE_SETTINGS,
9454            true, // caller believes it is fresh, but another writer got here first
9455        )
9456        .await?;
9457        assert_eq!(summary.files_copied, 1);
9458        assert_eq!(
9459            tokio::fs::read_to_string(dst.join("sub").join("a.txt")).await?,
9460            "new"
9461        );
9462        Ok(())
9463    }
9464
9465    // the tests below cover the FILE sibling of the stale-hint problem: the caller passes
9466    // `is_fresh = true` (the parent directory was just created, so it is presumed empty) while the
9467    // destination file already exists, because another writer got there first. a file operand is the
9468    // most direct way to reach `copy_file_fd` with `is_fresh == true` — it is also a real production
9469    // shape, since `rlink` delegates a single file to `copy_child` with the freshness of the
9470    // directory it just created. every conflict decision (`--overwrite`, `--ignore-existing`, an
9471    // identical file under `--overwrite-compare`, and the no-`--overwrite` error) must be reached
9472    // from here, not just from the `!is_fresh` route.
9473
9474    #[tokio::test]
9475    async fn overwrites_a_pre_existing_file_in_a_fresh_marked_destination()
9476    -> Result<(), anyhow::Error> {
9477        let tmp = testutils::create_temp_dir().await?;
9478        let src_file = tmp.join("src.txt");
9479        let dst_file = tmp.join("dst.txt");
9480        // distinct sizes so the metadata comparison treats them as different and overwrite proceeds.
9481        tokio::fs::write(&src_file, "fresh source content").await?;
9482        tokio::fs::write(&dst_file, "old").await?;
9483        let summary = copy(
9484            &PROGRESS,
9485            &src_file,
9486            &dst_file,
9487            &Settings {
9488                overwrite: true,
9489                ..settings_with_delete(None)
9490            },
9491            &NO_PRESERVE_SETTINGS,
9492            true, // caller believes it is fresh, but another writer got here first
9493        )
9494        .await?;
9495        assert_eq!(summary.files_copied, 1);
9496        assert_eq!(summary.rm_summary.files_removed, 1);
9497        assert_eq!(
9498            tokio::fs::read_to_string(&dst_file).await?,
9499            "fresh source content"
9500        );
9501        Ok(())
9502    }
9503
9504    #[tokio::test]
9505    async fn ignores_a_pre_existing_file_in_a_fresh_marked_destination() -> Result<(), anyhow::Error>
9506    {
9507        let tmp = testutils::create_temp_dir().await?;
9508        let src_file = tmp.join("src.txt");
9509        let dst_file = tmp.join("dst.txt");
9510        tokio::fs::write(&src_file, "fresh source content").await?;
9511        tokio::fs::write(&dst_file, "old").await?;
9512        let summary = copy(
9513            &PROGRESS,
9514            &src_file,
9515            &dst_file,
9516            &Settings {
9517                ignore_existing: true,
9518                ..settings_with_delete(None)
9519            },
9520            &NO_PRESERVE_SETTINGS,
9521            true,
9522        )
9523        .await?;
9524        assert_eq!(summary.files_unchanged, 1);
9525        assert_eq!(summary.files_copied, 0);
9526        assert_eq!(summary.rm_summary.files_removed, 0);
9527        assert_eq!(tokio::fs::read_to_string(&dst_file).await?, "old");
9528        Ok(())
9529    }
9530
9531    // `--overwrite` with a destination the comparison deems identical must leave it alone rather
9532    // than remove and rewrite it. compares on size only so the fixture doesn't have to match mtimes.
9533    #[tokio::test]
9534    async fn skips_an_identical_pre_existing_file_in_a_fresh_marked_destination()
9535    -> Result<(), anyhow::Error> {
9536        let tmp = testutils::create_temp_dir().await?;
9537        let src_file = tmp.join("src.txt");
9538        let dst_file = tmp.join("dst.txt");
9539        tokio::fs::write(&src_file, "abc").await?;
9540        tokio::fs::write(&dst_file, "xyz").await?;
9541        let summary = copy(
9542            &PROGRESS,
9543            &src_file,
9544            &dst_file,
9545            &Settings {
9546                overwrite: true,
9547                overwrite_compare: filecmp::MetadataCmpSettings {
9548                    size: true,
9549                    ..Default::default()
9550                },
9551                ..settings_with_delete(None)
9552            },
9553            &NO_PRESERVE_SETTINGS,
9554            true,
9555        )
9556        .await?;
9557        assert_eq!(summary.files_unchanged, 1);
9558        assert_eq!(summary.files_copied, 0);
9559        assert_eq!(summary.rm_summary.files_removed, 0);
9560        // untouched: an identical destination is not removed and recreated.
9561        assert_eq!(tokio::fs::read_to_string(&dst_file).await?, "xyz");
9562        Ok(())
9563    }
9564
9565    // without `--overwrite` the conflict is still an error — but it must be the actionable one that
9566    // names the flag, not the raw `EEXIST` from `create_file`'s `O_EXCL`.
9567    #[tokio::test]
9568    async fn reports_missing_overwrite_for_a_pre_existing_file_in_a_fresh_marked_destination()
9569    -> Result<(), anyhow::Error> {
9570        let tmp = testutils::create_temp_dir().await?;
9571        let src_file = tmp.join("src.txt");
9572        let dst_file = tmp.join("dst.txt");
9573        tokio::fs::write(&src_file, "fresh source content").await?;
9574        tokio::fs::write(&dst_file, "old").await?;
9575        let error = copy(
9576            &PROGRESS,
9577            &src_file,
9578            &dst_file,
9579            &settings_with_delete(None), // neither --overwrite nor --ignore-existing
9580            &NO_PRESERVE_SETTINGS,
9581            true,
9582        )
9583        .await
9584        .expect_err("a pre-existing destination without --overwrite must fail");
9585        let message = format!("{:#}", &error.source);
9586        assert!(
9587            message.contains("did you intend to specify --overwrite?"),
9588            "expected the actionable overwrite error, got: {message}"
9589        );
9590        // and the destination is left exactly as it was.
9591        assert_eq!(tokio::fs::read_to_string(&dst_file).await?, "old");
9592        Ok(())
9593    }
9594
9595    // the `!is_fresh` counterpart of `ignores_a_pre_existing_file_in_a_fresh_marked_destination`:
9596    // `--ignore-existing` on a real (non-dry-run) local file copy had no coverage here, only in
9597    // dry-run and remote tests. pins that the route the helper is shared with keeps its behavior.
9598    #[tokio::test]
9599    async fn ignores_a_pre_existing_file_when_the_destination_is_not_fresh()
9600    -> Result<(), anyhow::Error> {
9601        let tmp = testutils::create_temp_dir().await?;
9602        let src_file = tmp.join("src.txt");
9603        let dst_file = tmp.join("dst.txt");
9604        tokio::fs::write(&src_file, "fresh source content").await?;
9605        tokio::fs::write(&dst_file, "old").await?;
9606        let summary = copy(
9607            &PROGRESS,
9608            &src_file,
9609            &dst_file,
9610            &Settings {
9611                ignore_existing: true,
9612                ..settings_with_delete(None)
9613            },
9614            &NO_PRESERVE_SETTINGS,
9615            false,
9616        )
9617        .await?;
9618        assert_eq!(summary.files_unchanged, 1);
9619        assert_eq!(summary.files_copied, 0);
9620        assert_eq!(tokio::fs::read_to_string(&dst_file).await?, "old");
9621        Ok(())
9622    }
9623
9624    // the source must open successfully before the destination is unlinked. an unreadable source
9625    // deterministically exercises the interval after planning but before mutation, and must leave
9626    // the destination intact. The same ordering covers cancellation and a long `--iops-throttle`
9627    // wait, neither of which is injectable here.
9628    #[tokio::test]
9629    async fn overwrite_keeps_the_destination_when_the_source_cannot_be_opened()
9630    -> Result<(), anyhow::Error> {
9631        let tmp = testutils::create_temp_dir().await?;
9632        let src = tmp.join("src");
9633        tokio::fs::create_dir(&src).await?;
9634        tokio::fs::write(src.join("a.txt"), "new content").await?;
9635        // unreadable source file; the parent directory stays traversable so the walk still
9636        // classifies it and the copy still plans to replace the destination.
9637        tokio::fs::set_permissions(src.join("a.txt"), std::fs::Permissions::from_mode(0o000))
9638            .await?;
9639        let dst = tmp.join("dst");
9640        tokio::fs::create_dir(&dst).await?;
9641        // different size, so `--overwrite-compare` says the destination differs and must go.
9642        tokio::fs::write(dst.join("a.txt"), "PRECIOUS").await?;
9643        let error = copy(
9644            &PROGRESS,
9645            &src,
9646            &dst,
9647            &Settings {
9648                overwrite: true,
9649                ..settings_with_delete(None)
9650            },
9651            &NO_PRESERVE_SETTINGS,
9652            false,
9653        )
9654        .await
9655        .expect_err("an unreadable source must fail the copy");
9656        let message = format!("{:#}", &error.source);
9657        assert!(
9658            message.contains("failed opening src file"),
9659            "expected the source open to be the failure; got: {message}"
9660        );
9661        assert_eq!(
9662            tokio::fs::read_to_string(dst.join("a.txt")).await?,
9663            "PRECIOUS",
9664            "the destination must survive a copy that never got far enough to replace it"
9665        );
9666        assert_eq!(
9667            error.summary.rm_summary.files_removed, 0,
9668            "nothing was removed, and the summary must say so"
9669        );
9670        Ok(())
9671    }
9672
9673    #[test]
9674    fn fresh_copy_handoff_removes_one_submission_per_file() -> anyhow::Result<()> {
9675        tokio::runtime::Builder::new_multi_thread()
9676            .worker_threads(4)
9677            .max_blocking_threads(32)
9678            .enable_all()
9679            .build()?
9680            .block_on(async {
9681                let limits = testutils::AdmissionLimit::new().await;
9682                let tmp = tempfile::tempdir()?;
9683                let source = tmp.path().join("source");
9684                std::fs::create_dir(&source)?;
9685                let mut config = crate::filegen::FileGenConfig::new(&source, vec![4], 32, 1000);
9686                config.leaf_files = true;
9687                let generated = crate::filegen::filegen(&PROGRESS, &config).await?;
9688                assert_eq!(generated.files_created, 128);
9689                let settings = Settings {
9690                    reflink: crate::copy_data::ReflinkMode::Never,
9691                    ..settings_with_delete(None)
9692                };
9693                for concurrency in [8, 32] {
9694                    limits.set_files_in_flight(concurrency);
9695                    let policies = [LocalCopyHandoff::default(), LocalCopyHandoff::Never, LocalCopyHandoff::Fresh];
9696                    let mut counts = [0; 3];
9697                    // rotate the production policies; no timing or cache-state conclusion follows
9698                    for index in if concurrency == 8 { [0, 1, 2] } else { [2, 1, 0] } {
9699                        let settings = Settings { local_copy_handoff: policies[index], ..settings.clone() };
9700                        let destination = tmp.path().join(format!("copy-{concurrency}-{index}"));
9701                        let observer = testutils::BlockingSubmissions::start();
9702                        let summary = limits.run_with_timeout(std::time::Duration::from_secs(30), copy(
9703                            &PROGRESS, &source, &destination, &settings, &NO_PRESERVE_SETTINGS, false,
9704                        )).await??;
9705                        counts[index] = observer.count();
9706                        drop(observer);
9707                        assert_eq!(summary.files_copied, 128);
9708                        assert_eq!(summary.bytes_copied, 128_000);
9709                        assert_eq!(std::fs::read_dir(&destination)?.count(), 4);
9710                        for dir in 0..4 {
9711                            assert_eq!(std::fs::read_dir(destination.join(format!("dir{dir}")))?.count(), 32);
9712                            for file in 0..32 {
9713                                let relative = format!("dir{dir}/file{file}");
9714                                assert_eq!(std::fs::read(source.join(&relative))?, std::fs::read(destination.join(&relative))?);
9715                                assert_eq!(std::fs::metadata(source.join(&relative))?.permissions(), std::fs::metadata(destination.join(&relative))?.permissions());
9716                            }
9717                        }
9718                    }
9719                    assert_eq!(counts[0], counts[1], "the default retains separate jobs");
9720                    assert_eq!(counts[1] - counts[2], 128, "one saved submission per copied file");
9721                    println!("handoff submission fixture: files=128 bytes_per_file=1000 workers=4 blocking=32 concurrency={concurrency} default={} never={} fresh={}", counts[0], counts[1], counts[2]);
9722                }
9723                anyhow::Ok(())
9724            })
9725    }
9726
9727    async fn assert_conflict_retry_keeps_the_original_source(acl: bool) -> anyhow::Result<()> {
9728        use std::os::unix::fs::PermissionsExt as _;
9729        use testutils::acl::{get_xattr_at, permissive_acl, restrictive_access_acl, set_xattr_at};
9730        let acl_name = c"system.posix_acl_access";
9731        for handoff in [LocalCopyHandoff::Never, LocalCopyHandoff::Fresh] {
9732            let tmp = tempfile::tempdir()?;
9733            let source = tmp.path().join("source");
9734            let destination = tmp.path().join("destination");
9735            std::fs::write(&source, b"original payload")?;
9736            std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o751))?;
9737            let original_acl = acl.then(restrictive_access_acl);
9738            if let Some(blob) = &original_acl {
9739                set_xattr_at(&source, acl_name, blob);
9740            }
9741            let original_mode = std::fs::metadata(&source)?.permissions().mode() & 0o7777;
9742            std::fs::write(&destination, b"old")?;
9743            let source_parent =
9744                Arc::new(Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?);
9745            let destination_parent = Arc::new(
9746                Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?,
9747            );
9748            let current =
9749                CurrentRegular::open(&source_parent, OsStr::new("source"), &source).await?;
9750            std::fs::rename(&source, tmp.path().join("original"))?;
9751            std::fs::write(&source, b"replacement")?;
9752            std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o600))?;
9753            if acl {
9754                set_xattr_at(&source, acl_name, &permissive_acl());
9755                assert_ne!(get_xattr_at(&source, acl_name), original_acl);
9756            }
9757            let settings = Settings {
9758                local_copy_handoff: handoff,
9759                overwrite: true,
9760                reflink: crate::copy_data::ReflinkMode::Never,
9761                ..settings_with_delete(None)
9762            };
9763            let mut preservation = preserve::preserve_all();
9764            preservation.file.acl = acl;
9765            let summary = copy_current_regular(
9766                &PROGRESS,
9767                &source_parent,
9768                &destination_parent,
9769                OsStr::new("destination"),
9770                &destination,
9771                &source,
9772                current,
9773                FilePlan::Vacant,
9774                &settings,
9775                &preservation,
9776                &DestinationContext::parent(None),
9777            )
9778            .await?;
9779            assert_eq!(summary.files_copied, 1);
9780            assert_eq!(summary.bytes_copied, 16);
9781            assert_eq!(summary.rm_summary.files_removed, 1);
9782            assert_eq!(std::fs::read(&destination)?, b"original payload");
9783            assert_eq!(
9784                std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
9785                original_mode
9786            );
9787            if let Some(blob) = original_acl {
9788                assert_eq!(get_xattr_at(&destination, acl_name), Some(blob));
9789            }
9790        }
9791        Ok(())
9792    }
9793
9794    #[tokio::test]
9795    async fn conflict_retry_keeps_the_original_source_descriptor_without_acl_preservation()
9796    -> anyhow::Result<()> {
9797        assert_conflict_retry_keeps_the_original_source(false).await
9798    }
9799
9800    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
9801    #[tokio::test]
9802    async fn conflict_retry_keeps_the_original_source_descriptor_with_acl_preservation()
9803    -> anyhow::Result<()> {
9804        assert_conflict_retry_keeps_the_original_source(true).await
9805    }
9806
9807    #[tokio::test]
9808    async fn failed_source_acl_read_keeps_the_existing_destination_intact() -> anyhow::Result<()> {
9809        use std::os::fd::AsRawFd as _;
9810        for handoff in [LocalCopyHandoff::Never, LocalCopyHandoff::Fresh] {
9811            let tmp = tempfile::tempdir()?;
9812            let source = tmp.path().join("source");
9813            let destination = tmp.path().join("destination");
9814            std::fs::write(&source, b"new payload")?;
9815            std::fs::write(&destination, b"old payload")?;
9816            let original_destination = std::fs::metadata(&destination)?;
9817            let source_parent =
9818                Arc::new(Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?);
9819            let destination_parent = Arc::new(
9820                Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?,
9821            );
9822            let current =
9823                CurrentRegular::open(&source_parent, OsStr::new("source"), &source).await?;
9824            let identity = testutils::FdIdentityProbe::capture(current.file.as_raw_fd())?;
9825            let failure = testutils::BlockingPathGate::fail_once(&source, libc::EIO);
9826            let plan = FilePlan::Replace(
9827                destination_parent
9828                    .child(OsStr::new("destination"))
9829                    .await?
9830                    .into_removal_snapshot(),
9831            );
9832            let settings = Settings {
9833                local_copy_handoff: handoff,
9834                overwrite: true,
9835                ..settings_with_delete(None)
9836            };
9837            let mut preservation = preserve::preserve_all();
9838            preservation.file.acl = true;
9839            let error = copy_current_regular(
9840                &PROGRESS,
9841                &source_parent,
9842                &destination_parent,
9843                OsStr::new("destination"),
9844                &destination,
9845                &source,
9846                current,
9847                plan,
9848                &settings,
9849                &preservation,
9850                &DestinationContext::parent(None),
9851            )
9852            .await
9853            .expect_err("ACL failure must precede destination removal");
9854            assert!(
9855                error.source.to_string().contains("failed reading ACLs"),
9856                "unexpected copy error: {error:?}"
9857            );
9858            assert_eq!(
9859                error
9860                    .source
9861                    .root_cause()
9862                    .downcast_ref::<std::io::Error>()
9863                    .and_then(std::io::Error::raw_os_error),
9864                Some(libc::EIO)
9865            );
9866            assert_eq!(error.summary.files_copied, 0);
9867            assert_eq!(error.summary.bytes_copied, 0);
9868            assert_eq!(error.summary.rm_summary.files_removed, 0);
9869            assert!(identity.original_is_closed()?);
9870            assert_eq!(std::fs::read(&destination)?, b"old payload");
9871            let remaining = std::fs::metadata(&destination)?;
9872            assert_eq!(
9873                std::os::unix::fs::MetadataExt::ino(&remaining),
9874                std::os::unix::fs::MetadataExt::ino(&original_destination)
9875            );
9876            assert_eq!(remaining.permissions(), original_destination.permissions());
9877            assert_eq!(remaining.modified()?, original_destination.modified()?);
9878            assert_eq!(failure.hit_count(), 1);
9879            // the same path succeeds after the one-shot error, while its gate remains installed
9880            let (file, _) = safedir::read_acls_owned(
9881                std::fs::File::open(&source)?,
9882                congestion::Side::Source,
9883                false,
9884            )
9885            .await?;
9886            drop(file);
9887            assert_eq!(failure.hit_count(), 2);
9888        }
9889        Ok(())
9890    }
9891
9892    #[tokio::test]
9893    async fn failed_data_copy_keeps_the_created_file_owner_only() -> anyhow::Result<()> {
9894        use std::os::unix::fs::PermissionsExt as _;
9895        let tmp = tempfile::tempdir()?;
9896        let source = tmp.path().join("source");
9897        let destination = tmp.path().join("destination");
9898        std::fs::write(&source, b"payload")?;
9899        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
9900        let source_parent =
9901            Arc::new(Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?);
9902        let destination_parent =
9903            Arc::new(Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?);
9904        let mut current =
9905            CurrentRegular::open(&source_parent, OsStr::new("source"), &source).await?;
9906        // retain valid regular-file metadata but force the data read to fail after creation
9907        current.file = std::fs::OpenOptions::new().write(true).open(&source)?;
9908        let settings = Settings {
9909            local_copy_handoff: LocalCopyHandoff::Fresh,
9910            reflink: crate::copy_data::ReflinkMode::Never,
9911            ..settings_with_delete(None)
9912        };
9913        let error = copy_current_regular(
9914            &PROGRESS,
9915            &source_parent,
9916            &destination_parent,
9917            OsStr::new("destination"),
9918            &destination,
9919            &source,
9920            current,
9921            FilePlan::Vacant,
9922            &settings,
9923            &preserve::preserve_all(),
9924            &DestinationContext::parent(None),
9925        )
9926        .await
9927        .expect_err("an unreadable payload descriptor must fail the data copy");
9928        assert_eq!(
9929            error
9930                .source
9931                .root_cause()
9932                .downcast_ref::<std::io::Error>()
9933                .and_then(std::io::Error::raw_os_error),
9934            Some(libc::EBADF),
9935        );
9936        assert_eq!(error.summary.files_copied, 0);
9937        assert_eq!(error.summary.bytes_copied, 0);
9938        let metadata = std::fs::metadata(&destination)?;
9939        assert_eq!(metadata.permissions().mode() & 0o7777, 0o600);
9940        assert_eq!(metadata.len(), 0);
9941        Ok(())
9942    }
9943
9944    // `execute_dst_plan` is the ONLY mutating step, and it accumulates rather than overwrites: a
9945    // copy can plan the slot twice — once up front, then again after `create_file` reports it
9946    // refilled by a competing writer — and the first removal has to survive into the totals.
9947    #[tokio::test]
9948    async fn executing_a_second_replace_keeps_the_first_removal_in_the_totals()
9949    -> Result<(), anyhow::Error> {
9950        let tmp = testutils::create_temp_dir().await?;
9951        tokio::fs::write(tmp.join("victim.txt"), "0123456").await?; // 7 bytes
9952        let dst_parent =
9953            Arc::new(Dir::open_root_dir(&tmp, false, congestion::Side::Destination).await?);
9954        let victim: &OsStr = OsStr::new("victim.txt");
9955        let plan = FilePlan::Replace(dst_parent.child(victim).await?.into_removal_snapshot());
9956        // as if an earlier removal had already happened in this same copy.
9957        let mut copy_summary = Summary {
9958            rm_summary: RmSummary {
9959                files_removed: 1,
9960                bytes_removed: 10,
9961                ..Default::default()
9962            },
9963            ..Default::default()
9964        };
9965        execute_dst_plan(
9966            &PROGRESS,
9967            &dst_parent,
9968            victim,
9969            &tmp.join("victim.txt"),
9970            plan,
9971            &settings_with_delete(None),
9972            &mut copy_summary,
9973            &DestinationContext::parent(Some(Arc::clone(&dst_parent))),
9974        )
9975        .await?;
9976        assert_eq!(copy_summary.rm_summary.files_removed, 2);
9977        assert_eq!(copy_summary.rm_summary.bytes_removed, 17);
9978        assert!(!tmp.join("victim.txt").exists(), "the entry was unlinked");
9979        // and `Vacant` must be a genuine no-op on the same summary.
9980        execute_dst_plan(
9981            &PROGRESS,
9982            &dst_parent,
9983            victim,
9984            &tmp.join("victim.txt"),
9985            FilePlan::Vacant,
9986            &settings_with_delete(None),
9987            &mut copy_summary,
9988            &DestinationContext::parent(Some(Arc::clone(&dst_parent))),
9989        )
9990        .await?;
9991        assert_eq!(copy_summary.rm_summary.files_removed, 2);
9992        Ok(())
9993    }
9994
9995    // a competing writer may replace the planned entry before execution. overwrite removes the
9996    // current contained entry, while its accounting retains the metadata captured during planning.
9997    #[tokio::test]
9998    async fn executing_a_swapped_replace_removes_the_current_entry_and_keeps_earlier_totals()
9999    -> Result<(), anyhow::Error> {
10000        let tmp = testutils::create_temp_dir().await?;
10001        tokio::fs::write(tmp.join("victim.txt"), "original").await?;
10002        let dst_parent =
10003            Arc::new(Dir::open_root_dir(&tmp, false, congestion::Side::Destination).await?);
10004        let victim: &OsStr = OsStr::new("victim.txt");
10005        let plan = FilePlan::Replace(dst_parent.child(victim).await?.into_removal_snapshot());
10006        // a competing writer swaps in a different inode under the same name after we planned.
10007        tokio::fs::remove_file(tmp.join("victim.txt")).await?;
10008        tokio::fs::write(tmp.join("victim.txt"), "someone else's file").await?;
10009        let mut copy_summary = Summary {
10010            rm_summary: RmSummary {
10011                files_removed: 1,
10012                bytes_removed: 10,
10013                ..Default::default()
10014            },
10015            ..Default::default()
10016        };
10017        execute_dst_plan(
10018            &PROGRESS,
10019            &dst_parent,
10020            victim,
10021            &tmp.join("victim.txt"),
10022            plan,
10023            &settings_with_delete(None),
10024            &mut copy_summary,
10025            &DestinationContext::parent(Some(Arc::clone(&dst_parent))),
10026        )
10027        .await?;
10028        assert_eq!(copy_summary.rm_summary.files_removed, 2);
10029        assert_eq!(copy_summary.rm_summary.bytes_removed, 18);
10030        assert!(
10031            !tmp.join("victim.txt").exists(),
10032            "overwrite removes the entry currently occupying the contained slot"
10033        );
10034        Ok(())
10035    }
10036
10037    #[tokio::test]
10038    async fn file_plan_swapped_to_symlink_unlinks_the_slot_and_keeps_file_snapshot_accounting()
10039    -> Result<(), anyhow::Error> {
10040        let tmp = testutils::create_temp_dir().await?;
10041        let dst = tmp.join("dst");
10042        tokio::fs::create_dir(&dst).await?;
10043        let victim_path = dst.join("victim.txt");
10044        let sentinel_path = tmp.join("sentinel.txt");
10045        tokio::fs::write(&victim_path, "original").await?;
10046        tokio::fs::write(&sentinel_path, "keep me").await?;
10047        let dst_parent =
10048            Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
10049        let victim: &OsStr = OsStr::new("victim.txt");
10050        let plan = FilePlan::Replace(dst_parent.child(victim).await?.into_removal_snapshot());
10051
10052        // a competing writer replaces the planned file with a link to an external target.
10053        tokio::fs::remove_file(&victim_path).await?;
10054        tokio::fs::symlink(&sentinel_path, &victim_path).await?;
10055
10056        let mut copy_summary = Summary::default();
10057        execute_dst_plan(
10058            &PROGRESS,
10059            &dst_parent,
10060            victim,
10061            &victim_path,
10062            plan,
10063            &settings_with_delete(None),
10064            &mut copy_summary,
10065            &DestinationContext::parent(Some(Arc::clone(&dst_parent))),
10066        )
10067        .await?;
10068
10069        assert!(
10070            tokio::fs::symlink_metadata(&victim_path).await.is_err(),
10071            "overwrite must unlink the replacement symlink"
10072        );
10073        assert_eq!(tokio::fs::read_to_string(&sentinel_path).await?, "keep me");
10074        assert_eq!(copy_summary.rm_summary.files_removed, 1);
10075        assert_eq!(copy_summary.rm_summary.symlinks_removed, 0);
10076        assert_eq!(copy_summary.rm_summary.bytes_removed, 8);
10077        Ok(())
10078    }
10079
10080    // the pure half of the same accounting rule: when the retry's plan says SKIP, a removal the
10081    // copy already performed still has to reach the summary the caller returns.
10082    #[test]
10083    fn a_skip_keeps_an_earlier_removal_in_the_totals() {
10084        let copy_summary = Summary {
10085            rm_summary: RmSummary {
10086                files_removed: 1,
10087                bytes_removed: 10,
10088                ..Default::default()
10089            },
10090            ..Default::default()
10091        };
10092        let skip = Summary {
10093            files_unchanged: 1,
10094            ..Default::default()
10095        };
10096        let summary = skip_summary(skip, &copy_summary);
10097        assert_eq!(summary.files_unchanged, 1);
10098        assert_eq!(summary.rm_summary.files_removed, 1);
10099        assert_eq!(summary.rm_summary.bytes_removed, 10);
10100    }
10101
10102    // the two tests below are NOT regression tests for the file fix above — they PASS on the code
10103    // that preceded it, and that is the point. `copy_symlink_fd` never consults `is_fresh` in its
10104    // create path: it attempts `symlink_at` unconditionally and resolves any `AlreadyExists` through
10105    // the normal ignore-existing / overwrite logic, which is the shape `copy_file_fd` was changed to
10106    // adopt. these pin that the symlink sibling stays immune to a stale freshness hint, so a later
10107    // refactor that teaches its `AlreadyExists` branch to trust `is_fresh` fails here instead of
10108    // silently reintroducing the file bug on the symlink path.
10109
10110    #[tokio::test]
10111    async fn stale_fresh_hint_overwrites_preexisting_symlink() -> Result<(), anyhow::Error> {
10112        let tmp = testutils::create_temp_dir().await?;
10113        let src_link = tmp.join("src.link");
10114        let dst_link = tmp.join("dst.link");
10115        tokio::fs::symlink("target-a", &src_link).await?;
10116        tokio::fs::symlink("target-b", &dst_link).await?;
10117        let summary = copy(
10118            &PROGRESS,
10119            &src_link,
10120            &dst_link,
10121            &Settings {
10122                overwrite: true,
10123                ..settings_with_delete(None)
10124            },
10125            &NO_PRESERVE_SETTINGS,
10126            true, // caller believes it is fresh, but another writer got here first
10127        )
10128        .await?;
10129        assert_eq!(summary.symlinks_created, 1);
10130        assert_eq!(summary.rm_summary.symlinks_removed, 1);
10131        assert_eq!(
10132            tokio::fs::read_link(&dst_link).await?.to_str(),
10133            Some("target-a")
10134        );
10135        Ok(())
10136    }
10137
10138    #[tokio::test]
10139    async fn stale_fresh_hint_ignores_preexisting_symlink() -> Result<(), anyhow::Error> {
10140        let tmp = testutils::create_temp_dir().await?;
10141        let src_link = tmp.join("src.link");
10142        let dst_link = tmp.join("dst.link");
10143        tokio::fs::symlink("target-a", &src_link).await?;
10144        tokio::fs::symlink("target-b", &dst_link).await?;
10145        let summary = copy(
10146            &PROGRESS,
10147            &src_link,
10148            &dst_link,
10149            &Settings {
10150                ignore_existing: true,
10151                ..settings_with_delete(None)
10152            },
10153            &NO_PRESERVE_SETTINGS,
10154            true,
10155        )
10156        .await?;
10157        assert_eq!(summary.symlinks_unchanged, 1);
10158        assert_eq!(summary.symlinks_created, 0);
10159        assert_eq!(
10160            tokio::fs::read_link(&dst_link).await?.to_str(),
10161            Some("target-b")
10162        );
10163        Ok(())
10164    }
10165
10166    // Task 1.5 (c): FIFO swap. While the copy runs, `src/sub/entry` is flipped between a real file
10167    // and a FIFO (named pipe). open_file_read uses O_NONBLOCK + an fstat S_ISREG check, so a FIFO is
10168    // rejected without blocking. The whole copy is wrapped in a generous timeout: the assertion is
10169    // that it never hangs, and a FIFO is never copied as file data.
10170    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
10171    async fn fifo_swap_never_hangs_or_copies_pipe() -> Result<(), anyhow::Error> {
10172        let tmp_dir = testutils::create_temp_dir().await?;
10173        let test_path = tmp_dir.as_path();
10174        let src = test_path.join("src");
10175        let sub = src.join("sub");
10176        tokio::fs::create_dir(&src).await?;
10177        tokio::fs::create_dir(&sub).await?;
10178        tokio::fs::write(sub.join("entry"), "REAL_CONTENT").await?;
10179
10180        let swapper = {
10181            let sub = sub.clone();
10182            crate::testutils::SwapperGuard::spawn(move |stop| {
10183                let entry = sub.join("entry");
10184                let staged_real = sub.join("__staged_real");
10185                let staged_fifo = sub.join("__staged_fifo");
10186                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
10187                    // real file staged then renamed over `entry`.
10188                    let _ = std::fs::remove_file(&staged_real);
10189                    if std::fs::write(&staged_real, b"REAL_CONTENT").is_ok() {
10190                        let _ = std::fs::rename(&staged_real, &entry);
10191                    }
10192                    // FIFO staged then renamed over `entry`. mkfifo can't target an existing name,
10193                    // so create it at a staging path and rename it in.
10194                    let _ = std::fs::remove_file(&staged_fifo);
10195                    let made = nix::unistd::mkfifo(
10196                        &staged_fifo,
10197                        nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
10198                    )
10199                    .is_ok();
10200                    if made {
10201                        let _ = std::fs::rename(&staged_fifo, &entry);
10202                    }
10203                }
10204            })
10205        };
10206
10207        let settings = toctou_settings();
10208        for i in 0..200 {
10209            let dst = test_path.join(format!("dst_{i}"));
10210            // the generous timeout is the anti-hang assertion: a FIFO opened without O_NONBLOCK
10211            // would block the copy forever waiting for a writer.
10212            let _ = tokio::time::timeout(
10213                std::time::Duration::from_secs(30),
10214                copy(
10215                    &PROGRESS,
10216                    &src,
10217                    &dst,
10218                    &settings,
10219                    &NO_PRESERVE_SETTINGS,
10220                    false,
10221                ),
10222            )
10223            .await
10224            .expect("copy must not hang when an entry is swapped to a FIFO");
10225            // CORE ASSERTION: whatever landed at the destination is either absent or a real regular
10226            // file with the real content — a FIFO is never copied as data, and never copied as a
10227            // special (no specials are expected in the destination).
10228            let entry_dst = dst.join("sub").join("entry");
10229            if let Ok(md) = tokio::fs::symlink_metadata(&entry_dst).await {
10230                use std::os::unix::fs::FileTypeExt as _;
10231                let ft = md.file_type();
10232                assert!(
10233                    !ft.is_fifo(),
10234                    "iteration {i}: a FIFO was reproduced at the destination"
10235                );
10236                if ft.is_file() {
10237                    let content = tokio::fs::read_to_string(&entry_dst).await?;
10238                    assert_eq!(
10239                        content, "REAL_CONTENT",
10240                        "iteration {i}: a regular destination file must hold the real content"
10241                    );
10242                }
10243            }
10244            let _ = tokio::fs::remove_dir_all(&dst).await;
10245        }
10246
10247        drop(swapper);
10248        Ok(())
10249    }
10250
10251    // a deep, narrow chain `a/a/a/.../file` copies fully without hanging or exhausting fds
10252    // the shared driver uses async recursion, so depth exercises the recursive chain; 800 is
10253    // deep enough to stress the fd budget / hold-and-wait avoidance without risking a stack blowup
10254    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
10255    async fn copy_deep_narrow_tree_completes() -> Result<(), anyhow::Error> {
10256        let tmp_dir = testutils::create_temp_dir().await?;
10257        let test_path = tmp_dir.as_path();
10258        let src = test_path.join("src");
10259        const DEPTH: usize = 800;
10260        // build src/a/a/.../a/leaf.txt by appending one "a" per level.
10261        let mut cur = src.clone();
10262        for _ in 0..DEPTH {
10263            cur = cur.join("a");
10264        }
10265        tokio::fs::create_dir_all(&cur).await?;
10266        tokio::fs::write(cur.join("leaf.txt"), "DEEP_LEAF").await?;
10267
10268        let dst = test_path.join("dst");
10269        let summary = tokio::time::timeout(
10270            std::time::Duration::from_secs(120),
10271            copy(
10272                &PROGRESS,
10273                &src,
10274                &dst,
10275                &toctou_settings(),
10276                &NO_PRESERVE_SETTINGS,
10277                false,
10278            ),
10279        )
10280        .await
10281        .expect("deep-narrow copy must not hang (fd budget / hold-and-wait)")?;
10282        assert_eq!(
10283            summary.files_copied, 1,
10284            "the single leaf file must be copied"
10285        );
10286        // the destination root directory plus the DEPTH-level `a` chain copied into it.
10287        assert_eq!(summary.directories_created, DEPTH + 1);
10288        // verify the leaf actually landed at the bottom of the destination chain.
10289        let mut leaf = dst.clone();
10290        for _ in 0..DEPTH {
10291            leaf = leaf.join("a");
10292        }
10293        let content = tokio::fs::read_to_string(leaf.join("leaf.txt")).await?;
10294        assert_eq!(content, "DEEP_LEAF");
10295        Ok(())
10296    }
10297
10298    // Task 1.6: a single very wide directory (many sibling files) copies fully within a timeout. The
10299    // per-entry file-in-flight permit bounds concurrency; this confirms the wide fan-out drains without
10300    // fd exhaustion or a hang.
10301    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
10302    async fn copy_wide_tree_completes() -> Result<(), anyhow::Error> {
10303        let tmp_dir = testutils::create_temp_dir().await?;
10304        let test_path = tmp_dir.as_path();
10305        let src = test_path.join("src");
10306        tokio::fs::create_dir(&src).await?;
10307        const WIDTH: usize = 2000;
10308        for i in 0..WIDTH {
10309            tokio::fs::write(src.join(format!("f{i}.txt")), format!("content {i}")).await?;
10310        }
10311        let dst = test_path.join("dst");
10312        let summary = tokio::time::timeout(
10313            std::time::Duration::from_secs(120),
10314            copy(
10315                &PROGRESS,
10316                &src,
10317                &dst,
10318                &toctou_settings(),
10319                &NO_PRESERVE_SETTINGS,
10320                false,
10321            ),
10322        )
10323        .await
10324        .expect("wide copy must not hang (fd exhaustion / permit deadlock)")?;
10325        assert_eq!(summary.files_copied, WIDTH, "every file must be copied");
10326        // spot-check a few files actually landed with the right content.
10327        for i in [0usize, WIDTH / 2, WIDTH - 1] {
10328            let content = tokio::fs::read_to_string(dst.join(format!("f{i}.txt"))).await?;
10329            assert_eq!(content, format!("content {i}"));
10330        }
10331        Ok(())
10332    }
10333
10334    // fake metadata carrying the fields --overwrite-compare can use (size, mtime, uid, gid, mode).
10335    #[derive(Clone, Debug)]
10336    struct CmpMeta {
10337        uid: u32,
10338        gid: u32,
10339        mode: u32,
10340        size: u64,
10341        mtime: i64,
10342    }
10343    impl crate::preserve::Metadata for CmpMeta {
10344        fn uid(&self) -> u32 {
10345            self.uid
10346        }
10347        fn gid(&self) -> u32 {
10348            self.gid
10349        }
10350        fn atime(&self) -> i64 {
10351            0
10352        }
10353        fn atime_nsec(&self) -> i64 {
10354            0
10355        }
10356        fn mtime(&self) -> i64 {
10357            self.mtime
10358        }
10359        fn mtime_nsec(&self) -> i64 {
10360            0
10361        }
10362        fn permissions(&self) -> std::fs::Permissions {
10363            std::os::unix::fs::PermissionsExt::from_mode(self.mode)
10364        }
10365        fn size(&self) -> u64 {
10366            self.size
10367        }
10368    }
10369
10370    fn size_mtime() -> filecmp::MetadataCmpSettings {
10371        filecmp::MetadataCmpSettings {
10372            size: true,
10373            mtime: true,
10374            ..Default::default()
10375        }
10376    }
10377    fn base() -> CmpMeta {
10378        CmpMeta {
10379            uid: 0,
10380            gid: 0,
10381            mode: 0o644,
10382            size: 10,
10383            mtime: 100,
10384        }
10385    }
10386
10387    #[test]
10388    fn skip_send_no_existing_entry_sends() {
10389        let src = base();
10390        let r = skip_unchanged_send(
10391            &size_mtime(),
10392            None,
10393            false,
10394            &src,
10395            None::<ExistingDst<CmpMeta>>,
10396        );
10397        assert!(!r);
10398    }
10399
10400    #[test]
10401    fn skip_send_ignore_existing_skips_any_type() {
10402        let src = base();
10403        let dst = base();
10404        let r = skip_unchanged_send(
10405            &size_mtime(),
10406            None,
10407            true,
10408            &src,
10409            Some(ExistingDst {
10410                meta: &dst,
10411                is_file: false,
10412            }),
10413        );
10414        assert!(r);
10415    }
10416
10417    #[test]
10418    fn skip_send_overwrite_identical_skips() {
10419        let src = base();
10420        let dst = base();
10421        let r = skip_unchanged_send(
10422            &size_mtime(),
10423            None,
10424            false,
10425            &src,
10426            Some(ExistingDst {
10427                meta: &dst,
10428                is_file: true,
10429            }),
10430        );
10431        assert!(r);
10432    }
10433
10434    #[test]
10435    fn skip_send_overwrite_different_size_sends() {
10436        let src = base();
10437        let dst = CmpMeta { size: 11, ..base() };
10438        let r = skip_unchanged_send(
10439            &size_mtime(),
10440            None,
10441            false,
10442            &src,
10443            Some(ExistingDst {
10444                meta: &dst,
10445                is_file: true,
10446            }),
10447        );
10448        assert!(!r);
10449    }
10450
10451    #[test]
10452    fn skip_send_overwrite_different_mtime_sends() {
10453        let src = base();
10454        let dst = CmpMeta {
10455            mtime: 200,
10456            ..base()
10457        };
10458        let r = skip_unchanged_send(
10459            &size_mtime(),
10460            None,
10461            false,
10462            &src,
10463            Some(ExistingDst {
10464                meta: &dst,
10465                is_file: true,
10466            }),
10467        );
10468        assert!(!r);
10469    }
10470
10471    #[test]
10472    fn skip_send_overwrite_non_file_sends() {
10473        let src = base();
10474        let dst = base();
10475        let r = skip_unchanged_send(
10476            &size_mtime(),
10477            None,
10478            false,
10479            &src,
10480            Some(ExistingDst {
10481                meta: &dst,
10482                is_file: false,
10483            }),
10484        );
10485        assert!(!r);
10486    }
10487
10488    #[test]
10489    fn skip_send_filter_newer_skips_when_dest_newer() {
10490        let src = CmpMeta {
10491            mtime: 100,
10492            size: 5,
10493            ..base()
10494        };
10495        let dst = CmpMeta {
10496            mtime: 200,
10497            size: 11,
10498            ..base()
10499        };
10500        let r = skip_unchanged_send(
10501            &size_mtime(),
10502            Some(OverwriteFilter::Newer),
10503            false,
10504            &src,
10505            Some(ExistingDst {
10506                meta: &dst,
10507                is_file: true,
10508            }),
10509        );
10510        assert!(r);
10511    }
10512
10513    #[test]
10514    fn skip_send_filter_newer_sends_when_dest_older() {
10515        let src = CmpMeta {
10516            mtime: 200,
10517            size: 5,
10518            ..base()
10519        };
10520        let dst = CmpMeta {
10521            mtime: 100,
10522            size: 11,
10523            ..base()
10524        };
10525        let r = skip_unchanged_send(
10526            &size_mtime(),
10527            Some(OverwriteFilter::Newer),
10528            false,
10529            &src,
10530            Some(ExistingDst {
10531                meta: &dst,
10532                is_file: true,
10533            }),
10534        );
10535        assert!(!r);
10536    }
10537}