Skip to main content

common/
copy.rs

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