Skip to main content

common/
link.rs

1use crate::delete::LinkChildOutcomes;
2use anyhow::{Context, anyhow};
3use async_recursion::async_recursion;
4use std::sync::Arc;
5use tracing::instrument;
6
7use crate::copy;
8use crate::copy::{
9    EmptyDirAction, Settings as CopySettings, Summary as CopySummary, check_empty_dir_cleanup,
10};
11use crate::filecmp;
12use crate::preserve;
13use crate::progress;
14use crate::safedir::{self, Dir, Handle};
15use crate::walk::{
16    self, AdmittedEntry, AdmittedLeaf, EntryAdmission, EntryKind, LeafPermit, PermitKind,
17};
18
19/// Error type for link operations. See [`crate::error::OperationError`] for
20/// logging conventions and rationale.
21pub type Error = crate::error::OperationError<Summary>;
22
23#[derive(Debug, Clone)]
24pub struct Settings {
25    pub copy_settings: CopySettings,
26    pub update_compare: filecmp::MetadataCmpSettings,
27    pub update_exclusive: bool,
28    /// filter settings for include/exclude patterns
29    pub filter: Option<crate::filter::FilterSettings>,
30    /// dry-run mode for previewing operations
31    pub dry_run: Option<crate::config::DryRunMode>,
32    /// metadata preservation settings
33    pub preserve: preserve::Settings,
34}
35
36#[derive(Copy, Clone, Debug, Eq, PartialEq)]
37enum UpdateRootRequirement {
38    Optional,
39    RequiredForDestructiveOperation,
40}
41
42impl UpdateRootRequirement {
43    fn from_settings(settings: &Settings) -> Self {
44        if settings.update_exclusive || settings.copy_settings.delete.is_some() {
45            Self::RequiredForDestructiveOperation
46        } else {
47            Self::Optional
48        }
49    }
50
51    fn is_required(self) -> bool {
52        self == Self::RequiredForDestructiveOperation
53    }
54
55    fn for_entry(self, rel_path: &std::path::Path) -> Self {
56        if rel_path.as_os_str().is_empty() {
57            self
58        } else {
59            Self::Optional
60        }
61    }
62
63    #[allow(clippy::result_large_err)]
64    fn classify<T>(
65        self,
66        result: std::io::Result<T>,
67        update_path: &std::path::Path,
68    ) -> Result<Option<T>, Error> {
69        match result {
70            Ok(value) => Ok(Some(value)),
71            Err(error) if error.kind() == std::io::ErrorKind::NotFound && !self.is_required() => {
72                Ok(None)
73            }
74            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
75                Err(missing_destructive_update_error(update_path))
76            }
77            Err(error) => Err(Error::new(
78                anyhow::Error::new(error)
79                    .context(format!("failed reading metadata from {update_path:?}")),
80                Default::default(),
81            )),
82        }
83    }
84}
85
86fn missing_destructive_update_error(update_path: &std::path::Path) -> Error {
87    Error::new(
88        anyhow!(
89            "--update path {:?} does not exist (rejected under --delete or --update-exclusive to avoid silently pruning destination entries the update tree would otherwise have preserved)",
90            update_path
91        ),
92        Default::default(),
93    )
94}
95
96/// Summary with the appropriate `*_skipped` counter set to 1 for the given entry kind.
97/// Special files count as `files_skipped` to match the historical mapping used
98/// when filters skip an entry (`specials_skipped` is reserved for `--skip-specials`).
99fn skipped_summary_for(kind: EntryKind) -> Summary {
100    let copy_summary = match kind {
101        EntryKind::Dir => CopySummary {
102            directories_skipped: 1,
103            ..Default::default()
104        },
105        EntryKind::Symlink => CopySummary {
106            symlinks_skipped: 1,
107            ..Default::default()
108        },
109        EntryKind::File | EntryKind::Special => CopySummary {
110            files_skipped: 1,
111            ..Default::default()
112        },
113    };
114    Summary {
115        copy_summary,
116        ..Default::default()
117    }
118}
119
120#[derive(Copy, Clone, Debug, Default)]
121pub struct Summary {
122    pub hard_links_created: usize,
123    pub hard_links_unchanged: usize,
124    pub copy_summary: CopySummary,
125}
126
127impl std::ops::Add for Summary {
128    type Output = Self;
129    fn add(self, other: Self) -> Self {
130        Self {
131            hard_links_created: self.hard_links_created + other.hard_links_created,
132            hard_links_unchanged: self.hard_links_unchanged + other.hard_links_unchanged,
133            copy_summary: self.copy_summary + other.copy_summary,
134        }
135    }
136}
137
138impl std::fmt::Display for Summary {
139    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
140        write!(
141            f,
142            "{}\n\
143            link:\n\
144            -----\n\
145            hard-links created: {}\n\
146            hard links unchanged: {}\n",
147            &self.copy_summary, self.hard_links_created, self.hard_links_unchanged
148        )
149    }
150}
151
152/// Hard-link the already-classified source entry (pinned by `src_handle`) to `dst_name` within
153/// `dst_dir`, fd-relative and inode-exact.
154///
155/// `dst_dir.hard_link_handle_at` links the EXACT inode `src_handle` pins (via its `O_PATH` fd,
156/// using `linkat(.., "/proc/self/fd/N", .., AT_SYMLINK_FOLLOW)`) rather than re-resolving the
157/// source by name. On an actor-writable source, `name` can be swapped to a different inode
158/// (symlink, FIFO, another file) after classification; linking the pinned inode ensures rlink either
159/// hard-links the exact classified regular file or fails closed (`ENOENT` when its last link was
160/// removed), never the replacement. `linkat` still refuses to hard-link a directory (`EPERM`).
161///
162/// On `EEXIST` under `--overwrite`, the existing destination is re-classified through `dst_dir`'s
163/// fd and, if it is an identical hard link (same dev+ino), left as is; otherwise it is removed via
164/// fd-relative [`copy::remove_existing`] and the link is retried — mirroring copy's overwrite
165/// branches.
166///
167/// No metadata is applied here, and `f:acl` in particular must never reach this path: a hard-linked
168/// destination SHARES the source's inode, so writing an ACL "to the destination" would rewrite the
169/// SOURCE's permissions. There is nothing to apply anyway — the shared inode already carries the
170/// source's metadata verbatim, which is the whole point of a hard link. `f:acl` therefore applies
171/// only on rlink's real copy path ([`copy::copy_child`], for changed files under `--update`).
172#[instrument(skip(prog_track, settings))]
173#[allow(clippy::too_many_arguments)]
174async fn hard_link_entry_fd(
175    prog_track: &'static progress::Progress,
176    src_handle: &crate::safedir::Handle,
177    dst_dir: &Arc<Dir>,
178    dst_name: &std::ffi::OsStr,
179    dst_path: &std::path::Path,
180    settings: &Settings,
181) -> Result<Summary, Error> {
182    let mut link_summary = Summary::default();
183    match dst_dir.hard_link_handle_at(src_handle, dst_name).await {
184        Ok(()) => {}
185        Err(error)
186            if settings.copy_settings.overwrite
187                && error.kind() == std::io::ErrorKind::AlreadyExists =>
188        {
189            tracing::debug!("'dst' already exists, check if we need to update");
190            let dst_handle = dst_dir
191                .child(dst_name)
192                .await
193                .with_context(|| format!("cannot read {dst_path:?} metadata"))
194                .map_err(|err| Error::new(err, Default::default()))?;
195            // identical hard link: same file type and same (dev, ino) as the source entry. Both
196            // handles pin their inodes (O_PATH), so a matching (dev, ino) genuinely proves the two
197            // names already resolve to the same inode — no change needed.
198            if dst_handle.kind() == src_handle.kind()
199                && dst_handle.dev() == src_handle.dev()
200                && dst_handle.ino() == src_handle.ino()
201            {
202                tracing::debug!("no change, leaving file as is");
203                prog_track.hard_links_unchanged.inc();
204                return Ok(Summary {
205                    hard_links_unchanged: 1,
206                    ..Default::default()
207                });
208            }
209            tracing::info!("'dst' file type changed, removing and hard-linking");
210            // fd-relative removal is contained to dst_dir (mirrors copy.rs).
211            let rm_summary = copy::remove_existing(
212                prog_track,
213                dst_dir,
214                dst_name,
215                dst_path,
216                dst_handle.into_removal_snapshot(),
217                &settings.copy_settings,
218            )
219            .await
220            .map_err(|err| {
221                link_summary.copy_summary.rm_summary = err.summary.rm_summary;
222                Error::new(err.source, link_summary)
223            })?;
224            link_summary.copy_summary.rm_summary = rm_summary;
225            dst_dir
226                .hard_link_handle_at(src_handle, dst_name)
227                .await
228                .with_context(|| format!("failed to hard link to {dst_path:?}"))
229                .map_err(|err| Error::new(err, link_summary))?;
230        }
231        Err(error) => {
232            return Err(Error::new(
233                anyhow::Error::from(error).context(format!("failed to hard link to {dst_path:?}")),
234                link_summary,
235            ));
236        }
237    }
238    prog_track.hard_links_created.inc();
239    link_summary.hard_links_created = 1;
240    Ok(link_summary)
241}
242
243/// Public entry point for link operations.
244///
245/// The dual-tree link walk is fd-based: the source, optional `update`, and destination roots are
246/// opened relative to their parent directories and every per-entry operation is performed through
247/// file-descriptor-relative syscalls (see [`crate::safedir`]). Hard links are made inode-exact
248/// through the already-classified source `Handle` (`linkat` via `/proc/self/fd/N` with
249/// `AT_SYMLINK_FOLLOW`), so the link targets the exact regular file that was classified, even if
250/// its directory entry is concurrently swapped — never a re-resolved name; entries that must be
251/// copied instead of hard-linked are delegated to `copy::copy_child` with the held parent `Dir`s —
252/// no path is re-resolved from a root. The held parents prevent full-path redirection and contain
253/// each by-name operation, while the pinned source handle makes hard-link creation inode-exact.
254/// `--dereference` is the one exception — copy still resolves symlinks by path (`canonicalize`) and
255/// is not hardened.
256#[instrument(skip(prog_track, settings))]
257pub async fn link(
258    prog_track: &'static progress::Progress,
259    cwd: &std::path::Path,
260    src: &std::path::Path,
261    dst: &std::path::Path,
262    update: &Option<std::path::PathBuf>,
263    settings: &Settings,
264    is_fresh: bool,
265) -> Result<Summary, Error> {
266    crate::task_scope::scope_tasks(link_inner(
267        prog_track, cwd, src, dst, update, settings, is_fresh,
268    ))
269    .await
270}
271
272#[cfg(test)]
273type AfterUpdatePrecheckHook = Box<dyn FnOnce() + Send>;
274
275#[cfg(test)]
276static AFTER_UPDATE_PRECHECK_HOOKS: std::sync::LazyLock<
277    std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, AfterUpdatePrecheckHook>>,
278> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
279
280#[cfg(test)]
281struct AfterUpdatePrecheckHookRegistration {
282    update_path: std::path::PathBuf,
283}
284
285#[cfg(test)]
286impl Drop for AfterUpdatePrecheckHookRegistration {
287    fn drop(&mut self) {
288        AFTER_UPDATE_PRECHECK_HOOKS
289            .lock()
290            .unwrap_or_else(std::sync::PoisonError::into_inner)
291            .remove(&self.update_path);
292    }
293}
294
295#[cfg(test)]
296fn install_after_update_precheck_hook(
297    update_path: std::path::PathBuf,
298    hook: AfterUpdatePrecheckHook,
299) -> AfterUpdatePrecheckHookRegistration {
300    let replaced = AFTER_UPDATE_PRECHECK_HOOKS
301        .lock()
302        .unwrap_or_else(std::sync::PoisonError::into_inner)
303        .insert(update_path.clone(), hook);
304    assert!(replaced.is_none(), "update precheck hook already installed");
305    AfterUpdatePrecheckHookRegistration { update_path }
306}
307
308#[cfg(test)]
309fn run_after_update_precheck_hook(update_path: &std::path::Path) {
310    let hook = AFTER_UPDATE_PRECHECK_HOOKS
311        .lock()
312        .unwrap_or_else(std::sync::PoisonError::into_inner)
313        .remove(update_path);
314    if let Some(hook) = hook {
315        hook();
316    }
317}
318
319async fn link_inner(
320    prog_track: &'static progress::Progress,
321    cwd: &std::path::Path,
322    src: &std::path::Path,
323    dst: &std::path::Path,
324    update: &Option<std::path::PathBuf>,
325    settings: &Settings,
326    is_fresh: bool,
327) -> Result<Summary, Error> {
328    // `cwd` is retained for API/signature parity (callers still pass it) but the fd-based walk
329    // reconstructs every path from the explicit roots, so it is no longer threaded into the walk.
330    let _ = cwd;
331    let update_root_requirement = UpdateRootRequirement::from_settings(settings);
332    // reserve root admission before any strict probe or operand-parent open, then transfer it into
333    // link_internal. an authoritative directory releases it before dual-tree descent.
334    let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
335    enum LinkRootSetup {
336        Complete(Summary),
337        Ready {
338            src_operand: crate::walk::RootOperand,
339            src_parent: Arc<Dir>,
340            dst_parent: Option<Arc<Dir>>,
341            update_parent: Option<(Arc<Dir>, std::ffi::OsString)>,
342            admission: LinkEntryAdmission,
343        },
344    }
345    let setup_admission = permit.as_ref().map(LeafPermit::admission);
346    let setup = safedir::with_optional_fd_admission(setup_admission, async move {
347        // a missing --update root is destructive under both --update-exclusive (materialized set =
348        // update set, so nothing materializes) AND --delete (the source-only keep-set makes any dst
349        // entry the missing update tree WOULD have protected look extraneous, and prune wipes it).
350        // in either case `link_internal` hits the recursive early-return / silent `None` fallback
351        // before that destruction would happen, so rlink reports success — silently preserving
352        // stale dst (--update-exclusive) or silently pruning would-be-protected entries (--delete).
353        // reject up front so the usual error ordering catches a typo'd --update before later operand
354        // work. The same typed requirement is retained through the authoritative root classification,
355        // closing the race after this probe. Plain "--update without --delete or --update-exclusive"
356        // still falls back to no-update mode, and recursive child-level "update missing" cases remain
357        // ordinary no-op/source-only decisions.
358        if let Some(update_path) = update.as_ref() {
359            if crate::safedir::strict_operand_resolution() {
360                // under strict operand resolution, validate the update operand prefix UP FRONT
361                // (fd-relative, `openat2(RESOLVE_NO_SYMLINKS)`), unconditionally for ALL --update — so a
362                // plain --update with an excluded source (which returns before the update parent would
363                // otherwise be opened) cannot slip a symlinked update prefix through. A symlink in a
364                // directory component fails closed (ELOOP); this also serves the destructive-mode
365                // existence check below.
366                let kind =
367                    crate::safedir::strict_probe_dst_kind(update_path, congestion::Side::Source)
368                        .await
369                        .map_err(|err| {
370                            Error::new(
371                                anyhow::Error::new(err).context(format!(
372                                    "failed reading metadata from update {update_path:?}"
373                                )),
374                                Default::default(),
375                            )
376                        })?;
377                if update_root_requirement.is_required() && kind.is_none() {
378                    return Err(missing_destructive_update_error(update_path));
379                }
380            } else if update_root_requirement.is_required() {
381                match crate::walk::run_metadata_probed(
382                    congestion::Side::Source,
383                    congestion::MetadataOp::Stat,
384                    tokio::fs::symlink_metadata(update_path),
385                )
386                .await
387                {
388                    Ok(_) => {}
389                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
390                        return Err(missing_destructive_update_error(update_path));
391                    }
392                    Err(err) => {
393                        return Err(Error::new(
394                            anyhow::Error::new(err).context(format!(
395                                "failed reading metadata from update {:?}",
396                                update_path
397                            )),
398                            Default::default(),
399                        ));
400                    }
401                }
402            }
403        }
404        #[cfg(test)]
405        if let Some(update_path) = update.as_ref() {
406            run_after_update_precheck_hook(update_path);
407        }
408        // source: decompose via the shared helper so `.`/`..` operands (e.g. `rlink . dst`, `rlink
409        // tree/.. dst`) are canonicalized to a real directory + basename instead of being rejected; `/`
410        // is still rejected. (The destination and `--update` operands keep their direct split below.)
411        let src_operand = crate::walk::split_root_operand(src)
412            .await
413            .map_err(|err| Error::new(err, Default::default()))?;
414        let src = src_operand.display.as_path();
415        let src_name = src_operand.name.as_os_str();
416        // under strict operand resolution (--require-toctou-safe) the parent prefix is opened BEFORE
417        // the root filter check, so a symlinked source prefix fails closed even when the root would be
418        // skipped by a filter, and the root is classified fd-relative. On the default path the filter
419        // check keeps the historical path-based `symlink_metadata` classification and runs FIRST: an
420        // excluded root under an execute-only (0111, searchable-not-readable) parent must skip cleanly,
421        // and the O_RDONLY parent open would fail EACCES there.
422        let strict_src_parent: Option<Arc<Dir>> = if crate::safedir::strict_operand_resolution() {
423            let parent = Dir::open_parent_dir(&src_operand.parent, congestion::Side::Source)
424                .await
425                .with_context(|| {
426                    format!(
427                        "cannot open source parent directory {:?}",
428                        src_operand.parent
429                    )
430                })
431                .map_err(|err| Error::new(err, Default::default()))?;
432            // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below here).
433            Some(Arc::new(parent.into_tree()))
434        } else {
435            None
436        };
437        // the destination's parent path, split leniently for the up-front strict validation below (a
438        // `.`/`..`/`/` destination has no distinct parent+name; the authoritative split — which rejects
439        // such a destination — runs AFTER the filter, preserving default-mode ordering so a filtered-out
440        // source still skips cleanly). empty parent (a single-component relative path) means ".".
441        let dst_parent_path_opt: Option<&std::path::Path> = match (dst.parent(), dst.file_name()) {
442            (Some(parent), Some(_)) if parent.as_os_str().is_empty() => {
443                Some(std::path::Path::new("."))
444            }
445            (Some(parent), Some(_)) => Some(parent),
446            _ => None,
447        };
448        // under strict operand resolution, resolve the destination parent UP FRONT — before the source
449        // root-filter early-return, unconditionally — so a symlinked destination prefix fails closed in
450        // every mode regardless of filters/flags (see copy::copy for the same pattern). An absent parent
451        // (dry-run previewing into a not-yet-created tree, or a filtered-out root) is not a symlink
452        // violation; only a symlinked prefix component (ELOOP) fails closed here.
453        let strict_dst_parent: Option<Arc<Dir>> = match (
454            crate::safedir::strict_operand_resolution(),
455            dst_parent_path_opt,
456        ) {
457            (true, Some(dst_parent_path)) => {
458                match Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination).await {
459                    Ok(parent) => Some(Arc::new(parent.into_tree())),
460                    Err(err)
461                        if err.kind() == std::io::ErrorKind::NotFound
462                            || err.raw_os_error() == Some(libc::ENOTDIR) =>
463                    {
464                        None
465                    }
466                    Err(err) => {
467                        return Err(Error::new(
468                            anyhow::Error::new(err).context(format!(
469                                "cannot open destination parent directory {dst_parent_path:?}"
470                            )),
471                            Default::default(),
472                        ));
473                    }
474                }
475            }
476            // default mode, or a degenerate destination (rejected by the authoritative split below)
477            _ => None,
478        };
479        // in default mode a dual root may take the same metadata-only exclusion fast path as a
480        // source-only root. Both physical operands are one logical item in the source namespace,
481        // so evaluate both types under `src_name`; the update operand's basename is irrelevant.
482        // This path may only exclude. Every provisional include falls through to the fd-relative
483        // joint recheck below, and metadata errors also fall through so the existing parent-open /
484        // authoritative-classification error precedence remains unchanged.
485        if strict_src_parent.is_none()
486            && let (Some(filter), Some(update_path)) = (settings.filter.as_ref(), update.as_ref())
487        {
488            let src_metadata = crate::walk::run_metadata_probed(
489                congestion::Side::Source,
490                congestion::MetadataOp::Stat,
491                tokio::fs::symlink_metadata(src),
492            )
493            .await;
494            let update_metadata = crate::walk::run_metadata_probed(
495                congestion::Side::Source,
496                congestion::MetadataOp::Stat,
497                tokio::fs::symlink_metadata(update_path),
498            )
499            .await;
500            if let (Ok(src_metadata), Ok(update_metadata)) = (src_metadata, update_metadata)
501                && let RootFilterSelection::Skip { kind, result } = select_filtered_root(
502                    filter,
503                    src_name,
504                    EntryKind::from_metadata(&src_metadata),
505                    Some(EntryKind::from_metadata(&update_metadata)),
506                    settings.update_exclusive,
507                )
508            {
509                if let Some(mode) = settings.dry_run {
510                    crate::dry_run::report_skip(src, &result, mode, kind.label_long());
511                }
512                kind.inc_skipped(prog_track);
513                return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
514            }
515        }
516        // a source-only root preserves the historical cheap early filter. a dual root that was not
517        // conclusively excluded above defers to the joint fd-relative setup decision after both
518        // handles are classified.
519        if update.is_none()
520            && let Some(ref filter) = settings.filter
521        {
522            let (kind, is_dir) = match &strict_src_parent {
523                // strict: classify via the held parent fd (O_NOFOLLOW), never by path
524                Some(parent) => {
525                    let root_handle = parent
526                        .child(src_name)
527                        .await
528                        .with_context(|| format!("failed reading metadata from {:?}", &src))
529                        .map_err(|err| Error::new(err, Default::default()))?;
530                    (root_handle.kind(), root_handle.kind() == EntryKind::Dir)
531                }
532                None => {
533                    let src_metadata = crate::walk::run_metadata_probed(
534                        congestion::Side::Source,
535                        congestion::MetadataOp::Stat,
536                        tokio::fs::symlink_metadata(src),
537                    )
538                    .await
539                    .with_context(|| format!("failed reading metadata from {:?}", &src))
540                    .map_err(|err| Error::new(err, Default::default()))?;
541                    (
542                        EntryKind::from_metadata(&src_metadata),
543                        src_metadata.is_dir(),
544                    )
545                }
546            };
547            let result = filter.should_include_root_item(std::path::Path::new(src_name), is_dir);
548            match result {
549                crate::filter::FilterResult::Included => {}
550                result => {
551                    if let Some(mode) = settings.dry_run {
552                        crate::dry_run::report_skip(src, &result, mode, kind.label_long());
553                    }
554                    kind.inc_skipped(prog_track);
555                    return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
556                }
557            }
558        }
559        // open the parent directories of the source and (optional) update roots for the
560        // walk so each root entry is opened and classified relative to a directory fd — the same
561        // fd-relative path every nested entry takes. The roots are then handed to `link_internal` by
562        // their basenames, exactly like child entries. under strict operand resolution the source
563        // parent was already opened and validated above, so reuse its held fd here.
564        let src_parent = match strict_src_parent {
565            Some(parent) => parent,
566            None => {
567                let parent = Dir::open_parent_dir(&src_operand.parent, congestion::Side::Source)
568                    .await
569                    .with_context(|| {
570                        format!(
571                            "cannot open source parent directory {:?}",
572                            src_operand.parent
573                        )
574                    })
575                    .map_err(|err| Error::new(err, Default::default()))?;
576                // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below here).
577                Arc::new(parent.into_tree())
578            }
579        };
580        // the update tree (if present) is rooted at `update`; open its parent and remember the root
581        // basename so setup can classify it via the held fd. A missing root/parent silently falls
582        // back only for optional plain update; destructive delete/update or update-exclusive is
583        // enforced again by the authoritative typed requirement.
584        //
585        // for plain `--update` (no `--delete`, no `--update-exclusive`) a missing parent is treated the
586        // same as a missing update root: fall back silently to no-update mode. This preserves the long-
587        // standing behavior where `rlink --update /tmp/no/such src dst` (with `/tmp/no` absent) proceeds
588        // by linking from `src` rather than erroring — the existing missing-update-root fallback already
589        // applies to that case; the parent-open merely must not ENOENT-fail before `link_internal` can
590        // apply it. Under `--delete` or `--update-exclusive`, parent failure propagates and root absence
591        // is rejected again by whichever authoritative root classification site retains the handle.
592        let update_parent = match update.as_ref() {
593            Some(update_path) => {
594                // decompose the update operand the same way as the source: the update tree is a READ
595                // tree, so `.`/`..`/`dir/..` are meaningful and `split_root_operand` canonicalizes them
596                // (and rejects `/`). This makes `rlink --update . src dst` / `--update tree/.. src dst`
597                // work instead of erroring, matching the source-operand handling. The helper already
598                // normalizes an empty parent to ".", so no `resolve_parent` is needed here.
599                let update_operand = crate::walk::split_root_operand(update_path)
600                    .await
601                    .map_err(|err| Error::new(err, Default::default()))?;
602                let update_parent_path = update_operand.parent;
603                let update_name = update_operand.name;
604                // the update tree's TRUSTED parent prefix is resolved following symlinks (see the
605                // source parent above): a symlinked update container must be followed into the real dir.
606                let fallback_eligible = !update_root_requirement.is_required();
607                match Dir::open_parent_dir(&update_parent_path, congestion::Side::Source).await {
608                    // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below).
609                    Ok(dir) => Some((Arc::new(dir.into_tree()), update_name)),
610                    Err(err)
611                        if fallback_eligible
612                            && (matches!(
613                                err.kind(),
614                                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
615                            ) || err.raw_os_error() == Some(libc::ENOTDIR)) =>
616                    {
617                        // the update path's parent (or an ancestor) doesn't exist — treat the whole
618                        // update tree as absent and fall back to no-update mode, exactly as when the
619                        // update ROOT itself is missing (handled inside link_internal).
620                        tracing::debug!(
621                            "update parent {:?} not found ({:#}); falling back to no-update mode",
622                            update_parent_path,
623                            err
624                        );
625                        None
626                    }
627                    Err(err) => {
628                        return Err(Error::new(
629                            anyhow::Error::new(err).context(format!(
630                                "cannot open update parent directory {:?}",
631                                update_parent_path
632                            )),
633                            Default::default(),
634                        ));
635                    }
636                }
637            }
638            None => None,
639        };
640        // a dual root must be filtered before destination validation, and its type authorization must
641        // stay bound to the exact handles that informed it. classify both roots once, select the
642        // surviving side, and thread those handles into link_internal; same-class file/directory
643        // payloads retain their documented by-name semantics below that authorization boundary.
644        let admission = match (settings.filter.as_ref(), update.as_ref()) {
645            (Some(filter), Some(update_path)) => {
646                let src_handle = src_parent
647                    .child(src_name)
648                    .await
649                    .with_context(|| format!("failed reading metadata from {src:?}"))
650                    .map_err(|err| Error::new(err, Default::default()))?;
651                let mut entry = AdmittedLinkEntry::new(src_handle, permit);
652                entry.update_handle = match update_parent.as_ref() {
653                    Some((parent, update_name)) => update_root_requirement
654                        .classify(parent.child(update_name).await, update_path)?,
655                    None => None,
656                };
657                if settings.update_exclusive && entry.update_handle.is_none() {
658                    return Ok(LinkRootSetup::Complete(Default::default()));
659                }
660                match select_filtered_root(
661                    filter,
662                    src_name,
663                    entry.src_handle.kind(),
664                    entry.update_handle.as_ref().map(Handle::kind),
665                    settings.update_exclusive,
666                ) {
667                    RootFilterSelection::SourceOnly => entry.update_handle = None,
668                    RootFilterSelection::WithUpdate => {}
669                    RootFilterSelection::Skip { kind, result } => {
670                        if let Some(mode) = settings.dry_run {
671                            crate::dry_run::report_skip(src, &result, mode, kind.label_long());
672                        }
673                        kind.inc_skipped(prog_track);
674                        return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
675                    }
676                }
677                LinkEntryAdmission::Filtered(entry)
678            }
679            _ => LinkEntryAdmission::from(EntryAdmission::from(permit)),
680        };
681        // authoritative destination split runs only after every applicable root filter. a `.`/`..`/`/`
682        // destination is not a meaningful link target, and rejecting it avoids clobbering the cwd.
683        // empty parent (a single-component relative path) means the current directory.
684        let (Some(dst_parent_path), Some(_dst_name)) = (dst.parent(), dst.file_name()) else {
685            return Err(Error::new(
686                anyhow!(
687                    "link destination {:?} has no parent directory or file name",
688                    dst
689                ),
690                Default::default(),
691            ));
692        };
693        let dst_parent_path = if dst_parent_path.as_os_str().is_empty() {
694            std::path::Path::new(".")
695        } else {
696            dst_parent_path
697        };
698        // one `listxattr` on the source ROOT per run — a constant, not a per-entry probe — warning that
699        // a source root carrying an ACL is about to be linked by settings that drop it. WITHOUT
700        // `--update`, files count as already safe whatever `f:acl` says: a hard-linked destination
701        // file IS the source inode, so its ACL cannot be dropped (and must never be written through,
702        // which is why `f:acl` applies only on rlink's real copy path). WITH `--update` that certainty
703        // is gone — a changed file is materialized by COPYING the update-tree entry, which drops its
704        // acl unless `f:acl` is on — so the file half then defers to the setting like any copy. (the
705        // probe still examines the SOURCE root; whether the update entry differs — and so whether the
706        // copy path actually runs — is not known yet, matching the probe's documented
707        // root-only-heuristic character.) whether the notice is wanted AT ALL still comes from the
708        // preserve settings, which for rlink default to `all` — metadata fidelity is what the tool is
709        // for — so a bare `rlink` asks for it where a bare `rcp` does not.
710        let root_acl_notice = crate::safedir::RootAclNotice {
711            file_acl_preserved: update.is_none() || settings.preserve.file.acl,
712            ..crate::safedir::RootAclNotice::for_preserve(&settings.preserve)
713        };
714        match &admission {
715            LinkEntryAdmission::Filtered(entry) => {
716                crate::safedir::warn_if_root_acl_unpreserved(
717                    &entry.src_handle,
718                    src,
719                    root_acl_notice,
720                )
721                .await;
722            }
723            LinkEntryAdmission::Unclassified { .. } => {
724                crate::safedir::warn_if_root_acl_unpreserved_at(
725                    &src_parent,
726                    src_name,
727                    src,
728                    root_acl_notice,
729                )
730                .await;
731            }
732        }
733        // in dry-run we never touch the destination, so we don't open its parent at all (it may not
734        // even exist). `dst_parent == None` is the signal throughout the walk that destination
735        // operations must be skipped. in a real link, reuse the strict-validated parent, or open it
736        // following symlinks (default mode; a symlinked destination container is followed into the real
737        // dir).
738        let dst_parent = if settings.dry_run.is_some() {
739            None
740        } else {
741            match strict_dst_parent {
742                Some(parent) => Some(parent),
743                None => {
744                    let dir = Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination)
745                        .await
746                        .with_context(|| {
747                            format!(
748                                "cannot open destination parent directory {:?}",
749                                dst_parent_path
750                            )
751                        })
752                        .map_err(|err| Error::new(err, Default::default()))?;
753                    // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below).
754                    Some(Arc::new(dir.into_tree()))
755                }
756            }
757        };
758        Ok(LinkRootSetup::Ready {
759            src_operand,
760            src_parent,
761            dst_parent,
762            update_parent,
763            admission,
764        })
765    })
766    .await?;
767    let (src_operand, src_parent, dst_parent, update_parent, admission) = match setup {
768        LinkRootSetup::Complete(summary) => return Ok(summary),
769        LinkRootSetup::Ready {
770            src_operand,
771            src_parent,
772            dst_parent,
773            update_parent,
774            admission,
775        } => (
776            src_operand,
777            src_parent,
778            dst_parent,
779            update_parent,
780            admission,
781        ),
782    };
783    let src = src_operand.display.as_path();
784    let src_name = src_operand.name.as_os_str();
785    let update_ref = update_parent
786        .as_ref()
787        .map(|(dir, name)| (dir, name.as_os_str()));
788    link_internal(
789        prog_track,
790        &src_parent,
791        update_ref,
792        dst_parent.as_ref(),
793        src_name,
794        src,
795        dst,
796        update.as_deref(),
797        std::path::Path::new(""),
798        update_root_requirement,
799        settings,
800        is_fresh,
801        admission,
802        copy::DeleteScanAnchor::new(dst, std::path::Path::new("")),
803    )
804    .await
805    .map(|result| result.summary)
806}
807/// Keeps both comparison handles structurally ahead of their shared admission permit.
808struct AdmittedLinkEntry<S = Handle, U = Handle, P = LeafPermit> {
809    src_handle: S,
810    update_handle: Option<U>,
811    permit: Option<P>,
812}
813
814/// Owns exactly one link entry's classification and admission state.
815enum LinkEntryAdmission {
816    Unclassified {
817        admission: EntryAdmission,
818        hinted_src_handle: Option<Handle>,
819    },
820    Filtered(AdmittedLinkEntry),
821}
822
823/// One exact link-entry decision and the destination-protection bit it authorizes.
824struct LinkEntryResult {
825    summary: Summary,
826    protect_destination: bool,
827}
828
829impl LinkEntryResult {
830    fn selected(summary: Summary) -> Self {
831        Self {
832            summary,
833            protect_destination: true,
834        }
835    }
836
837    fn filtered(summary: Summary) -> Self {
838        Self {
839            summary,
840            protect_destination: false,
841        }
842    }
843}
844
845/// Result folded from one spawned source/update entry.
846struct LinkTaskResult {
847    summary: Summary,
848    keep_name: Option<std::ffi::OsString>,
849}
850
851impl LinkTaskResult {
852    fn from_link(name: std::ffi::OsString, result: LinkEntryResult) -> Self {
853        Self {
854            summary: result.summary,
855            keep_name: result.protect_destination.then_some(name),
856        }
857    }
858
859    fn from_update(name: std::ffi::OsString, result: LinkEntryResult) -> Self {
860        Self::from_link(name, result)
861    }
862
863    fn fold(self, summary: &mut Summary, outcomes: &mut LinkChildOutcomes) {
864        if let Some(name) = self.keep_name {
865            outcomes.record_exact(name);
866        }
867        *summary = *summary + self.summary;
868    }
869}
870
871impl LinkEntryAdmission {
872    fn admission(&self) -> Option<throttle::FdAdmission> {
873        match self {
874            Self::Unclassified { admission, .. } => admission.admission(),
875            Self::Filtered(entry) => entry.permit.as_ref().map(LeafPermit::admission),
876        }
877    }
878}
879
880impl From<EntryAdmission> for LinkEntryAdmission {
881    fn from(admission: EntryAdmission) -> Self {
882        Self::Unclassified {
883            admission,
884            hinted_src_handle: None,
885        }
886    }
887}
888
889/// Select which side of a dual-root entry survives its joint filter decision.
890enum RootFilterSelection {
891    SourceOnly,
892    WithUpdate,
893    Skip {
894        kind: EntryKind,
895        result: crate::filter::FilterResult,
896    },
897}
898
899/// Filter a link root once in its source-root-relative namespace using both authoritative types.
900fn select_filtered_root(
901    filter: &crate::filter::FilterSettings,
902    logical_name: &std::ffi::OsStr,
903    src_kind: EntryKind,
904    update_kind: Option<EntryKind>,
905    update_exclusive: bool,
906) -> RootFilterSelection {
907    let logical_name = std::path::Path::new(logical_name);
908    let src_result = filter.should_include_root_item(logical_name, src_kind == EntryKind::Dir);
909    let src_included = matches!(&src_result, crate::filter::FilterResult::Included);
910    let Some(update_kind) = update_kind else {
911        return if src_included {
912            RootFilterSelection::SourceOnly
913        } else {
914            RootFilterSelection::Skip {
915                kind: src_kind,
916                result: src_result,
917            }
918        };
919    };
920    let update_result =
921        filter.should_include_root_item(logical_name, update_kind == EntryKind::Dir);
922    if matches!(&update_result, crate::filter::FilterResult::Included) {
923        RootFilterSelection::WithUpdate
924    } else if !update_exclusive && src_included {
925        RootFilterSelection::SourceOnly
926    } else {
927        let (kind, result) = if update_exclusive {
928            (update_kind, update_result)
929        } else {
930            (src_kind, src_result)
931        };
932        RootFilterSelection::Skip { kind, result }
933    }
934}
935
936/// Select which exact side of a nested dual-tree entry survives its filter decision.
937fn select_filtered_nested(
938    filter: &crate::filter::FilterSettings,
939    logical_path: &std::path::Path,
940    src_kind: EntryKind,
941    update_kind: Option<EntryKind>,
942    update_exclusive: bool,
943) -> RootFilterSelection {
944    let src_result = filter.should_include(logical_path, src_kind == EntryKind::Dir);
945    let src_included = matches!(&src_result, crate::filter::FilterResult::Included);
946    let Some(update_kind) = update_kind else {
947        return if src_included {
948            RootFilterSelection::SourceOnly
949        } else {
950            RootFilterSelection::Skip {
951                kind: src_kind,
952                result: src_result,
953            }
954        };
955    };
956    let update_result = filter.should_include(logical_path, update_kind == EntryKind::Dir);
957    if matches!(&update_result, crate::filter::FilterResult::Included) {
958        RootFilterSelection::WithUpdate
959    } else if !update_exclusive && src_included {
960        RootFilterSelection::SourceOnly
961    } else {
962        let (kind, result) = if update_exclusive {
963            (update_kind, update_result)
964        } else {
965            (src_kind, src_result)
966        };
967        RootFilterSelection::Skip { kind, result }
968    }
969}
970
971fn drop_link_handles_before_permit<S, U, P>(
972    src_handle: S,
973    update_handle: Option<U>,
974    permit: Option<P>,
975) {
976    drop(src_handle);
977    drop(update_handle);
978    drop(permit);
979}
980
981impl AdmittedLinkEntry<Handle, Handle, LeafPermit> {
982    fn new(src_handle: Handle, permit: Option<LeafPermit>) -> Self {
983        Self {
984            src_handle,
985            update_handle: None,
986            permit,
987        }
988    }
989
990    // the directory outcome returns the original private bundle so its two handles can be closed
991    // before the permit. boxing that expected recursive transition would allocate per directory.
992    #[allow(clippy::result_large_err)]
993    fn into_source_leaf(self) -> Result<AdmittedLeaf, Self> {
994        let Self {
995            src_handle,
996            update_handle,
997            permit,
998        } = self;
999        match AdmittedLeaf::try_new(src_handle, permit) {
1000            Ok(leaf) => {
1001                drop(update_handle);
1002                Ok(leaf)
1003            }
1004            Err((src_handle, permit)) => Err(Self {
1005                src_handle,
1006                update_handle,
1007                permit,
1008            }),
1009        }
1010    }
1011
1012    fn into_update_entry(self) -> AdmittedEntry {
1013        let Self {
1014            src_handle,
1015            update_handle,
1016            permit,
1017        } = self;
1018        drop(src_handle);
1019        let update_handle =
1020            update_handle.expect("update action requires a classified update entry");
1021        AdmittedEntry::new(update_handle, permit)
1022    }
1023
1024    fn into_source_entry(self) -> AdmittedEntry {
1025        let Self {
1026            src_handle,
1027            update_handle,
1028            permit,
1029        } = self;
1030        drop(update_handle);
1031        AdmittedEntry::new(src_handle, permit)
1032    }
1033
1034    fn close_for_directory(self) -> bool {
1035        let Self {
1036            src_handle,
1037            update_handle,
1038            permit,
1039        } = self;
1040        let has_update_dir = update_handle
1041            .as_ref()
1042            .is_some_and(|handle| handle.kind() == EntryKind::Dir);
1043        drop_link_handles_before_permit(src_handle, update_handle, permit);
1044        has_update_dir
1045    }
1046}
1047
1048/// Process one entry in the dual source/update tree.
1049///
1050/// The source entry is classified via `src_parent.child(name)` (fstat-authoritative; the getdents
1051/// hint is only a spawn-loop heuristic). When an update entry exists at this name it is classified
1052/// too, and the hard-link-vs-copy decision mirrors the old `--update` overlay logic exactly:
1053/// a type mismatch, changed file, or symlink in the update tree is copied from the update version
1054/// via [`copy::copy_child`]; an unchanged file is hard-linked from the source; a directory recurses
1055/// through the dual tree. With no update tree, a source file is hard-linked, a source symlink is
1056/// copied, and a directory recurses.
1057///
1058/// `admission` is the explicit scheduling state supplied by the directory loop. Every
1059/// leaf-dispatch branch retains a held permit through its final fd-bearing work, including nested
1060/// overwrite removal; direct directory recursion releases it before descent, while delegated copy
1061/// consumes the already-classified update entry and owns its leaf-or-directory transition.
1062#[instrument(skip(prog_track, src_parent, update, dst_parent, settings, admission))]
1063#[async_recursion]
1064#[allow(clippy::too_many_arguments)]
1065async fn link_internal(
1066    prog_track: &'static progress::Progress,
1067    src_parent: &Arc<Dir>,
1068    update: Option<(&Arc<Dir>, &std::ffi::OsStr)>,
1069    dst_parent: Option<&Arc<Dir>>,
1070    name: &std::ffi::OsStr,
1071    src_root: &std::path::Path,
1072    dst_root: &std::path::Path,
1073    update_root: Option<&std::path::Path>,
1074    rel_path: &std::path::Path,
1075    update_root_requirement: UpdateRootRequirement,
1076    settings: &Settings,
1077    is_fresh: bool,
1078    admission: LinkEntryAdmission,
1079    delete_scan_parent: copy::DeleteScanAnchor,
1080) -> Result<LinkEntryResult, Error> {
1081    let _prog_guard = prog_track.ops.guard();
1082    // reconstruct diagnostic paths and the deliberately path-based dereference fallback.
1083    let src_path = walk::join_rel(src_root, rel_path);
1084    let dst_path = walk::join_rel(dst_root, rel_path);
1085    let update_path = update_root.map(|root| walk::join_rel(root, rel_path));
1086    // nested destination names equal the source name; a renamed root uses its destination basename.
1087    let dst_name = if rel_path.as_os_str().is_empty() {
1088        dst_root.file_name().ok_or_else(|| {
1089            Error::new(
1090                anyhow!("link destination {:?} has no file name", &dst_path),
1091                Default::default(),
1092            )
1093        })?
1094    } else {
1095        name
1096    };
1097    let mut admission = admission;
1098    if let LinkEntryAdmission::Unclassified {
1099        admission: entry_admission,
1100        hinted_src_handle,
1101    } = &mut admission
1102    {
1103        let current = std::mem::replace(entry_admission, EntryAdmission::RootOrDelegated);
1104        *entry_admission = if update.is_some() {
1105            current.require_admission()
1106        } else {
1107            current
1108        };
1109        // a positive source-directory hint gets one unadmitted classification only when no
1110        // separate update entry participates in the decision. if stale, close the first handle
1111        // before acquiring and reclassify inside the admitted worker region below.
1112        if matches!(entry_admission, EntryAdmission::HintedDirectory) {
1113            tracing::debug!("classifying hinted source entry");
1114            let handle = walk::classify_entry(src_parent, name)
1115                .await
1116                .with_context(|| format!("failed reading metadata from {:?}", &src_path))
1117                .map_err(|err| Error::new(err, Default::default()))?;
1118            if handle.kind() == EntryKind::Dir {
1119                *hinted_src_handle = Some(handle);
1120            } else {
1121                drop(handle);
1122                *entry_admission = EntryAdmission::RootOrDelegated;
1123            }
1124        }
1125        if hinted_src_handle.is_none() || update.is_some() {
1126            let current = std::mem::replace(entry_admission, EntryAdmission::RootOrDelegated);
1127            *entry_admission = walk::ensure_entry_admission(PermitKind::OpenFile, current).await;
1128        }
1129    }
1130    let weak_admission = admission.admission();
1131
1132    enum LinkDispatch {
1133        Complete(LinkEntryResult),
1134        Directory { has_update_dir: bool },
1135    }
1136
1137    let dispatch = safedir::with_optional_fd_admission(weak_admission, async {
1138        let (mut entry, root_filter_applied) = match admission {
1139            LinkEntryAdmission::Filtered(entry) => (entry, true),
1140            LinkEntryAdmission::Unclassified {
1141                admission,
1142                hinted_src_handle,
1143            } => {
1144                let src_handle = match hinted_src_handle {
1145                    Some(handle) => handle,
1146                    None => {
1147                        tracing::debug!("classifying source entry");
1148                        walk::classify_entry(src_parent, name)
1149                            .await
1150                            .with_context(|| {
1151                                format!("failed reading metadata from {:?}", &src_path)
1152                            })
1153                            .map_err(|err| Error::new(err, Default::default()))?
1154                    }
1155                };
1156                let mut entry = AdmittedLinkEntry::new(src_handle, admission.into_permit());
1157                // classify the update entry at this name (if an update tree is present at this
1158                // level). root absence is rejected when destructive settings require the operand;
1159                // nested absence remains the ordinary source-only / update-exclusive no-op case.
1160                entry.update_handle = match update {
1161                    Some((update_dir, update_name)) => {
1162                        tracing::debug!("classifying 'update' entry");
1163                        let update_path = update_path
1164                            .as_deref()
1165                            .expect("update directory present implies update path present");
1166                        update_root_requirement
1167                            .for_entry(rel_path)
1168                            .classify(update_dir.child(update_name).await, update_path)?
1169                    }
1170                    None => None,
1171                };
1172                if update.is_some() && settings.update_exclusive && entry.update_handle.is_none() {
1173                    return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1174                        Default::default(),
1175                    )));
1176                }
1177                (entry, false)
1178            }
1179        };
1180        // a root is one logical item in the source namespace even when the update operand has another
1181        // basename. decide from both fd-classified types together: normal mode is their filtered union,
1182        // while --update-exclusive selects only a filter-passing update side.
1183        if !root_filter_applied
1184            && rel_path.as_os_str().is_empty()
1185            && let Some(filter) = settings.filter.as_ref()
1186        {
1187            match select_filtered_root(
1188                filter,
1189                name,
1190                entry.src_handle.kind(),
1191                entry.update_handle.as_ref().map(Handle::kind),
1192                settings.update_exclusive,
1193            ) {
1194                RootFilterSelection::SourceOnly => entry.update_handle = None,
1195                RootFilterSelection::WithUpdate => {}
1196                RootFilterSelection::Skip { kind, result } => {
1197                    if let Some(mode) = settings.dry_run {
1198                        crate::dry_run::report_skip(&src_path, &result, mode, kind.label_long());
1199                    }
1200                    kind.inc_skipped(prog_track);
1201                    return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1202                        skipped_summary_for(kind),
1203                    )));
1204                }
1205            }
1206        // a nested source loop may have filtered from an advisory hint. Re-evaluate BOTH sides from
1207        // the exact handles that can drive materialization, so a later type swap cannot inherit that
1208        // earlier decision.
1209        } else if !rel_path.as_os_str().is_empty()
1210            && let Some(filter) = settings.filter.as_ref()
1211        {
1212            match select_filtered_nested(
1213                filter,
1214                rel_path,
1215                entry.src_handle.kind(),
1216                entry.update_handle.as_ref().map(Handle::kind),
1217                settings.update_exclusive,
1218            ) {
1219                RootFilterSelection::SourceOnly => entry.update_handle = None,
1220                RootFilterSelection::WithUpdate => {}
1221                RootFilterSelection::Skip { kind, result } => {
1222                    if let Some(mode) = settings.dry_run {
1223                        crate::dry_run::report_skip(&src_path, &result, mode, kind.label_long());
1224                    }
1225                    kind.inc_skipped(prog_track);
1226                    return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1227                        skipped_summary_for(kind),
1228                    )));
1229                }
1230            }
1231        }
1232        // from this point every leaf-dispatch action retains the private entry bundle or an
1233        // `AdmittedLeaf` through its final fd-bearing work, including nested overwrite removal. A
1234        // delegated update action closes the comparison source handle, then transfers the selected
1235        // update handle and permit together as one AdmittedEntry. copy consumes that exact owner through
1236        // the shared driver, including its directory drop-before-recursion transition. Direct dual-tree
1237        // directory recursion closes admission and both handles here.
1238        if let Some(update_entry) = entry.update_handle.as_ref() {
1239            let (update_dir, update_name) = update.unwrap();
1240            let update_path = update_path.as_deref().unwrap();
1241            if update_entry.kind() != entry.src_handle.kind() {
1242                // file type changed, just copy the updated one
1243                tracing::debug!(
1244                    "link: file type of {:?} ({:?}) and {:?} ({:?}) differs - copying from update",
1245                    src_path,
1246                    entry.src_handle.kind(),
1247                    update_path,
1248                    update_entry.kind()
1249                );
1250                // delegate at this entry's logical path so that, under --delete, pruning inside the
1251                // delegated subtree matches include/exclude descendants at the correct filter root
1252                // (e.g. `node/*.log`). Pass the held update parent + name and transfer the exact selected
1253                // update handle with its admission. The shared copy driver releases provisional
1254                // admission itself when that handle is an authoritative directory.
1255                let admission = entry.into_update_entry();
1256                return delegate_copy(
1257                    prog_track,
1258                    update_dir,
1259                    dst_parent,
1260                    update_name,
1261                    update_path,
1262                    dst_root,
1263                    rel_path,
1264                    delete_scan_parent.clone(),
1265                    settings,
1266                    is_fresh,
1267                    admission,
1268                )
1269                .await
1270                .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1271            }
1272            if update_entry.kind() == EntryKind::File {
1273                // check if the file is unchanged and if so hard-link, otherwise copy from the updated one
1274                if filecmp::metadata_equal(
1275                    &settings.update_compare,
1276                    entry.src_handle.meta(),
1277                    update_entry.meta(),
1278                ) {
1279                    // unchanged file: hard-link from src while retaining admission across `linkat`.
1280                    tracing::debug!("no change, hard link 'src'");
1281                    let leaf = match entry.into_source_leaf() {
1282                        Ok(leaf) => leaf,
1283                        Err(entry) => {
1284                            return Ok(LinkDispatch::Directory {
1285                                has_update_dir: entry.close_for_directory(),
1286                            });
1287                        }
1288                    };
1289                    if settings.dry_run.is_some() {
1290                        crate::dry_run::report_action("link", &src_path, Some(&dst_path), "file");
1291                        return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1292                            hard_links_created: 1,
1293                            ..Default::default()
1294                        })));
1295                    }
1296                    let dst_dir =
1297                        dst_parent.expect("destination parent must be open for a real hard link");
1298                    return hard_link_entry_fd(
1299                        prog_track,
1300                        leaf.handle(),
1301                        dst_dir,
1302                        dst_name,
1303                        &dst_path,
1304                        settings,
1305                    )
1306                    .await
1307                    .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1308                }
1309                tracing::debug!(
1310                    "link: {:?} metadata has changed, copying from {:?}",
1311                    src_path,
1312                    update_path
1313                );
1314                // changed file: delegate to copy, transferring the same admission guard.
1315                let admission = entry.into_update_entry();
1316                return delegate_copy(
1317                    prog_track,
1318                    update_dir,
1319                    dst_parent,
1320                    update_name,
1321                    update_path,
1322                    dst_root,
1323                    rel_path,
1324                    delete_scan_parent.clone(),
1325                    settings,
1326                    is_fresh,
1327                    admission,
1328                )
1329                .await
1330                .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1331            }
1332            if update_entry.kind() == EntryKind::Symlink {
1333                // update symlink: copy it under the same leaf admission guard, including any overwrite
1334                // removal it triggers
1335                tracing::debug!("'update' is a symlink so just symlink that");
1336                let admission = entry.into_update_entry();
1337                return delegate_copy(
1338                    prog_track,
1339                    update_dir,
1340                    dst_parent,
1341                    update_name,
1342                    update_path,
1343                    dst_root,
1344                    rel_path,
1345                    delete_scan_parent.clone(),
1346                    settings,
1347                    is_fresh,
1348                    admission,
1349                )
1350                .await
1351                .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1352            }
1353        } else {
1354            // update hasn't been specified (or is absent at this name): hard-link a source file or copy
1355            // a source symlink, retaining admission across all leaf work and nested overwrite removal
1356            tracing::debug!("no 'update' entry");
1357            if entry.src_handle.kind() == EntryKind::File {
1358                let leaf = match entry.into_source_leaf() {
1359                    Ok(leaf) => leaf,
1360                    Err(entry) => {
1361                        return Ok(LinkDispatch::Directory {
1362                            has_update_dir: entry.close_for_directory(),
1363                        });
1364                    }
1365                };
1366                if settings.dry_run.is_some() {
1367                    crate::dry_run::report_action("link", &src_path, Some(&dst_path), "file");
1368                    return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1369                        hard_links_created: 1,
1370                        ..Default::default()
1371                    })));
1372                }
1373                let dst_dir =
1374                    dst_parent.expect("destination parent must be open for a real hard link");
1375                return hard_link_entry_fd(
1376                    prog_track,
1377                    leaf.handle(),
1378                    dst_dir,
1379                    dst_name,
1380                    &dst_path,
1381                    settings,
1382                )
1383                .await
1384                .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1385            }
1386            if entry.src_handle.kind() == EntryKind::Symlink {
1387                tracing::debug!("'src' is a symlink so just symlink that");
1388                let admission = entry.into_source_entry();
1389                return delegate_copy(
1390                    prog_track,
1391                    src_parent,
1392                    dst_parent,
1393                    name,
1394                    &src_path,
1395                    dst_root,
1396                    rel_path,
1397                    delete_scan_parent.clone(),
1398                    settings,
1399                    is_fresh,
1400                    admission,
1401                )
1402                .await
1403                .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1404            }
1405        }
1406        if entry.src_handle.kind() != EntryKind::Dir {
1407            // special file (or unsupported type): retain admission until this branch returns and drops
1408            // the source/update classification handles.
1409            if settings.copy_settings.skip_specials {
1410                tracing::debug!(
1411                    "skipping special file {:?} (kind: {:?})",
1412                    src_path,
1413                    entry.src_handle.kind()
1414                );
1415                if let Some(mode) = settings.dry_run {
1416                    match mode {
1417                        crate::config::DryRunMode::Brief => {}
1418                        crate::config::DryRunMode::All => println!("skip special {:?}", src_path),
1419                        crate::config::DryRunMode::Explain => {
1420                            println!(
1421                                "skip special {:?} (unsupported file type: {:?})",
1422                                src_path,
1423                                entry.src_handle.kind()
1424                            );
1425                        }
1426                    }
1427                }
1428                prog_track.specials_skipped.inc();
1429                return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1430                    copy_summary: CopySummary {
1431                        specials_skipped: 1,
1432                        ..Default::default()
1433                    },
1434                    ..Default::default()
1435                })));
1436            }
1437            return Err(Error::new(
1438                anyhow!(
1439                    "copy: {:?} -> {:?} failed, unsupported src file type: {:?}",
1440                    src_path,
1441                    dst_path,
1442                    entry.src_handle.kind()
1443                ),
1444                Default::default(),
1445            ));
1446        }
1447        // directory: release before recursing the dual tree. this is rlink's direct counterpart to the
1448        // shared driver's drop-before-recurse boundary.
1449        debug_assert!(
1450            entry.update_handle.is_none()
1451                || entry.update_handle.as_ref().unwrap().kind() == EntryKind::Dir
1452        );
1453        // only drive the dual-tree update walk when an update directory entry actually exists at this
1454        // name. If `update_handle` is None (the update tree has no counterpart for this src dir, the
1455        // recursive "update missing" case), process this subtree in no-update mode: hard-link the whole
1456        // source subtree. Passing the parent update tuple here would make `link_dir_entry` try to
1457        // `open_dir` a non-existent update child.
1458        let has_update_dir = entry.close_for_directory();
1459        Ok(LinkDispatch::Directory { has_update_dir })
1460    })
1461    .await?;
1462    let has_update_dir = match dispatch {
1463        LinkDispatch::Complete(summary) => return Ok(summary),
1464        LinkDispatch::Directory { has_update_dir } => has_update_dir,
1465    };
1466    let update_for_dir = update.filter(|_| has_update_dir);
1467    let update_root_for_dir = update_root.filter(|_| has_update_dir);
1468    let update_path_for_dir = update_path.as_deref().filter(|_| has_update_dir);
1469    link_dir_entry(
1470        prog_track,
1471        src_parent,
1472        update_for_dir,
1473        dst_parent,
1474        name,
1475        dst_name,
1476        src_root,
1477        dst_root,
1478        update_root_for_dir,
1479        rel_path,
1480        &src_path,
1481        &dst_path,
1482        update_path_for_dir,
1483        settings,
1484        is_fresh,
1485        delete_scan_parent,
1486    )
1487    .await
1488    .map(LinkEntryResult::selected)
1489}
1490
1491/// Delegate a single entry to the fd-based copy ([`copy::copy_child`]), passing the HELD parent
1492/// directory handles plus the entry `name` for payload authority. Copy's documented dereference
1493/// and read-only preview exceptions still apply. `dst_root` retains the original destination
1494/// anchor; `filter_base` is the entry's logical relative path (so pruning inside the subtree
1495/// matches include/exclude patterns at the entry's true path). `delete_scan_anchor` independently
1496/// carries the held preview parent or its known absence. The returned copy
1497/// summary is folded into a link `Summary`.
1498#[allow(clippy::too_many_arguments)]
1499async fn delegate_copy(
1500    prog_track: &'static progress::Progress,
1501    src_parent: &Arc<Dir>,
1502    dst_parent: Option<&Arc<Dir>>,
1503    name: &std::ffi::OsStr,
1504    src_path: &std::path::Path,
1505    dst_root: &std::path::Path,
1506    filter_base: &std::path::Path,
1507    delete_scan_anchor: copy::DeleteScanAnchor,
1508    settings: &Settings,
1509    is_fresh: bool,
1510    admission: AdmittedEntry,
1511) -> Result<Summary, Error> {
1512    // link's dry-run mode owns whether a destination handle exists. Keep delegated copy behavior
1513    // aligned even for direct API callers that did not duplicate the mode into `copy_settings`;
1514    // the normal CLI path already agrees and pays no clone.
1515    let normalized_copy_settings =
1516        (settings.copy_settings.dry_run != settings.dry_run).then(|| {
1517            let mut copy_settings = settings.copy_settings.clone();
1518            copy_settings.dry_run = settings.dry_run;
1519            copy_settings
1520        });
1521    let copy_settings = normalized_copy_settings
1522        .as_ref()
1523        .unwrap_or(&settings.copy_settings);
1524    let copy_summary = copy::copy_child(
1525        prog_track,
1526        src_parent,
1527        dst_parent,
1528        name,
1529        src_path,
1530        dst_root,
1531        filter_base,
1532        copy_settings,
1533        &settings.preserve,
1534        is_fresh,
1535        delete_scan_anchor,
1536        admission,
1537    )
1538    .await
1539    .map_err(|err| {
1540        let copy_summary = err.summary;
1541        Error::new(
1542            err.source,
1543            Summary {
1544                copy_summary,
1545                ..Default::default()
1546            },
1547        )
1548    })?;
1549    Ok(Summary {
1550        copy_summary,
1551        ..Default::default()
1552    })
1553}
1554
1555/// Resolve (create / reuse / overwrite) the destination directory fd-relative, open the source
1556/// (and update) directories, then recurse via [`link_dir_contents`]. Mirrors copy's
1557/// [`copy::resolve_dst_dir`] for the overwrite branches (fd-relative, parent-contained removal).
1558#[allow(clippy::too_many_arguments)]
1559async fn link_dir_entry(
1560    prog_track: &'static progress::Progress,
1561    src_parent: &Arc<Dir>,
1562    update: Option<(&Arc<Dir>, &std::ffi::OsStr)>,
1563    dst_parent: Option<&Arc<Dir>>,
1564    name: &std::ffi::OsStr,
1565    dst_name: &std::ffi::OsStr,
1566    src_root: &std::path::Path,
1567    dst_root: &std::path::Path,
1568    update_root: Option<&std::path::Path>,
1569    rel_path: &std::path::Path,
1570    src_path: &std::path::Path,
1571    dst_path: &std::path::Path,
1572    update_path: Option<&std::path::Path>,
1573    settings: &Settings,
1574    is_fresh: bool,
1575    delete_scan_parent: copy::DeleteScanAnchor,
1576) -> Result<Summary, Error> {
1577    let src_dir = src_parent
1578        .open_dir(name)
1579        .await
1580        .with_context(|| format!("cannot open directory {:?} for reading", src_path))
1581        .map_err(|err| Error::new(err, Default::default()))?;
1582    let src_dir = Arc::new(src_dir);
1583    // open the update directory too (it has the same file type as src here — both are dirs).
1584    let update_dir = match update {
1585        Some((update_parent, update_name)) => {
1586            let dir = update_parent
1587                .open_dir(update_name)
1588                .await
1589                .with_context(|| {
1590                    format!("cannot open update directory {:?} for reading", update_path)
1591                })
1592                .map_err(|err| Error::new(err, Default::default()))?;
1593            Some(Arc::new(dir))
1594        }
1595        None => None,
1596    };
1597    // dry-run: report the directory and traverse its contents, but never create a destination dir.
1598    if settings.dry_run.is_some() {
1599        let preview_dir = if settings.copy_settings.delete.is_some() {
1600            delete_scan_parent
1601                .open(dst_name)
1602                .await
1603                .with_context(|| format!("cannot open destination {dst_path:?} for delete scan"))
1604                .map_err(|error| Error::new(error, Default::default()))?
1605        } else {
1606            None
1607        };
1608        crate::dry_run::report_action("link", src_path, Some(dst_path), "dir");
1609        let base = Summary {
1610            copy_summary: CopySummary {
1611                directories_created: 1, // report as would-be-created
1612                ..Default::default()
1613            },
1614            ..Default::default()
1615        };
1616        return link_dir_contents(
1617            prog_track,
1618            &src_dir,
1619            update_dir.as_ref(),
1620            None, // dry-run: no destination dir
1621            None, // dry-run: no destination parent
1622            dst_name,
1623            src_root,
1624            dst_root,
1625            update_root,
1626            rel_path,
1627            src_path,
1628            dst_path,
1629            true, // treat as "created" so empty-dir cleanup can suppress the dry-run count
1630            is_fresh,
1631            None, // preview handles never lock the destination, so nothing to restore
1632            settings,
1633            base,
1634            SourceEntries::Live,
1635            UpdateEntries::Live,
1636            preview_dir.as_ref(),
1637        )
1638        .await;
1639    }
1640    // real link: dst_parent is Some.
1641    let dst_parent = dst_parent.expect("destination parent must be open for a real link");
1642    let copy::DirSlot {
1643        dir: dst_dir,
1644        summary: base,
1645        is_fresh: child_is_fresh,
1646        we_created,
1647        reused_lock,
1648    } = match copy::resolve_dst_dir(
1649        prog_track,
1650        dst_parent,
1651        dst_name,
1652        dst_path,
1653        &settings.copy_settings,
1654    )
1655    .await
1656    .map_err(|err| {
1657        Error::new(
1658            err.source,
1659            Summary {
1660                copy_summary: err.summary,
1661                ..Default::default()
1662            },
1663        )
1664    })? {
1665        copy::DirResolution::Skip(summary) => {
1666            return Ok(Summary {
1667                copy_summary: summary,
1668                ..Default::default()
1669            });
1670        }
1671        copy::DirResolution::Proceed(slot) => slot,
1672    };
1673    link_dir_contents(
1674        prog_track,
1675        &src_dir,
1676        update_dir.as_ref(),
1677        Some(&dst_dir),
1678        Some(dst_parent),
1679        dst_name,
1680        src_root,
1681        dst_root,
1682        update_root,
1683        rel_path,
1684        src_path,
1685        dst_path,
1686        we_created,
1687        child_is_fresh,
1688        reused_lock,
1689        settings,
1690        Summary {
1691            copy_summary: base,
1692            ..Default::default()
1693        },
1694        SourceEntries::Live,
1695        UpdateEntries::Live,
1696        None,
1697    )
1698    .await
1699}
1700
1701/// Derive source-entry admission from its type hint and whether an update tree participates.
1702///
1703/// A source hint says nothing about a separate update entry, so a dual-tree decision always needs
1704/// admission before either entry is classified.
1705fn source_entry_admission(hint: Option<EntryKind>, has_update: bool) -> EntryAdmission {
1706    let admission = EntryAdmission::from_hint(hint);
1707    if has_update {
1708        // the source hint says nothing about the separate update entry, so the combined decision
1709        // must acquire before it is spawned or opens either classification handle.
1710        admission.require_admission()
1711    } else {
1712        admission
1713    }
1714}
1715
1716/// Whether a preliminary hint decision must defer to the exact worker outcome.
1717fn requires_exact_entry_outcome(settings: &Settings) -> bool {
1718    settings.copy_settings.delete.is_some() || settings.dry_run.is_some()
1719}
1720
1721/// Advisory source-loop decision made before the exact link worker runs.
1722enum SourceEntryDecision {
1723    /// The cheap filter decision is terminal in an ordinary real run.
1724    Filtered { kind: EntryKind },
1725    /// The entry still needs its exact worker decision.
1726    Dispatch(EntryAdmission),
1727}
1728
1729/// Apply reliable source-hint exclusions and return the admission state to transfer into the
1730/// worker. An unknown hint always defers type-sensitive filtering and accounting to the exact
1731/// worker classification.
1732fn select_source_for_dispatch(
1733    hint: Option<EntryKind>,
1734    relative_path: &std::path::Path,
1735    settings: &Settings,
1736    has_update: bool,
1737) -> SourceEntryDecision {
1738    if !requires_exact_entry_outcome(settings)
1739        && let Some(kind) = hint
1740        && walk::should_skip_entry_ref(
1741            settings.filter.as_ref(),
1742            relative_path,
1743            kind == EntryKind::Dir,
1744        )
1745        .is_some()
1746    {
1747        return SourceEntryDecision::Filtered { kind };
1748    }
1749    SourceEntryDecision::Dispatch(source_entry_admission(hint, has_update))
1750}
1751
1752/// Terminal exact selection for an update-only directory entry.
1753enum UpdateOnlyDecision {
1754    /// The authoritative classification excludes this entry.
1755    Skipped {
1756        kind: EntryKind,
1757        result: crate::filter::FilterResult,
1758    },
1759    /// The exact classification and its admission are ready to transfer into copy.
1760    Admitted(AdmittedEntry),
1761}
1762
1763fn select_exact_update_only_entry(
1764    entry: AdmittedEntry,
1765    relative_path: &std::path::Path,
1766    filter: Option<&crate::filter::FilterSettings>,
1767) -> UpdateOnlyDecision {
1768    let kind = entry.kind();
1769    match walk::should_skip_entry_ref(filter, relative_path, kind == EntryKind::Dir) {
1770        Some(result) => UpdateOnlyDecision::Skipped { kind, result },
1771        None => UpdateOnlyDecision::Admitted(entry),
1772    }
1773}
1774
1775/// Advisory update-only decision made before the exact worker runs.
1776enum UpdateOnlyDispatch {
1777    /// A reliable hint excludes this entry in a non-observable ordinary run.
1778    Skipped { kind: EntryKind },
1779    /// The entry still needs its exact worker decision.
1780    Dispatch(EntryAdmission),
1781}
1782
1783/// Apply the cheap reliable-hint exclusion fast path and derive worker admission.
1784fn select_update_only_for_dispatch(
1785    hint: Option<EntryKind>,
1786    relative_path: &std::path::Path,
1787    settings: &Settings,
1788) -> UpdateOnlyDispatch {
1789    if !requires_exact_entry_outcome(settings)
1790        && let Some(kind) = hint
1791        && walk::should_skip_entry_ref(
1792            settings.filter.as_ref(),
1793            relative_path,
1794            kind == EntryKind::Dir,
1795        )
1796        .is_some()
1797    {
1798        return UpdateOnlyDispatch::Skipped { kind };
1799    }
1800    UpdateOnlyDispatch::Dispatch(EntryAdmission::from_hint(hint))
1801}
1802
1803/// Classify one update-only entry inside its worker and retain the exact owner used for dispatch.
1804///
1805/// A positive directory hint gets one unadmitted classification. If it is stale and resolves to a
1806/// leaf, that handle is closed before waiting for admission and classifying again.
1807async fn select_exact_update_only_for_dispatch(
1808    update_dir: &Arc<Dir>,
1809    name: &std::ffi::OsStr,
1810    mut admission: EntryAdmission,
1811    relative_path: &std::path::Path,
1812    filter: Option<&crate::filter::FilterSettings>,
1813) -> std::io::Result<UpdateOnlyDecision> {
1814    let entry = if matches!(admission, EntryAdmission::HintedDirectory) {
1815        let handle = walk::classify_entry(update_dir, name).await?;
1816        if handle.kind() == EntryKind::Dir {
1817            AdmittedEntry::new(handle, None)
1818        } else {
1819            drop(handle);
1820            admission = EntryAdmission::RootOrDelegated;
1821            let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
1822            walk::classify_admitted_entry(update_dir, name, admission.into_permit()).await?
1823        }
1824    } else {
1825        let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
1826        walk::classify_admitted_entry(update_dir, name, admission.into_permit()).await?
1827    };
1828    Ok(select_exact_update_only_entry(entry, relative_path, filter))
1829}
1830
1831/// Process one scheduled update-only entry from exact classification through its terminal keep
1832/// decision. Every spawned child returns a [`LinkTaskResult`], including filter and special skips.
1833#[allow(clippy::too_many_arguments)]
1834async fn process_update_only_entry(
1835    prog_track: &'static progress::Progress,
1836    update_parent: Arc<Dir>,
1837    dst_parent: Option<Arc<Dir>>,
1838    entry_name: std::ffi::OsString,
1839    update_entry_path: std::path::PathBuf,
1840    dst_root: std::path::PathBuf,
1841    entry_rel: std::path::PathBuf,
1842    delete_scan_anchor: copy::DeleteScanAnchor,
1843    settings: Settings,
1844    is_fresh: bool,
1845    admission: EntryAdmission,
1846) -> Result<LinkTaskResult, Error> {
1847    let decision = select_exact_update_only_for_dispatch(
1848        &update_parent,
1849        &entry_name,
1850        admission,
1851        &entry_rel,
1852        settings.filter.as_ref(),
1853    )
1854    .await
1855    .with_context(|| format!("failed reading metadata from {update_entry_path:?}"))
1856    .map_err(|err| Error::new(err, Default::default()))?;
1857    let entry = match decision {
1858        UpdateOnlyDecision::Skipped { kind, result } => {
1859            if let Some(mode) = settings.dry_run {
1860                crate::dry_run::report_skip(&update_entry_path, &result, mode, kind.label());
1861            }
1862            tracing::debug!(
1863                "skipping update entry {:?} due to filter",
1864                &update_entry_path
1865            );
1866            kind.inc_skipped(prog_track);
1867            return Ok(LinkTaskResult::from_update(
1868                entry_name,
1869                LinkEntryResult::filtered(skipped_summary_for(kind)),
1870            ));
1871        }
1872        UpdateOnlyDecision::Admitted(entry) => entry,
1873    };
1874    let entry_kind = entry.kind();
1875    if settings.copy_settings.skip_specials && entry_kind == EntryKind::Special {
1876        tracing::debug!("skipping special file {:?}", &update_entry_path);
1877        if let Some(mode) = settings.dry_run {
1878            match mode {
1879                crate::config::DryRunMode::Brief => {}
1880                crate::config::DryRunMode::All => println!("skip special {:?}", &update_entry_path),
1881                crate::config::DryRunMode::Explain => {
1882                    println!(
1883                        "skip special {:?} (unsupported file type: {:?})",
1884                        &update_entry_path, entry_kind
1885                    );
1886                }
1887            }
1888        }
1889        prog_track.specials_skipped.inc();
1890        return Ok(LinkTaskResult::from_update(
1891            entry_name,
1892            LinkEntryResult::selected(Summary {
1893                copy_summary: CopySummary {
1894                    specials_skipped: 1,
1895                    ..Default::default()
1896                },
1897                ..Default::default()
1898            }),
1899        ));
1900    }
1901    tracing::debug!("found a new entry in the 'update' directory");
1902    let summary = delegate_copy(
1903        prog_track,
1904        &update_parent,
1905        dst_parent.as_ref(),
1906        &entry_name,
1907        &update_entry_path,
1908        &dst_root,
1909        &entry_rel,
1910        delete_scan_anchor,
1911        &settings,
1912        is_fresh,
1913        entry,
1914    )
1915    .await?;
1916    Ok(LinkTaskResult::from_update(
1917        entry_name,
1918        LinkEntryResult::selected(summary),
1919    ))
1920}
1921
1922fn fold_link_task_result(
1923    result: Result<Result<LinkTaskResult, Error>, tokio::task::JoinError>,
1924    link_summary: &mut Summary,
1925    outcomes: &mut LinkChildOutcomes,
1926    fail_early: bool,
1927    src_path: &std::path::Path,
1928    dst_path: &std::path::Path,
1929) -> Result<(), anyhow::Error> {
1930    match result {
1931        Ok(Ok(result)) => result.fold(link_summary, outcomes),
1932        Ok(Err(error)) => {
1933            tracing::error!(
1934                "link: {:?} -> {:?} failed with: {:#}",
1935                src_path,
1936                dst_path,
1937                &error
1938            );
1939            *link_summary = *link_summary + error.summary;
1940            if fail_early {
1941                return Err(error.source);
1942            }
1943            outcomes.record_error(error.source);
1944        }
1945        Err(join_error) => {
1946            if fail_early {
1947                return Err(join_error.into());
1948            }
1949            outcomes.record_error(join_error.into());
1950        }
1951    }
1952    Ok(())
1953}
1954
1955/// Await link-entry admission while reaping ready children. A completed fail-early error wins a tie
1956/// with newly available capacity, so another permanently pending worker cannot consume that
1957/// capacity and strand the unread error. Both source and update-only producers use this boundary.
1958async fn ensure_link_admission(
1959    admission: EntryAdmission,
1960    join_set: &mut tokio::task::JoinSet<Result<LinkTaskResult, Error>>,
1961    link_summary: &mut Summary,
1962    outcomes: &mut LinkChildOutcomes,
1963    fail_early: bool,
1964    src_path: &std::path::Path,
1965    dst_path: &std::path::Path,
1966) -> Result<EntryAdmission, anyhow::Error> {
1967    let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission);
1968    tokio::pin!(admission);
1969    loop {
1970        let has_tasks = !join_set.is_empty();
1971        tokio::select! {
1972            biased;
1973            result = join_set.join_next(), if has_tasks => {
1974                fold_link_task_result(
1975                    result.expect("a non-empty link JoinSet must yield one task result"),
1976                    link_summary,
1977                    outcomes,
1978                    fail_early,
1979                    src_path,
1980                    dst_path,
1981                )?;
1982            }
1983            admission = &mut admission => return Ok(admission),
1984        }
1985    }
1986}
1987
1988enum SourceEntries {
1989    Live,
1990    #[cfg(test)]
1991    InjectedReadError(std::io::Error),
1992    #[cfg(test)]
1993    Injected(Vec<(std::ffi::OsString, Option<EntryKind>)>),
1994}
1995
1996enum UpdateEntries {
1997    Live,
1998    #[cfg(test)]
1999    InjectedReadError(tokio::sync::oneshot::Receiver<std::io::Error>),
2000    #[cfg(test)]
2001    Injected(Vec<(std::ffi::OsString, Option<EntryKind>)>),
2002}
2003
2004/// The dual-tree body of a directory link: enumerate the source entries (hard-linking unchanged
2005/// files, delegating copies, recursing into subdirectories), then enumerate the update entries and
2006/// copy those not present in the source, then run `--delete` pruning, empty-directory cleanup, and
2007/// finally apply the directory's own metadata.
2008///
2009/// `dst_dir == None` / `dst_parent == None` means dry-run (no destination mutation). `preview_dir`
2010/// is independently held from pre-order for dry-run deletion scans only. `base` carries
2011/// the `directories_created`/`directories_unchanged` contribution from resolving this directory.
2012#[allow(clippy::too_many_arguments)]
2013async fn link_dir_contents(
2014    prog_track: &'static progress::Progress,
2015    src_dir: &Arc<Dir>,
2016    update_dir: Option<&Arc<Dir>>,
2017    dst_dir: Option<&Arc<Dir>>,
2018    dst_parent: Option<&Arc<Dir>>,
2019    dst_name: &std::ffi::OsStr,
2020    src_root: &std::path::Path,
2021    dst_root: &std::path::Path,
2022    update_root: Option<&std::path::Path>,
2023    rel_path: &std::path::Path,
2024    src_path: &std::path::Path,
2025    dst_path: &std::path::Path,
2026    we_created_this_dir: bool,
2027    is_fresh: bool,
2028    reused_lock: Option<crate::safedir::ReusedDirLock>,
2029    settings: &Settings,
2030    base: Summary,
2031    source_entries: SourceEntries,
2032    update_entries: UpdateEntries,
2033    preview_dir: Option<&Arc<Dir>>,
2034) -> Result<Summary, Error> {
2035    tracing::debug!("process contents of 'src' directory");
2036    let mut link_summary = base;
2037    let mut join_set = tokio::task::JoinSet::new();
2038    // source names suppress only duplicate update-only scheduling; worker results own --delete keep
2039    // protection after their exact final selection.
2040    let mut processed_files = std::collections::HashSet::new();
2041    // always retain worker/enumeration errors; also retain exact names when --delete is enabled.
2042    let mut outcomes = LinkChildOutcomes::new(settings.copy_settings.delete.as_ref());
2043    // enumeration owns no workers: every fallible producer exit returns here, where the
2044    // directory owns the decision to cancel or drain before pruning and finalization.
2045    let enumeration_result = async {
2046        let src_entries = match source_entries {
2047            SourceEntries::Live => src_dir.read_entries().await,
2048            #[cfg(test)]
2049            SourceEntries::Injected(entries) => Ok(entries),
2050            #[cfg(test)]
2051            SourceEntries::InjectedReadError(error) => Err(error),
2052        }
2053        .with_context(|| format!("cannot open directory {src_path:?} for reading"))?;
2054        // iterate through src entries and recursively call "link" on each one
2055        for (entry_name, hint) in src_entries {
2056            let entry_rel = walk::join_path(rel_path, std::path::Path::new(&entry_name));
2057            let decision =
2058                select_source_for_dispatch(hint, &entry_rel, settings, update_dir.is_some());
2059            let admission = match decision {
2060                SourceEntryDecision::Filtered { kind } => {
2061                    tracing::debug!(
2062                        "skipping {:?} due to filter",
2063                        walk::join_path(src_path, std::path::Path::new(&entry_name))
2064                    );
2065                    link_summary = link_summary + skipped_summary_for(kind);
2066                    kind.inc_skipped(prog_track);
2067                    continue;
2068                }
2069                SourceEntryDecision::Dispatch(admission) => admission,
2070            };
2071            if update_dir.is_some() {
2072                processed_files.insert(entry_name.clone());
2073            }
2074            let admission = ensure_link_admission(
2075                admission,
2076                &mut join_set,
2077                &mut link_summary,
2078                &mut outcomes,
2079                settings.copy_settings.fail_early,
2080                src_path,
2081                dst_path,
2082            )
2083            .await?;
2084            // acquire-then-IMMEDIATELY-spawn (the permit is moved into `do_link` and spawned on the next
2085            // line, in the same loop step) is load-bearing: collecting a Vec of pre-acquired permits and
2086            // spawning later would hold N permits before any task runs and self-deadlock a saturated pool.
2087            // this mirrors the shared driver's incremental acquire-then-spawn loop; both reap ready
2088            // workers into their exact-result folds while admission waits.
2089            let src_parent = Arc::clone(src_dir);
2090            let dst_parent = dst_dir.map(Arc::clone);
2091            let update_parent = update_dir.map(Arc::clone);
2092            let settings = settings.clone();
2093            let src_root = src_root.to_owned();
2094            let dst_root = dst_root.to_owned();
2095            let update_root = update_root.map(std::path::Path::to_path_buf);
2096            let delete_scan_parent = copy::DeleteScanAnchor::parent(preview_dir.cloned());
2097            let do_link = move || async move {
2098                let update_ref = update_parent
2099                    .as_ref()
2100                    .map(|dir| (dir, entry_name.as_os_str()));
2101                link_internal(
2102                    prog_track,
2103                    &src_parent,
2104                    update_ref,
2105                    dst_parent.as_ref(),
2106                    &entry_name,
2107                    &src_root,
2108                    &dst_root,
2109                    update_root.as_deref(),
2110                    &entry_rel,
2111                    UpdateRootRequirement::Optional,
2112                    &settings,
2113                    is_fresh,
2114                    admission.into(),
2115                    delete_scan_parent,
2116                )
2117                .await
2118                .map(|result| LinkTaskResult::from_link(entry_name, result))
2119            };
2120            crate::task_scope::spawn_tracked(&mut join_set, do_link());
2121        }
2122        // only process update if the path was provided and the directory is present
2123        if let Some(update_dir) = update_dir {
2124            let update_root = update_root.expect("update_dir present implies update_root present");
2125            tracing::debug!("process contents of 'update' directory");
2126            let update_entries = match update_entries {
2127                UpdateEntries::Live => update_dir.read_entries().await,
2128                #[cfg(test)]
2129                UpdateEntries::Injected(entries) => Ok(entries),
2130                #[cfg(test)]
2131                UpdateEntries::InjectedReadError(error) => {
2132                    Err(error.await.expect("injected read error"))
2133                }
2134            }
2135            .with_context(|| {
2136                format!(
2137                    "cannot open directory {:?} for reading",
2138                    walk::join_rel(update_root, rel_path)
2139                )
2140            })?;
2141            // iterate through update entries and copy names absent from src. reliable excluded hints
2142            // keep their cheap skip in ordinary real runs; delete and preview runs reclassify before an
2143            // observable decision. every entry that can reach copy transfers its exact handle and
2144            // admission.
2145            for (entry_name, hint) in update_entries {
2146                if processed_files.contains(&entry_name) {
2147                    // the source worker owns the exact joint source/update selection and reports its
2148                    // destination-protection decision when it completes.
2149                    continue;
2150                }
2151                let entry_rel = walk::join_path(rel_path, std::path::Path::new(&entry_name));
2152                let admission = match select_update_only_for_dispatch(hint, &entry_rel, settings) {
2153                    UpdateOnlyDispatch::Skipped { kind } => {
2154                        tracing::debug!(
2155                            "skipping update entry {:?} due to filter",
2156                            walk::join_rel(update_root, &entry_rel)
2157                        );
2158                        link_summary = link_summary + skipped_summary_for(kind);
2159                        kind.inc_skipped(prog_track);
2160                        continue;
2161                    }
2162                    UpdateOnlyDispatch::Dispatch(admission) => admission,
2163                };
2164                let update_entry_path = walk::join_rel(update_root, &entry_rel);
2165                let admission = ensure_link_admission(
2166                    admission,
2167                    &mut join_set,
2168                    &mut link_summary,
2169                    &mut outcomes,
2170                    settings.copy_settings.fail_early,
2171                    src_path,
2172                    dst_path,
2173                )
2174                .await?;
2175                // acquire-then-IMMEDIATELY-spawn is load-bearing here for the same reason as the source
2176                // loop: the worker owns authoritative classification and must be able to release the
2177                // permit before scheduling waits for another one
2178                let dst_root = dst_root.to_path_buf();
2179                let update_parent = Arc::clone(update_dir);
2180                let dst_parent = dst_dir.map(Arc::clone);
2181                let settings = settings.clone();
2182                let delete_scan_anchor = copy::DeleteScanAnchor::parent(preview_dir.cloned());
2183                let do_copy = move || {
2184                    // filter-base for the delegated copy: this update entry's path relative to the
2185                    // source root, so any --delete pruning inside it matches the include/exclude filter
2186                    // at the entry's true relative path (e.g. cache/*.log), not relative to the entry.
2187                    process_update_only_entry(
2188                        prog_track,
2189                        update_parent,
2190                        dst_parent,
2191                        entry_name,
2192                        update_entry_path,
2193                        dst_root,
2194                        entry_rel,
2195                        delete_scan_anchor,
2196                        settings,
2197                        is_fresh,
2198                        admission,
2199                    )
2200                };
2201                crate::task_scope::spawn_tracked(&mut join_set, do_copy());
2202            }
2203        }
2204        Ok::<(), anyhow::Error>(())
2205    }
2206    .await;
2207    if let Err(error) = enumeration_result {
2208        if settings.copy_settings.fail_early {
2209            crate::walk_driver::abort_and_join(&mut join_set).await;
2210            return Err(Error::new(error, link_summary));
2211        }
2212        outcomes.record_error(error);
2213    }
2214    while let Some(res) = join_set.join_next().await {
2215        if let Err(error) = fold_link_task_result(
2216            res,
2217            &mut link_summary,
2218            &mut outcomes,
2219            settings.copy_settings.fail_early,
2220            src_path,
2221            dst_path,
2222        ) {
2223            crate::walk_driver::abort_and_join(&mut join_set).await;
2224            return Err(Error::new(error, link_summary));
2225        }
2226    }
2227    // rsync-style --delete for rlink: remove destination entries the final exact decisions did not
2228    // protect. `outcomes` holds the selected src ∪ update names normally, or only selected update
2229    // names under --update-exclusive; deliberately skipped specials retain their historical
2230    // protection even though no new entry is materialized.
2231    let (decision, errors) = outcomes.finish();
2232    if let Some(keep_set) = decision.into_ready(dst_path)
2233        && let Some(prune_dir) = crate::delete::select_scan_dir(dst_dir, preview_dir, dst_path)
2234        && let Err(error) = crate::delete::prune_and_fold(
2235            prog_track,
2236            prune_dir,
2237            rel_path,
2238            &keep_set,
2239            settings.filter.as_ref(),
2240            settings.copy_settings.fail_early,
2241            settings.dry_run,
2242            &mut link_summary.copy_summary.rm_summary,
2243        )
2244        .await
2245    {
2246        if settings.copy_settings.fail_early {
2247            return Err(Error::new(error, link_summary));
2248        }
2249        errors.push(error);
2250    }
2251    // when filtering is active and we created this directory, check if anything was actually
2252    // linked/copied into it. if nothing was linked, we may need to clean up the empty directory.
2253    let this_dir_count = usize::from(we_created_this_dir);
2254    let child_dirs_created = link_summary
2255        .copy_summary
2256        .directories_created
2257        .saturating_sub(this_dir_count);
2258    let anything_linked = link_summary.hard_links_created > 0
2259        || link_summary.copy_summary.files_copied > 0
2260        || link_summary.copy_summary.symlinks_created > 0
2261        || child_dirs_created > 0;
2262    match check_empty_dir_cleanup(
2263        settings.filter.as_ref(),
2264        we_created_this_dir,
2265        anything_linked,
2266        rel_path,
2267        settings.dry_run.is_some(),
2268    ) {
2269        EmptyDirAction::Keep => { /* proceed with metadata application */ }
2270        EmptyDirAction::DryRunSkip => {
2271            tracing::debug!(
2272                "dry-run: directory {:?} would not be created (nothing to link inside)",
2273                dst_path
2274            );
2275            link_summary.copy_summary.directories_created = 0;
2276            // a child error collected during the walk must still surface — otherwise a
2277            // traversal-only directory whose only child FAILED becomes "empty", is skipped here, and
2278            // the failed link is reported as success (mirrors copy::finalize_dir).
2279            if errors.has_errors() {
2280                return Err(Error::new(errors.into_error().unwrap(), link_summary));
2281            }
2282            return Ok(link_summary);
2283        }
2284        EmptyDirAction::Remove => {
2285            tracing::debug!(
2286                "directory {:?} has nothing to link inside, removing empty directory",
2287                dst_path
2288            );
2289            // remove the empty directory fd-relative, through its parent dir handle: `rmdir_at`
2290            // operates on `dst_name` within the held `dst_parent` fd (never by path) and only
2291            // succeeds on an empty directory, so it is contained to `dst_parent`. `dst_parent` is
2292            // always Some here (None only in dry-run, where this arm is unreachable).
2293            let rmdir_result = match dst_parent {
2294                Some(dst_parent) => dst_parent.rmdir_at(dst_name).await,
2295                None => {
2296                    crate::walk::run_metadata_probed(
2297                        congestion::Side::Destination,
2298                        congestion::MetadataOp::RmDir,
2299                        tokio::fs::remove_dir(dst_path),
2300                    )
2301                    .await
2302                }
2303            };
2304            match rmdir_result {
2305                Ok(()) => {
2306                    link_summary.copy_summary.directories_created = 0;
2307                    // surface a collected child error even though the empty directory was removed,
2308                    // so a failed child link is never reported as success (mirrors
2309                    // copy::finalize_dir).
2310                    if errors.has_errors() {
2311                        return Err(Error::new(errors.into_error().unwrap(), link_summary));
2312                    }
2313                    return Ok(link_summary);
2314                }
2315                Err(err) => {
2316                    // removal failed (not empty, permission error, etc.) — keep directory
2317                    tracing::debug!(
2318                        "failed to remove empty directory {:?}: {:#}, keeping",
2319                        dst_path,
2320                        &err
2321                    );
2322                    // fall through to apply metadata
2323                }
2324            }
2325        }
2326    }
2327    // apply directory metadata regardless of whether all children linked successfully. the
2328    // directory itself was created/opened above. skipped in dry-run (no directory exists). prefer
2329    // the update directory's metadata when an update tree is present at this level (it is the
2330    // materialized version, matching the old `update_metadata_opt` preference), else the source
2331    // directory's. The metadata is read from the SAME fd whose contents were enumerated (read-side
2332    // fidelity, docs/tocttou.md), not the classify handles.
2333    tracing::debug!("set 'dst' directory metadata");
2334    let metadata_result = match dst_dir {
2335        Some(dst_dir) => {
2336            let meta_dir = update_dir.unwrap_or(src_dir);
2337            // for a reused directory locked down under strict mode, put back the ACLs the
2338            // lockdown stripped and restore the original owner component-wise, then apply source
2339            // metadata (see set_reused_dir_metadata_fd — no transient window hands the directory to
2340            // a hostile prior owner); None for fresh dirs.
2341            async {
2342                let preserve_meta = meta_dir.meta().await?;
2343                // the ACLs come from the same fd as the metadata, and only when `d:acl` was asked
2344                // for — rlink creates its directories fresh, so unlike files there is no shared
2345                // inode and applying them is ordinary destination work.
2346                let preserve_acls = if settings.preserve.dir.acl {
2347                    Some(meta_dir.read_acls().await?)
2348                } else {
2349                    None
2350                };
2351                crate::safedir::set_reused_dir_metadata_fd(
2352                    &settings.preserve,
2353                    &preserve_meta,
2354                    preserve_acls.as_ref(),
2355                    reused_lock,
2356                    dst_dir,
2357                )
2358                .await
2359            }
2360            .await
2361        }
2362        None => Ok(()),
2363    };
2364    if errors.has_errors() {
2365        // child failures take precedence - log metadata error if it also failed
2366        if let Err(metadata_err) = metadata_result {
2367            tracing::error!(
2368                "link: {:?} -> {:?} failed to set directory metadata: {:#}",
2369                src_path,
2370                dst_path,
2371                &metadata_err
2372            );
2373        }
2374        // unwrap is safe: has_errors() guarantees into_error() returns Some
2375        return Err(Error::new(errors.into_error().unwrap(), link_summary));
2376    }
2377    // no child failures, so metadata error is the primary error
2378    metadata_result
2379        .with_context(|| format!("failed setting directory metadata on {:?}", dst_path))
2380        .map_err(|err| Error::new(err, link_summary))?;
2381    Ok(link_summary)
2382}
2383
2384#[cfg(test)]
2385mod link_tests {
2386    use crate::rm;
2387    use crate::testutils;
2388    use std::os::unix::fs::PermissionsExt;
2389    use tracing_test::traced_test;
2390
2391    use super::*;
2392
2393    static PROGRESS: std::sync::LazyLock<progress::Progress> =
2394        std::sync::LazyLock::new(progress::Progress::new);
2395
2396    #[test]
2397    fn directory_close_primitive_drops_both_handles_before_permit() {
2398        let events = testutils::DropEvents::default();
2399        drop_link_handles_before_permit(
2400            events.probe("source handle"),
2401            Some(events.probe("update handle")),
2402            Some(events.probe("permit")),
2403        );
2404        assert_eq!(
2405            events.snapshot(),
2406            ["source handle", "update handle", "permit"]
2407        );
2408    }
2409
2410    #[test]
2411    fn admitted_link_entry_drops_both_handles_before_permit() {
2412        let events = testutils::DropEvents::default();
2413        let entry = AdmittedLinkEntry {
2414            src_handle: events.probe("source handle"),
2415            update_handle: Some(events.probe("update handle")),
2416            permit: Some(events.probe("permit")),
2417        };
2418        drop(entry);
2419        assert_eq!(
2420            events.snapshot(),
2421            ["source handle", "update handle", "permit"]
2422        );
2423    }
2424
2425    mod delete_keep_set_tests {
2426        //! Pure-logic unit tests for `LinkChildOutcomes`. No filesystem needed — these pin exact
2427        //! worker ownership so a future refactor cannot silently restore hint-based keeps.
2428
2429        use super::super::LinkChildOutcomes;
2430        use crate::copy::DeleteSettings;
2431        use std::ffi::{OsStr, OsString};
2432
2433        fn delete_on() -> DeleteSettings {
2434            DeleteSettings {
2435                delete_excluded: false,
2436            }
2437        }
2438
2439        #[test]
2440        fn exact_result_no_op_when_delete_off() {
2441            let mut k = LinkChildOutcomes::new(None);
2442            k.record_exact(OsString::from("foo"));
2443            assert!(k.as_set().is_none());
2444        }
2445
2446        #[test]
2447        fn exact_materialized_update_exclusive_duplicate_is_retained() {
2448            let d = delete_on();
2449            let mut k = LinkChildOutcomes::new(Some(&d));
2450            let mut summary = super::super::Summary::default();
2451            super::super::LinkTaskResult::from_link(
2452                OsString::from("node"),
2453                super::super::LinkEntryResult::selected(Default::default()),
2454            )
2455            .fold(&mut summary, &mut k);
2456            assert!(
2457                k.as_set().unwrap().contains(OsStr::new("node")),
2458                "the exact worker's materialized update selection must own the keep decision"
2459            );
2460        }
2461
2462        #[test]
2463        fn selected_source_entry_is_retained_in_normal_mode() {
2464            let d = delete_on();
2465            let mut k = LinkChildOutcomes::new(Some(&d));
2466            let mut summary = super::super::Summary::default();
2467            super::super::LinkTaskResult::from_link(
2468                OsString::from("node"),
2469                super::super::LinkEntryResult::selected(Default::default()),
2470            )
2471            .fold(&mut summary, &mut k);
2472            assert!(
2473                k.as_set().unwrap().contains(OsStr::new("node")),
2474                "the exact worker's selected source outcome must protect its destination"
2475            );
2476        }
2477
2478        #[test]
2479        fn full_directory_pass_keep_set_union_semantics() {
2480            // Models the union of src + update under plain `--delete --update` (no
2481            // --update-exclusive). Names: src has `keep`, `pipe` (special, skipped),
2482            // `node` (file). update has `from_upd`, `node` (a dir excluded by the dir-only
2483            // `node/` pattern). Under union semantics the excluded update `node/` does not
2484            // displace the src `node` file: `link_internal` materializes the src version, so
2485            // `node` STAYS in the keep-set (the filtered-out update branch records/removes
2486            // nothing). This is the corrected behavior versus the old type-mismatch bug, where
2487            // the excluded update dir was copied AND the src keep-set entry was dropped.
2488            let d = delete_on();
2489            let mut k = LinkChildOutcomes::new(Some(&d));
2490
2491            let mut summary = super::super::Summary::default();
2492            for name in ["keep", "pipe", "node"] {
2493                super::super::LinkTaskResult::from_link(
2494                    OsString::from(name),
2495                    super::super::LinkEntryResult::selected(Default::default()),
2496                )
2497                .fold(&mut summary, &mut k);
2498            }
2499            super::super::LinkTaskResult::from_update(
2500                OsString::from("from_upd"),
2501                super::super::LinkEntryResult::selected(Default::default()),
2502            )
2503            .fold(&mut summary, &mut k);
2504
2505            let set: std::collections::HashSet<OsString> = k.as_set().unwrap().clone();
2506            let expected: std::collections::HashSet<OsString> =
2507                ["keep", "pipe", "node", "from_upd"]
2508                    .into_iter()
2509                    .map(OsString::from)
2510                    .collect();
2511            assert_eq!(set, expected);
2512        }
2513    }
2514
2515    fn common_settings(dereference: bool, overwrite: bool) -> Settings {
2516        Settings {
2517            copy_settings: CopySettings {
2518                reflink: Default::default(),
2519                local_copy_handoff: Default::default(),
2520                dereference,
2521                fail_early: false,
2522                overwrite,
2523                overwrite_compare: filecmp::MetadataCmpSettings {
2524                    size: true,
2525                    mtime: true,
2526                    ..Default::default()
2527                },
2528                overwrite_filter: None,
2529                ignore_existing: false,
2530                chunk_size: 0,
2531                skip_specials: false,
2532                remote_copy_buffer_size: 0,
2533                filter: None,
2534                dry_run: None,
2535                delete: None,
2536            },
2537            update_compare: filecmp::MetadataCmpSettings {
2538                size: true,
2539                mtime: true,
2540                ..Default::default()
2541            },
2542            update_exclusive: false,
2543            filter: None,
2544            dry_run: None,
2545            preserve: preserve::preserve_all(),
2546        }
2547    }
2548
2549    struct RestoreRenamedUpdateRoot {
2550        original: std::path::PathBuf,
2551        renamed: std::path::PathBuf,
2552    }
2553
2554    impl Drop for RestoreRenamedUpdateRoot {
2555        fn drop(&mut self) {
2556            if self.renamed.exists() {
2557                let _ = std::fs::rename(&self.renamed, &self.original);
2558            }
2559        }
2560    }
2561
2562    struct DisappearingUpdateRootHook {
2563        _registration: AfterUpdatePrecheckHookRegistration,
2564        _cleanup: std::sync::Arc<std::sync::Mutex<Option<RestoreRenamedUpdateRoot>>>,
2565    }
2566
2567    fn disappear_update_root_after_precheck(
2568        update: &std::path::Path,
2569    ) -> DisappearingUpdateRootHook {
2570        let original = update.to_owned();
2571        let renamed = update.with_extension("removed-after-precheck");
2572        let cleanup = std::sync::Arc::new(std::sync::Mutex::new(None));
2573        let hook_cleanup = Arc::clone(&cleanup);
2574        let registration = install_after_update_precheck_hook(
2575            original.clone(),
2576            Box::new(move || {
2577                std::fs::rename(&original, &renamed)
2578                    .expect("rename update root after its early precheck");
2579                *hook_cleanup
2580                    .lock()
2581                    .unwrap_or_else(std::sync::PoisonError::into_inner) =
2582                    Some(RestoreRenamedUpdateRoot { original, renamed });
2583            }),
2584        );
2585        DisappearingUpdateRootHook {
2586            _registration: registration,
2587            _cleanup: cleanup,
2588        }
2589    }
2590
2591    async fn setup_disappearing_update_root_case() -> Result<
2592        (
2593            std::path::PathBuf,
2594            std::path::PathBuf,
2595            std::path::PathBuf,
2596            std::path::PathBuf,
2597        ),
2598        anyhow::Error,
2599    > {
2600        let test_path = testutils::create_temp_dir().await?;
2601        let src = test_path.join("src");
2602        let update = test_path.join("update");
2603        let dst = test_path.join("dst");
2604        tokio::fs::create_dir(&src).await?;
2605        tokio::fs::create_dir(&update).await?;
2606        tokio::fs::create_dir(&dst).await?;
2607        tokio::fs::write(src.join("source-only.txt"), "SOURCE").await?;
2608        tokio::fs::write(update.join("protected.txt"), "UPDATE").await?;
2609        tokio::fs::write(dst.join("source-only.txt"), "DESTINATION").await?;
2610        tokio::fs::write(dst.join("protected.txt"), "PROTECTED DESTINATION").await?;
2611        Ok((test_path, src, update, dst))
2612    }
2613
2614    fn assert_missing_destructive_update_error(error: &Error) {
2615        let message = format!("{:#}", error.source);
2616        assert!(
2617            message.contains("--update path") && message.contains("does not exist"),
2618            "missing destructive update error was unclear: {message}"
2619        );
2620    }
2621
2622    #[tokio::test]
2623    async fn update_exclusive_errors_if_update_root_disappears_after_precheck()
2624    -> Result<(), anyhow::Error> {
2625        let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
2626        let _hook = disappear_update_root_after_precheck(&update);
2627        let mut settings = common_settings(false, true);
2628        settings.update_exclusive = true;
2629        let result = link(
2630            &PROGRESS,
2631            &test_path,
2632            &src,
2633            &dst,
2634            &Some(update.clone()),
2635            &settings,
2636            false,
2637        )
2638        .await;
2639        assert_eq!(
2640            tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
2641            "DESTINATION"
2642        );
2643        assert_eq!(
2644            tokio::fs::read_to_string(dst.join("protected.txt")).await?,
2645            "PROTECTED DESTINATION"
2646        );
2647        let error = result.expect_err("a vanished update root must fail update-exclusive");
2648        assert_missing_destructive_update_error(&error);
2649        Ok(())
2650    }
2651
2652    #[tokio::test]
2653    async fn delete_update_does_not_prune_if_update_root_disappears_after_precheck()
2654    -> Result<(), anyhow::Error> {
2655        let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
2656        let _hook = disappear_update_root_after_precheck(&update);
2657        let mut settings = common_settings(false, true);
2658        settings.copy_settings.delete = Some(copy::DeleteSettings {
2659            delete_excluded: false,
2660        });
2661        settings.filter = Some(crate::filter::FilterSettings::new());
2662        let result = link(
2663            &PROGRESS,
2664            &test_path,
2665            &src,
2666            &dst,
2667            &Some(update.clone()),
2668            &settings,
2669            false,
2670        )
2671        .await;
2672        assert_eq!(
2673            tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
2674            "DESTINATION"
2675        );
2676        assert_eq!(
2677            tokio::fs::read_to_string(dst.join("protected.txt")).await?,
2678            "PROTECTED DESTINATION"
2679        );
2680        let error = result.expect_err("a vanished update root must stop delete pruning");
2681        assert_missing_destructive_update_error(&error);
2682        Ok(())
2683    }
2684
2685    #[tokio::test]
2686    async fn plain_update_falls_back_if_update_root_disappears_after_precheck()
2687    -> Result<(), anyhow::Error> {
2688        let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
2689        let _hook = disappear_update_root_after_precheck(&update);
2690        link(
2691            &PROGRESS,
2692            &test_path,
2693            &src,
2694            &dst,
2695            &Some(update),
2696            &common_settings(false, true),
2697            false,
2698        )
2699        .await?;
2700        assert_eq!(
2701            tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
2702            "SOURCE"
2703        );
2704        assert_eq!(
2705            tokio::fs::read_to_string(dst.join("protected.txt")).await?,
2706            "PROTECTED DESTINATION"
2707        );
2708        Ok(())
2709    }
2710
2711    #[tokio::test]
2712    async fn renamed_non_utf8_file_roots_keep_destination_basename() -> anyhow::Result<()> {
2713        use std::os::unix::ffi::OsStrExt;
2714        use std::os::unix::fs::MetadataExt;
2715        for with_update in [false, true] {
2716            let root = testutils::create_temp_dir().await?;
2717            let src = root.join(std::ffi::OsStr::from_bytes(b"source\xff"));
2718            let dst = root.join(std::ffi::OsStr::from_bytes(b"renamed\xfe"));
2719            let update = root.join(std::ffi::OsStr::from_bytes(b"update\xfd"));
2720            tokio::fs::write(&src, b"source").await?;
2721            tokio::fs::write(&update, b"updated contents").await?;
2722            let summary = link(
2723                &PROGRESS,
2724                &root,
2725                &src,
2726                &dst,
2727                &with_update.then_some(update),
2728                &common_settings(false, false),
2729                false,
2730            )
2731            .await?;
2732            assert_eq!(
2733                tokio::fs::read(&dst).await?,
2734                if with_update {
2735                    b"updated contents".as_slice()
2736                } else {
2737                    b"source"
2738                }
2739            );
2740            assert_eq!(summary.hard_links_created, usize::from(!with_update));
2741            assert_eq!(summary.copy_summary.files_copied, usize::from(with_update));
2742            let src_meta = tokio::fs::metadata(&src).await?;
2743            let dst_meta = tokio::fs::metadata(&dst).await?;
2744            assert_eq!(
2745                (src_meta.dev(), src_meta.ino()) == (dst_meta.dev(), dst_meta.ino()),
2746                !with_update
2747            );
2748        }
2749        Ok(())
2750    }
2751
2752    #[tokio::test]
2753    async fn invalid_destination_root_is_rejected_before_source_classification()
2754    -> anyhow::Result<()> {
2755        let root = testutils::create_temp_dir().await?;
2756        let dir = Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Source).await?);
2757        let source = root.join("missing-source");
2758        let destination = std::path::Path::new("/");
2759        let result = link_internal(
2760            &PROGRESS,
2761            &dir,
2762            None,
2763            None,
2764            std::ffi::OsStr::new("missing-source"),
2765            &source,
2766            destination,
2767            None,
2768            std::path::Path::new(""),
2769            UpdateRootRequirement::Optional,
2770            &common_settings(false, false),
2771            false,
2772            EntryAdmission::RootOrDelegated.into(),
2773            copy::DeleteScanAnchor::new(destination, std::path::Path::new("")),
2774        )
2775        .await;
2776        let error = match result {
2777            Ok(_) => panic!("invalid destination must fail"),
2778            Err(error) => error,
2779        };
2780        assert!(format!("{:#}", error.source).contains("has no file name"));
2781        assert!(!source.exists());
2782        Ok(())
2783    }
2784
2785    #[tokio::test]
2786    async fn update_exclusive_without_update_links_the_source_normally() -> Result<(), anyhow::Error>
2787    {
2788        use std::os::unix::fs::MetadataExt;
2789        let test_path = testutils::create_temp_dir().await?;
2790        let src = test_path.join("src");
2791        let dst = test_path.join("dst");
2792        tokio::fs::write(&src, "SOURCE").await?;
2793        let mut settings = common_settings(false, false);
2794        settings.update_exclusive = true;
2795        let summary = link(&PROGRESS, &test_path, &src, &dst, &None, &settings, false).await?;
2796        assert_eq!(summary.hard_links_created, 1);
2797        assert_eq!(tokio::fs::read_to_string(&dst).await?, "SOURCE");
2798        let src_metadata = tokio::fs::metadata(&src).await?;
2799        let dst_metadata = tokio::fs::metadata(&dst).await?;
2800        assert_eq!(
2801            (src_metadata.dev(), src_metadata.ino()),
2802            (dst_metadata.dev(), dst_metadata.ino())
2803        );
2804        Ok(())
2805    }
2806
2807    #[tokio::test]
2808    #[traced_test]
2809    async fn test_basic_link() -> Result<(), anyhow::Error> {
2810        let tmp_dir = testutils::setup_test_dir().await?;
2811        let test_path = tmp_dir.as_path();
2812        let summary = link(
2813            &PROGRESS,
2814            test_path,
2815            &test_path.join("foo"),
2816            &test_path.join("bar"),
2817            &None,
2818            &common_settings(false, false),
2819            false,
2820        )
2821        .await?;
2822        assert_eq!(summary.hard_links_created, 5);
2823        assert_eq!(summary.copy_summary.files_copied, 0);
2824        assert_eq!(summary.copy_summary.symlinks_created, 2);
2825        assert_eq!(summary.copy_summary.directories_created, 3);
2826        testutils::check_dirs_identical(
2827            &test_path.join("foo"),
2828            &test_path.join("bar"),
2829            testutils::FileEqualityCheck::Timestamp,
2830        )
2831        .await?;
2832        Ok(())
2833    }
2834
2835    #[tokio::test]
2836    async fn nested_non_utf8_names_keep_source_and_update_outcomes_during_delete()
2837    -> anyhow::Result<()> {
2838        use std::os::unix::ffi::OsStrExt;
2839        use std::os::unix::fs::MetadataExt;
2840        let branch = std::ffi::OsStr::from_bytes(b"branch\xff");
2841        let shared_name = std::ffi::OsStr::from_bytes(b"shared\xfe");
2842        let source_name = std::ffi::OsStr::from_bytes(b"source\xfd");
2843        let update_name = std::ffi::OsStr::from_bytes(b"update\xfc");
2844        for with_update in [false, true] {
2845            let root = testutils::create_temp_dir().await?;
2846            let src = root.join("src");
2847            let update = root.join("update");
2848            let dst = root.join("dst");
2849            let src_branch = src.join(branch);
2850            let update_branch = update.join(branch);
2851            let dst_branch = dst.join(branch);
2852            tokio::fs::create_dir_all(&src_branch).await?;
2853            tokio::fs::create_dir_all(&update_branch).await?;
2854            tokio::fs::create_dir_all(&dst_branch).await?;
2855            tokio::fs::write(src_branch.join(shared_name), b"original").await?;
2856            tokio::fs::write(src_branch.join(source_name), b"source only").await?;
2857            tokio::fs::write(update_branch.join(shared_name), b"updated contents").await?;
2858            tokio::fs::write(update_branch.join(update_name), b"update only").await?;
2859            tokio::fs::write(dst_branch.join("stale"), b"stale").await?;
2860            let mut settings = common_settings(false, true);
2861            settings.copy_settings.delete = Some(copy::DeleteSettings {
2862                delete_excluded: false,
2863            });
2864            let summary = link(
2865                &PROGRESS,
2866                &root,
2867                &src,
2868                &dst,
2869                &with_update.then_some(update),
2870                &settings,
2871                false,
2872            )
2873            .await?;
2874            assert_eq!(summary.hard_links_created, if with_update { 1 } else { 2 });
2875            assert_eq!(
2876                summary.copy_summary.files_copied,
2877                if with_update { 2 } else { 0 }
2878            );
2879            assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
2880            assert!(!dst_branch.join("stale").exists());
2881            assert_eq!(
2882                tokio::fs::read(dst_branch.join(shared_name)).await?,
2883                if with_update {
2884                    b"updated contents".as_slice()
2885                } else {
2886                    b"original"
2887                }
2888            );
2889            assert_eq!(
2890                tokio::fs::read(dst_branch.join(source_name)).await?,
2891                b"source only"
2892            );
2893            let src_meta = tokio::fs::metadata(src_branch.join(source_name)).await?;
2894            let dst_meta = tokio::fs::metadata(dst_branch.join(source_name)).await?;
2895            assert_eq!(
2896                (src_meta.dev(), src_meta.ino()),
2897                (dst_meta.dev(), dst_meta.ino())
2898            );
2899            if with_update {
2900                assert_eq!(
2901                    tokio::fs::read(dst_branch.join(update_name)).await?,
2902                    b"update only"
2903                );
2904            } else {
2905                assert!(!dst_branch.join(update_name).exists());
2906            }
2907            tokio::fs::remove_dir_all(root).await?;
2908        }
2909        Ok(())
2910    }
2911
2912    // regression: a source operand whose final component is `.`/`..` (e.g. `rlink tree/.. dst`)
2913    // must be linked, not rejected — `split_root_operand` canonicalizes it. Uses `tree/sub/..`
2914    // (== `tree`) rather than `.` to avoid touching the process-wide cwd.
2915    #[tokio::test]
2916    async fn links_dot_dot_source_operand() -> Result<(), anyhow::Error> {
2917        use std::os::unix::fs::MetadataExt;
2918        let tmp = testutils::create_temp_dir().await?;
2919        let tree = tmp.join("tree");
2920        tokio::fs::create_dir(&tree).await?;
2921        tokio::fs::write(tree.join("a.txt"), "hello").await?;
2922        tokio::fs::create_dir(tree.join("sub")).await?;
2923        let src = tree.join("sub").join(".."); // == tree
2924        let dst = tmp.join("dst");
2925        let summary = link(
2926            &PROGRESS,
2927            &tmp,
2928            &src,
2929            &dst,
2930            &None,
2931            &common_settings(false, false),
2932            false,
2933        )
2934        .await?;
2935        assert_eq!(
2936            summary.hard_links_created, 1,
2937            "the dot-dot source's file must be hard-linked"
2938        );
2939        assert!(
2940            dst.join("sub").is_dir(),
2941            "the dot-dot source's subdir must be created"
2942        );
2943        // the dst file shares the src inode (a hard link, not a copy).
2944        let src_ino = std::fs::metadata(tree.join("a.txt"))?.ino();
2945        let dst_ino = std::fs::metadata(dst.join("a.txt"))?.ino();
2946        assert_eq!(src_ino, dst_ino, "dst must be a hard link to the src inode");
2947        Ok(())
2948    }
2949
2950    // Regression: an `--update` operand whose final component is `.`/`..` (e.g.
2951    // `rlink --update tree/.. src dst`) must be accepted, not rejected — the update tree is a READ
2952    // tree, so `split_root_operand` canonicalizes it the same as the source. Uses `tree/sub/..`
2953    // (== `tree`) rather than `.` to avoid touching the process-wide cwd; src == update == tree so
2954    // the file links deterministically from the update tree.
2955    #[tokio::test]
2956    async fn links_dot_dot_update_operand() -> Result<(), anyhow::Error> {
2957        use std::os::unix::fs::MetadataExt;
2958        let tmp = testutils::create_temp_dir().await?;
2959        let tree = tmp.join("tree");
2960        tokio::fs::create_dir(&tree).await?;
2961        tokio::fs::write(tree.join("a.txt"), "hello").await?;
2962        tokio::fs::create_dir(tree.join("sub")).await?;
2963        let dst = tmp.join("dst");
2964        // the --update operand spelled with a trailing `..` (== tree); it must be canonicalized and
2965        // used, not rejected with "has no parent directory or file name".
2966        let update_operand = tree.join("sub").join(".."); // == tree
2967        let summary = link(
2968            &PROGRESS,
2969            &tmp,
2970            &tree,
2971            &dst,
2972            &Some(update_operand),
2973            &common_settings(false, false),
2974            false,
2975        )
2976        .await?;
2977        assert_eq!(
2978            summary.hard_links_created, 1,
2979            "the file must be hard-linked from the dot-dot update tree"
2980        );
2981        // the dst file shares the update tree's inode (linked from it, not copied).
2982        let update_ino = std::fs::metadata(tree.join("a.txt"))?.ino();
2983        let dst_ino = std::fs::metadata(dst.join("a.txt"))?.ino();
2984        assert_eq!(
2985            update_ino, dst_ino,
2986            "dst must be hard-linked from the update tree inode"
2987        );
2988        Ok(())
2989    }
2990
2991    #[tokio::test]
2992    #[traced_test]
2993    async fn test_basic_link_update() -> Result<(), anyhow::Error> {
2994        let tmp_dir = testutils::setup_test_dir().await?;
2995        let test_path = tmp_dir.as_path();
2996        let summary = link(
2997            &PROGRESS,
2998            test_path,
2999            &test_path.join("foo"),
3000            &test_path.join("bar"),
3001            &Some(test_path.join("foo")),
3002            &common_settings(false, false),
3003            false,
3004        )
3005        .await?;
3006        assert_eq!(summary.hard_links_created, 5);
3007        assert_eq!(summary.copy_summary.files_copied, 0);
3008        assert_eq!(summary.copy_summary.symlinks_created, 2);
3009        assert_eq!(summary.copy_summary.directories_created, 3);
3010        testutils::check_dirs_identical(
3011            &test_path.join("foo"),
3012            &test_path.join("bar"),
3013            testutils::FileEqualityCheck::Timestamp,
3014        )
3015        .await?;
3016        Ok(())
3017    }
3018
3019    #[tokio::test]
3020    #[traced_test]
3021    async fn test_basic_link_empty_src() -> Result<(), anyhow::Error> {
3022        let tmp_dir = testutils::setup_test_dir().await?;
3023        tokio::fs::create_dir(tmp_dir.join("baz")).await?;
3024        let test_path = tmp_dir.as_path();
3025        let summary = link(
3026            &PROGRESS,
3027            test_path,
3028            &test_path.join("baz"), // empty source
3029            &test_path.join("bar"),
3030            &Some(test_path.join("foo")),
3031            &common_settings(false, false),
3032            false,
3033        )
3034        .await?;
3035        assert_eq!(summary.hard_links_created, 0);
3036        assert_eq!(summary.copy_summary.files_copied, 5);
3037        assert_eq!(summary.copy_summary.symlinks_created, 2);
3038        assert_eq!(summary.copy_summary.directories_created, 3);
3039        testutils::check_dirs_identical(
3040            &test_path.join("foo"),
3041            &test_path.join("bar"),
3042            testutils::FileEqualityCheck::Timestamp,
3043        )
3044        .await?;
3045        Ok(())
3046    }
3047
3048    #[tokio::test]
3049    #[traced_test]
3050    async fn test_link_destination_permission_error_includes_root_cause()
3051    -> Result<(), anyhow::Error> {
3052        let tmp_dir = testutils::setup_test_dir().await?;
3053        let test_path = tmp_dir.as_path();
3054        let readonly_parent = test_path.join("readonly_dest");
3055        tokio::fs::create_dir(&readonly_parent).await?;
3056        tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
3057            .await?;
3058
3059        let mut settings = common_settings(false, false);
3060        settings.copy_settings.fail_early = true;
3061
3062        let result = link(
3063            &PROGRESS,
3064            test_path,
3065            &test_path.join("foo"),
3066            &readonly_parent.join("bar"),
3067            &None,
3068            &settings,
3069            false,
3070        )
3071        .await;
3072
3073        // restore permissions to allow temporary directory cleanup
3074        tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
3075            .await?;
3076
3077        assert!(result.is_err(), "link into read-only parent should fail");
3078        let err = result.unwrap_err();
3079        let err_msg = format!("{:#}", err.source);
3080        assert!(
3081            err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
3082            "Error message must include permission denied text. Got: {}",
3083            err_msg
3084        );
3085        Ok(())
3086    }
3087
3088    #[tokio::test]
3089    #[traced_test]
3090    async fn hard_link_file_into_readonly_parent_returns_error() -> Result<(), anyhow::Error> {
3091        // regression: hard_link_helper used to silently ignore non-AlreadyExists errors
3092        // and report hard_links_created=1 when the underlying hard_link call had failed
3093        let tmp_dir = testutils::setup_test_dir().await?;
3094        let src = tmp_dir.join("src.txt");
3095        tokio::fs::write(&src, "content").await?;
3096        let readonly_parent = tmp_dir.join("readonly_parent");
3097        tokio::fs::create_dir(&readonly_parent).await?;
3098        tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
3099            .await?;
3100        let dst = readonly_parent.join("dst.txt");
3101        let settings = common_settings(false, false);
3102        let result = link(&PROGRESS, &tmp_dir, &src, &dst, &None, &settings, false).await;
3103        tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
3104            .await?;
3105        let err = result.expect_err("link into read-only parent should fail");
3106        assert_eq!(err.summary.hard_links_created, 0);
3107        let err_msg = format!("{:#}", err.source);
3108        assert!(
3109            err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
3110            "error should include root cause, got: {err_msg}"
3111        );
3112        Ok(())
3113    }
3114
3115    pub async fn setup_update_dir(tmp_dir: &std::path::Path) -> Result<(), anyhow::Error> {
3116        // update
3117        // |- 0.txt
3118        // |- bar
3119        //    |- 1.txt
3120        //    |- 2.txt -> ../0.txt
3121        let foo_path = tmp_dir.join("update");
3122        tokio::fs::create_dir(&foo_path).await.unwrap();
3123        tokio::fs::write(foo_path.join("0.txt"), "0-new")
3124            .await
3125            .unwrap();
3126        let bar_path = foo_path.join("bar");
3127        tokio::fs::create_dir(&bar_path).await.unwrap();
3128        tokio::fs::write(bar_path.join("1.txt"), "1-new")
3129            .await
3130            .unwrap();
3131        tokio::fs::symlink("../1.txt", bar_path.join("2.txt"))
3132            .await
3133            .unwrap();
3134        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
3135        Ok(())
3136    }
3137
3138    #[tokio::test]
3139    #[traced_test]
3140    async fn test_link_update() -> Result<(), anyhow::Error> {
3141        let tmp_dir = testutils::setup_test_dir().await?;
3142        setup_update_dir(&tmp_dir).await?;
3143        let test_path = tmp_dir.as_path();
3144        let summary = link(
3145            &PROGRESS,
3146            test_path,
3147            &test_path.join("foo"),
3148            &test_path.join("bar"),
3149            &Some(test_path.join("update")),
3150            &common_settings(false, false),
3151            false,
3152        )
3153        .await?;
3154        assert_eq!(summary.hard_links_created, 2);
3155        assert_eq!(summary.copy_summary.files_copied, 2);
3156        assert_eq!(summary.copy_summary.symlinks_created, 3);
3157        assert_eq!(summary.copy_summary.directories_created, 3);
3158        // compare subset of src and dst
3159        testutils::check_dirs_identical(
3160            &test_path.join("foo").join("baz"),
3161            &test_path.join("bar").join("baz"),
3162            testutils::FileEqualityCheck::HardLink,
3163        )
3164        .await?;
3165        // compare update and dst
3166        testutils::check_dirs_identical(
3167            &test_path.join("update"),
3168            &test_path.join("bar"),
3169            testutils::FileEqualityCheck::Timestamp,
3170        )
3171        .await?;
3172        Ok(())
3173    }
3174
3175    #[tokio::test]
3176    #[traced_test]
3177    async fn test_link_update_exclusive() -> Result<(), anyhow::Error> {
3178        let tmp_dir = testutils::setup_test_dir().await?;
3179        setup_update_dir(&tmp_dir).await?;
3180        let test_path = tmp_dir.as_path();
3181        let mut settings = common_settings(false, false);
3182        settings.update_exclusive = true;
3183        let summary = link(
3184            &PROGRESS,
3185            test_path,
3186            &test_path.join("foo"),
3187            &test_path.join("bar"),
3188            &Some(test_path.join("update")),
3189            &settings,
3190            false,
3191        )
3192        .await?;
3193        // we should end up with same directory as the update
3194        // |- 0.txt
3195        // |- bar
3196        //    |- 1.txt
3197        //    |- 2.txt -> ../0.txt
3198        assert_eq!(summary.hard_links_created, 0);
3199        assert_eq!(summary.copy_summary.files_copied, 2);
3200        assert_eq!(summary.copy_summary.symlinks_created, 1);
3201        assert_eq!(summary.copy_summary.directories_created, 2);
3202        // compare update and dst
3203        testutils::check_dirs_identical(
3204            &test_path.join("update"),
3205            &test_path.join("bar"),
3206            testutils::FileEqualityCheck::Timestamp,
3207        )
3208        .await?;
3209        Ok(())
3210    }
3211
3212    async fn setup_test_dir_and_link() -> Result<std::path::PathBuf, anyhow::Error> {
3213        let tmp_dir = testutils::setup_test_dir().await?;
3214        let test_path = tmp_dir.as_path();
3215        let summary = link(
3216            &PROGRESS,
3217            test_path,
3218            &test_path.join("foo"),
3219            &test_path.join("bar"),
3220            &None,
3221            &common_settings(false, false),
3222            false,
3223        )
3224        .await?;
3225        assert_eq!(summary.hard_links_created, 5);
3226        assert_eq!(summary.copy_summary.symlinks_created, 2);
3227        assert_eq!(summary.copy_summary.directories_created, 3);
3228        Ok(tmp_dir)
3229    }
3230
3231    #[tokio::test]
3232    #[traced_test]
3233    async fn test_link_overwrite_basic() -> Result<(), anyhow::Error> {
3234        let tmp_dir = setup_test_dir_and_link().await?;
3235        let output_path = &tmp_dir.join("bar");
3236        {
3237            // bar
3238            // |- 0.txt
3239            // |- bar  <---------------------------------------- REMOVE
3240            //    |- 1.txt  <----------------------------------- REMOVE
3241            //    |- 2.txt  <----------------------------------- REMOVE
3242            //    |- 3.txt  <----------------------------------- REMOVE
3243            // |- baz
3244            //    |- 4.txt
3245            //    |- 5.txt -> ../bar/2.txt <-------------------- REMOVE
3246            //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
3247            let summary = rm::rm(
3248                &PROGRESS,
3249                &output_path.join("bar"),
3250                &rm::Settings {
3251                    fail_early: false,
3252                    filter: None,
3253                    dry_run: None,
3254                    time_filter: None,
3255                },
3256            )
3257            .await?
3258                + rm::rm(
3259                    &PROGRESS,
3260                    &output_path.join("baz").join("5.txt"),
3261                    &rm::Settings {
3262                        fail_early: false,
3263                        filter: None,
3264                        dry_run: None,
3265                        time_filter: None,
3266                    },
3267                )
3268                .await?;
3269            assert_eq!(summary.files_removed, 3);
3270            assert_eq!(summary.symlinks_removed, 1);
3271            assert_eq!(summary.directories_removed, 1);
3272        }
3273        let summary = link(
3274            &PROGRESS,
3275            &tmp_dir,
3276            &tmp_dir.join("foo"),
3277            output_path,
3278            &None,
3279            &common_settings(false, true), // overwrite!
3280            false,
3281        )
3282        .await?;
3283        assert_eq!(summary.hard_links_created, 3);
3284        assert_eq!(summary.copy_summary.symlinks_created, 1);
3285        assert_eq!(summary.copy_summary.directories_created, 1);
3286        testutils::check_dirs_identical(
3287            &tmp_dir.join("foo"),
3288            output_path,
3289            testutils::FileEqualityCheck::Timestamp,
3290        )
3291        .await?;
3292        Ok(())
3293    }
3294
3295    #[tokio::test]
3296    #[traced_test]
3297    async fn test_link_update_overwrite_basic() -> Result<(), anyhow::Error> {
3298        let tmp_dir = setup_test_dir_and_link().await?;
3299        let output_path = &tmp_dir.join("bar");
3300        {
3301            // bar
3302            // |- 0.txt
3303            // |- bar  <---------------------------------------- REMOVE
3304            //    |- 1.txt  <----------------------------------- REMOVE
3305            //    |- 2.txt  <----------------------------------- REMOVE
3306            //    |- 3.txt  <----------------------------------- REMOVE
3307            // |- baz
3308            //    |- 4.txt
3309            //    |- 5.txt -> ../bar/2.txt <-------------------- REMOVE
3310            //    |- 6.txt -> (absolute path) .../foo/bar/3.txt
3311            let summary = rm::rm(
3312                &PROGRESS,
3313                &output_path.join("bar"),
3314                &rm::Settings {
3315                    fail_early: false,
3316                    filter: None,
3317                    dry_run: None,
3318                    time_filter: None,
3319                },
3320            )
3321            .await?
3322                + rm::rm(
3323                    &PROGRESS,
3324                    &output_path.join("baz").join("5.txt"),
3325                    &rm::Settings {
3326                        fail_early: false,
3327                        filter: None,
3328                        dry_run: None,
3329                        time_filter: None,
3330                    },
3331                )
3332                .await?;
3333            assert_eq!(summary.files_removed, 3);
3334            assert_eq!(summary.symlinks_removed, 1);
3335            assert_eq!(summary.directories_removed, 1);
3336        }
3337        setup_update_dir(&tmp_dir).await?;
3338        // update
3339        // |- 0.txt
3340        // |- bar
3341        //    |- 1.txt
3342        //    |- 2.txt -> ../0.txt
3343        let summary = link(
3344            &PROGRESS,
3345            &tmp_dir,
3346            &tmp_dir.join("foo"),
3347            output_path,
3348            &Some(tmp_dir.join("update")),
3349            &common_settings(false, true), // overwrite!
3350            false,
3351        )
3352        .await?;
3353        assert_eq!(summary.hard_links_created, 1); // 3.txt
3354        assert_eq!(summary.copy_summary.files_copied, 2); // 0.txt, 1.txt
3355        assert_eq!(summary.copy_summary.symlinks_created, 2); // 2.txt, 5.txt
3356        assert_eq!(summary.copy_summary.directories_created, 1);
3357        // compare subset of src and dst
3358        testutils::check_dirs_identical(
3359            &tmp_dir.join("foo").join("baz"),
3360            &tmp_dir.join("bar").join("baz"),
3361            testutils::FileEqualityCheck::HardLink,
3362        )
3363        .await?;
3364        // compare update and dst
3365        testutils::check_dirs_identical(
3366            &tmp_dir.join("update"),
3367            &tmp_dir.join("bar"),
3368            testutils::FileEqualityCheck::Timestamp,
3369        )
3370        .await?;
3371        Ok(())
3372    }
3373
3374    #[tokio::test]
3375    #[traced_test]
3376    async fn test_link_overwrite_hardlink_file() -> Result<(), anyhow::Error> {
3377        let tmp_dir = setup_test_dir_and_link().await?;
3378        let output_path = &tmp_dir.join("bar");
3379        {
3380            // bar
3381            // |- 0.txt
3382            // |- bar
3383            //    |- 1.txt  <----------------------------------- REPLACE W/ FILE
3384            //    |- 2.txt  <----------------------------------- REPLACE W/ SYMLINK
3385            //    |- 3.txt  <----------------------------------- REPLACE W/ DIRECTORY
3386            // |- baz    <-------------------------------------- REPLACE W/ FILE
3387            //    |- ...
3388            let bar_path = output_path.join("bar");
3389            let summary = rm::rm(
3390                &PROGRESS,
3391                &bar_path.join("1.txt"),
3392                &rm::Settings {
3393                    fail_early: false,
3394                    filter: None,
3395                    dry_run: None,
3396                    time_filter: None,
3397                },
3398            )
3399            .await?
3400                + rm::rm(
3401                    &PROGRESS,
3402                    &bar_path.join("2.txt"),
3403                    &rm::Settings {
3404                        fail_early: false,
3405                        filter: None,
3406                        dry_run: None,
3407                        time_filter: None,
3408                    },
3409                )
3410                .await?
3411                + rm::rm(
3412                    &PROGRESS,
3413                    &bar_path.join("3.txt"),
3414                    &rm::Settings {
3415                        fail_early: false,
3416                        filter: None,
3417                        dry_run: None,
3418                        time_filter: None,
3419                    },
3420                )
3421                .await?
3422                + rm::rm(
3423                    &PROGRESS,
3424                    &output_path.join("baz"),
3425                    &rm::Settings {
3426                        fail_early: false,
3427                        filter: None,
3428                        dry_run: None,
3429                        time_filter: None,
3430                    },
3431                )
3432                .await?;
3433            assert_eq!(summary.files_removed, 4);
3434            assert_eq!(summary.symlinks_removed, 2);
3435            assert_eq!(summary.directories_removed, 1);
3436            // REPLACE with a file, a symlink, a directory and a file
3437            tokio::fs::write(bar_path.join("1.txt"), "1-new")
3438                .await
3439                .unwrap();
3440            tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
3441                .await
3442                .unwrap();
3443            tokio::fs::create_dir(&bar_path.join("3.txt"))
3444                .await
3445                .unwrap();
3446            tokio::fs::write(&output_path.join("baz"), "baz")
3447                .await
3448                .unwrap();
3449        }
3450        let summary = link(
3451            &PROGRESS,
3452            &tmp_dir,
3453            &tmp_dir.join("foo"),
3454            output_path,
3455            &None,
3456            &common_settings(false, true), // overwrite!
3457            false,
3458        )
3459        .await?;
3460        assert_eq!(summary.hard_links_created, 4);
3461        assert_eq!(summary.copy_summary.files_copied, 0);
3462        assert_eq!(summary.copy_summary.symlinks_created, 2);
3463        assert_eq!(summary.copy_summary.directories_created, 1);
3464        testutils::check_dirs_identical(
3465            &tmp_dir.join("foo"),
3466            &tmp_dir.join("bar"),
3467            testutils::FileEqualityCheck::HardLink,
3468        )
3469        .await?;
3470        Ok(())
3471    }
3472
3473    #[tokio::test]
3474    #[traced_test]
3475    async fn test_link_overwrite_error() -> Result<(), anyhow::Error> {
3476        let tmp_dir = setup_test_dir_and_link().await?;
3477        let output_path = &tmp_dir.join("bar");
3478        {
3479            // bar
3480            // |- 0.txt
3481            // |- bar
3482            //    |- 1.txt  <----------------------------------- REPLACE W/ FILE
3483            //    |- 2.txt  <----------------------------------- REPLACE W/ SYMLINK
3484            //    |- 3.txt  <----------------------------------- REPLACE W/ DIRECTORY
3485            // |- baz    <-------------------------------------- REPLACE W/ FILE
3486            //    |- ...
3487            let bar_path = output_path.join("bar");
3488            let summary = rm::rm(
3489                &PROGRESS,
3490                &bar_path.join("1.txt"),
3491                &rm::Settings {
3492                    fail_early: false,
3493                    filter: None,
3494                    dry_run: None,
3495                    time_filter: None,
3496                },
3497            )
3498            .await?
3499                + rm::rm(
3500                    &PROGRESS,
3501                    &bar_path.join("2.txt"),
3502                    &rm::Settings {
3503                        fail_early: false,
3504                        filter: None,
3505                        dry_run: None,
3506                        time_filter: None,
3507                    },
3508                )
3509                .await?
3510                + rm::rm(
3511                    &PROGRESS,
3512                    &bar_path.join("3.txt"),
3513                    &rm::Settings {
3514                        fail_early: false,
3515                        filter: None,
3516                        dry_run: None,
3517                        time_filter: None,
3518                    },
3519                )
3520                .await?
3521                + rm::rm(
3522                    &PROGRESS,
3523                    &output_path.join("baz"),
3524                    &rm::Settings {
3525                        fail_early: false,
3526                        filter: None,
3527                        dry_run: None,
3528                        time_filter: None,
3529                    },
3530                )
3531                .await?;
3532            assert_eq!(summary.files_removed, 4);
3533            assert_eq!(summary.symlinks_removed, 2);
3534            assert_eq!(summary.directories_removed, 1);
3535            // REPLACE with a file, a symlink, a directory and a file
3536            tokio::fs::write(bar_path.join("1.txt"), "1-new")
3537                .await
3538                .unwrap();
3539            tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
3540                .await
3541                .unwrap();
3542            tokio::fs::create_dir(&bar_path.join("3.txt"))
3543                .await
3544                .unwrap();
3545            tokio::fs::write(&output_path.join("baz"), "baz")
3546                .await
3547                .unwrap();
3548        }
3549        let source_path = &tmp_dir.join("foo");
3550        // unreadable
3551        tokio::fs::set_permissions(
3552            &source_path.join("baz"),
3553            std::fs::Permissions::from_mode(0o000),
3554        )
3555        .await?;
3556        // bar
3557        // |- ...
3558        // |- baz <- NON READABLE
3559        match link(
3560            &PROGRESS,
3561            &tmp_dir,
3562            &tmp_dir.join("foo"),
3563            output_path,
3564            &None,
3565            &common_settings(false, true), // overwrite!
3566            false,
3567        )
3568        .await
3569        {
3570            Ok(_) => panic!("Expected the link to error!"),
3571            Err(error) => {
3572                tracing::info!("{:#}", &error);
3573                assert_eq!(error.summary.hard_links_created, 3);
3574                assert_eq!(error.summary.copy_summary.files_copied, 0);
3575                assert_eq!(error.summary.copy_summary.symlinks_created, 0);
3576                assert_eq!(error.summary.copy_summary.directories_created, 0);
3577                assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 1);
3578                assert_eq!(error.summary.copy_summary.rm_summary.directories_removed, 1);
3579                assert_eq!(error.summary.copy_summary.rm_summary.symlinks_removed, 1);
3580            }
3581        }
3582        Ok(())
3583    }
3584
3585    /// Verify that directory metadata is applied even when child link operations fail.
3586    /// This is a regression test for a bug where directory permissions were not preserved
3587    /// when linking with fail_early=false and some children failed to link.
3588    #[tokio::test]
3589    #[traced_test]
3590    async fn test_link_directory_metadata_applied_on_child_error() -> Result<(), anyhow::Error> {
3591        let tmp_dir = testutils::create_temp_dir().await?;
3592        let test_path = tmp_dir.as_path();
3593        // create source directory with specific permissions
3594        let src_dir = test_path.join("src");
3595        tokio::fs::create_dir(&src_dir).await?;
3596        tokio::fs::set_permissions(&src_dir, std::fs::Permissions::from_mode(0o750)).await?;
3597        // create a readable file (will be linked successfully)
3598        tokio::fs::write(src_dir.join("readable.txt"), "content").await?;
3599        // create a subdirectory with a file, then make the subdirectory unreadable
3600        // this will cause the recursive walk to fail when trying to read subdirectory contents
3601        let unreadable_subdir = src_dir.join("unreadable_subdir");
3602        tokio::fs::create_dir(&unreadable_subdir).await?;
3603        tokio::fs::write(unreadable_subdir.join("hidden.txt"), "secret").await?;
3604        tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o000))
3605            .await?;
3606        let dst_dir = test_path.join("dst");
3607        // link with fail_early=false
3608        let result = link(
3609            &PROGRESS,
3610            test_path,
3611            &src_dir,
3612            &dst_dir,
3613            &None,
3614            &common_settings(false, false),
3615            false,
3616        )
3617        .await;
3618        // restore permissions so cleanup can succeed
3619        tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o755))
3620            .await?;
3621        // verify the operation returned an error (unreadable subdirectory should fail)
3622        assert!(
3623            result.is_err(),
3624            "link should fail due to unreadable subdirectory"
3625        );
3626        let error = result.unwrap_err();
3627        // verify the readable file was linked successfully
3628        assert_eq!(error.summary.hard_links_created, 1);
3629        // verify the destination directory exists and has the correct permissions
3630        let dst_metadata = tokio::fs::metadata(&dst_dir).await?;
3631        assert!(dst_metadata.is_dir());
3632        let actual_mode = dst_metadata.permissions().mode() & 0o7777;
3633        assert_eq!(
3634            actual_mode, 0o750,
3635            "directory should have preserved source permissions (0o750), got {:o}",
3636            actual_mode
3637        );
3638        Ok(())
3639    }
3640    mod filter_tests {
3641        use super::*;
3642        use crate::filter::FilterSettings;
3643
3644        async fn run_with_open_file_cleanup<F>(
3645            admission: &testutils::AdmissionLimit,
3646            operation: F,
3647        ) -> Result<F::Output, anyhow::Error>
3648        where
3649            F: std::future::Future,
3650        {
3651            let output = admission
3652                .run_with_timeout(std::time::Duration::from_secs(20), operation)
3653                .await
3654                .context("admission-sensitive filter operation did not finish")?;
3655            let permit = admission
3656                .run_with_timeout(
3657                    std::time::Duration::from_secs(20),
3658                    throttle::open_file_permit(),
3659                )
3660                .await
3661                .context("filter operation did not return open-file capacity")?;
3662            drop(permit);
3663            Ok(output)
3664        }
3665
3666        /// Test that path-based patterns (with /) work correctly with nested paths.
3667        #[tokio::test]
3668        #[traced_test]
3669        async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
3670            let tmp_dir = testutils::setup_test_dir().await?;
3671            let test_path = tmp_dir.as_path();
3672            // create filter that should only link files in bar/ directory
3673            let mut filter = FilterSettings::new();
3674            filter.add_include("bar/*.txt").unwrap();
3675            let summary = link(
3676                &PROGRESS,
3677                test_path,
3678                &test_path.join("foo"),
3679                &test_path.join("dst"),
3680                &None,
3681                &Settings {
3682                    copy_settings: CopySettings {
3683                        reflink: Default::default(),
3684                        local_copy_handoff: Default::default(),
3685                        dereference: false,
3686                        fail_early: false,
3687                        overwrite: false,
3688                        overwrite_compare: Default::default(),
3689                        overwrite_filter: None,
3690                        ignore_existing: false,
3691                        chunk_size: 0,
3692                        skip_specials: false,
3693                        remote_copy_buffer_size: 0,
3694                        filter: None,
3695                        dry_run: None,
3696                        delete: None,
3697                    },
3698                    update_compare: Default::default(),
3699                    update_exclusive: false,
3700                    filter: Some(filter),
3701                    dry_run: None,
3702                    preserve: preserve::preserve_all(),
3703                },
3704                false,
3705            )
3706            .await?;
3707            // should only link files matching bar/*.txt pattern (bar/1.txt, bar/2.txt, bar/3.txt)
3708            assert_eq!(
3709                summary.hard_links_created, 3,
3710                "should link 3 files matching bar/*.txt"
3711            );
3712            // verify the right files were linked
3713            assert!(
3714                test_path.join("dst/bar/1.txt").exists(),
3715                "bar/1.txt should be linked"
3716            );
3717            assert!(
3718                test_path.join("dst/bar/2.txt").exists(),
3719                "bar/2.txt should be linked"
3720            );
3721            assert!(
3722                test_path.join("dst/bar/3.txt").exists(),
3723                "bar/3.txt should be linked"
3724            );
3725            // verify files outside the pattern don't exist
3726            assert!(
3727                !test_path.join("dst/0.txt").exists(),
3728                "0.txt should not be linked"
3729            );
3730            Ok(())
3731        }
3732        /// Regression: with a filter active and `fail_early = false`, a directory whose only
3733        /// traversed child FAILS becomes "empty" and is pruned by the empty-dir cleanup — the child
3734        /// failure must still surface, not be masked as success. copy.rs's `finalize_dir` guards
3735        /// this in its DryRunSkip/Remove arms; `link_dir_contents` must do the same.
3736        #[tokio::test]
3737        #[traced_test]
3738        async fn test_filter_pruned_empty_dir_surfaces_child_error() -> Result<(), anyhow::Error> {
3739            let tmp_dir = testutils::create_temp_dir().await?;
3740            let test_path = tmp_dir.as_path();
3741            // src/ is the root; src/sub/ is traversal-only under the filter (it does not directly
3742            // match), and its sole child `unreadable/` (mode 0o000) fails to open during the walk.
3743            // nothing links into sub/, so the empty-dir cleanup prunes it.
3744            let src_dir = test_path.join("src");
3745            let unreadable = src_dir.join("sub").join("unreadable");
3746            tokio::fs::create_dir_all(&unreadable).await?;
3747            tokio::fs::write(unreadable.join("x.txt"), "secret").await?;
3748            tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
3749            // an include pattern that matches nothing present forces traversal of sub/ and
3750            // unreadable/ without directly matching sub/, so sub/ is "traversal-only".
3751            let mut filter = FilterSettings::new();
3752            filter.add_include("*.match").unwrap();
3753            let mut settings = common_settings(false, false);
3754            settings.filter = Some(filter);
3755            let result = link(
3756                &PROGRESS,
3757                test_path,
3758                &src_dir,
3759                &test_path.join("dst"),
3760                &None,
3761                &settings,
3762                false,
3763            )
3764            .await;
3765            // restore perms so the temp dir can be cleaned up
3766            tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).await?;
3767            assert!(
3768                result.is_err(),
3769                "a child link failure inside a filter-pruned empty directory must surface as an \
3770                 error, not be masked as success"
3771            );
3772            Ok(())
3773        }
3774        /// As above but in dry-run mode, which hits the `DryRunSkip` arm instead of `Remove`: a
3775        /// collected child error must still surface rather than being reported as a clean dry run.
3776        #[tokio::test]
3777        #[traced_test]
3778        async fn test_filter_pruned_empty_dir_surfaces_child_error_dry_run()
3779        -> Result<(), anyhow::Error> {
3780            let tmp_dir = testutils::create_temp_dir().await?;
3781            let test_path = tmp_dir.as_path();
3782            let src_dir = test_path.join("src");
3783            let unreadable = src_dir.join("sub").join("unreadable");
3784            tokio::fs::create_dir_all(&unreadable).await?;
3785            tokio::fs::write(unreadable.join("x.txt"), "secret").await?;
3786            tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
3787            let mut filter = FilterSettings::new();
3788            filter.add_include("*.match").unwrap();
3789            let mut settings = common_settings(false, false);
3790            settings.filter = Some(filter);
3791            settings.dry_run = Some(crate::config::DryRunMode::Brief);
3792            settings.copy_settings.dry_run = Some(crate::config::DryRunMode::Brief);
3793            let result = link(
3794                &PROGRESS,
3795                test_path,
3796                &src_dir,
3797                &test_path.join("dst"),
3798                &None,
3799                &settings,
3800                false,
3801            )
3802            .await;
3803            tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).await?;
3804            assert!(
3805                result.is_err(),
3806                "dry-run must also surface the child error, not report a clean run"
3807            );
3808            Ok(())
3809        }
3810        /// Test that filters are applied to top-level file arguments.
3811        #[tokio::test]
3812        #[traced_test]
3813        async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
3814            let tmp_dir = testutils::setup_test_dir().await?;
3815            let test_path = tmp_dir.as_path();
3816            // create filter that excludes .txt files
3817            let mut filter = FilterSettings::new();
3818            filter.add_exclude("*.txt").unwrap();
3819            let summary = link(
3820                &PROGRESS,
3821                test_path,
3822                &test_path.join("foo/0.txt"), // single file source
3823                &test_path.join("dst/0.txt"),
3824                &None,
3825                &Settings {
3826                    copy_settings: CopySettings {
3827                        reflink: Default::default(),
3828                        local_copy_handoff: Default::default(),
3829                        dereference: false,
3830                        fail_early: false,
3831                        overwrite: false,
3832                        overwrite_compare: Default::default(),
3833                        overwrite_filter: None,
3834                        ignore_existing: false,
3835                        chunk_size: 0,
3836                        skip_specials: false,
3837                        remote_copy_buffer_size: 0,
3838                        filter: None,
3839                        dry_run: None,
3840                        delete: None,
3841                    },
3842                    update_compare: Default::default(),
3843                    update_exclusive: false,
3844                    filter: Some(filter),
3845                    dry_run: None,
3846                    preserve: preserve::preserve_all(),
3847                },
3848                false,
3849            )
3850            .await?;
3851            // the file should NOT be linked because it matches the exclude pattern
3852            assert_eq!(
3853                summary.hard_links_created, 0,
3854                "file matching exclude pattern should not be linked"
3855            );
3856            assert!(
3857                !test_path.join("dst/0.txt").exists(),
3858                "excluded file should not exist at destination"
3859            );
3860            Ok(())
3861        }
3862        /// An update root is filtered under the source root's logical name in union mode.
3863        #[tokio::test]
3864        #[traced_test]
3865        async fn update_root_filter_uses_source_name_in_union_mode() -> Result<(), anyhow::Error> {
3866            let test_path = testutils::create_temp_dir().await?;
3867            let src = test_path.join("foo");
3868            let update = test_path.join("bar");
3869            let dst = test_path.join("dst");
3870            tokio::fs::write(&src, "SRC").await?;
3871            tokio::fs::write(&update, "UPDATED").await?;
3872            let mut filter = FilterSettings::new();
3873            filter.add_include("foo").unwrap();
3874            let mut settings = common_settings(false, false);
3875            settings.copy_settings.filter = Some(filter.clone());
3876            settings.filter = Some(filter);
3877            let summary = link(
3878                &PROGRESS,
3879                &test_path,
3880                &src,
3881                &dst,
3882                &Some(update),
3883                &settings,
3884                false,
3885            )
3886            .await?;
3887            assert_eq!(tokio::fs::read_to_string(&dst).await?, "UPDATED");
3888            assert_eq!(summary.copy_summary.files_copied, 1);
3889            Ok(())
3890        }
3891        /// An update root is filtered under the source root's logical name in exclusive mode.
3892        #[tokio::test]
3893        #[traced_test]
3894        async fn update_root_filter_uses_source_name_in_exclusive_mode() -> Result<(), anyhow::Error>
3895        {
3896            let test_path = testutils::create_temp_dir().await?;
3897            let src = test_path.join("foo");
3898            let update = test_path.join("bar");
3899            let dst = test_path.join("dst");
3900            tokio::fs::write(&src, "SRC").await?;
3901            tokio::fs::write(&update, "UPDATED").await?;
3902            let mut filter = FilterSettings::new();
3903            filter.add_include("foo").unwrap();
3904            let mut settings = common_settings(false, false);
3905            settings.update_exclusive = true;
3906            settings.copy_settings.filter = Some(filter.clone());
3907            settings.filter = Some(filter);
3908            let summary = link(
3909                &PROGRESS,
3910                &test_path,
3911                &src,
3912                &dst,
3913                &Some(update),
3914                &settings,
3915                false,
3916            )
3917            .await?;
3918            assert_eq!(tokio::fs::read_to_string(&dst).await?, "UPDATED");
3919            assert_eq!(summary.copy_summary.files_copied, 1);
3920            Ok(())
3921        }
3922        /// A filter-passing update directory keeps a root excluded for the source-file type.
3923        #[tokio::test]
3924        #[traced_test]
3925        async fn update_directory_can_include_root_excluded_for_source_file()
3926        -> Result<(), anyhow::Error> {
3927            let test_path = testutils::create_temp_dir().await?;
3928            let src_parent = test_path.join("source");
3929            let update_parent = test_path.join("update");
3930            let src = src_parent.join("data");
3931            let update = update_parent.join("data");
3932            let dst = test_path.join("dst");
3933            tokio::fs::create_dir(&src_parent).await?;
3934            tokio::fs::create_dir(&update_parent).await?;
3935            tokio::fs::write(&src, "SOURCE-FILE").await?;
3936            tokio::fs::create_dir(&update).await?;
3937            tokio::fs::write(update.join("inner.txt"), "UPDATE-DIR").await?;
3938            let mut filter = FilterSettings::new();
3939            filter.add_include("data/").unwrap();
3940            filter.add_include("data/**").unwrap();
3941            let mut settings = common_settings(false, false);
3942            settings.filter = Some(filter);
3943            let summary = link(
3944                &PROGRESS,
3945                &test_path,
3946                &src,
3947                &dst,
3948                &Some(update),
3949                &settings,
3950                false,
3951            )
3952            .await?;
3953            assert_eq!(
3954                tokio::fs::read_to_string(dst.join("inner.txt")).await?,
3955                "UPDATE-DIR"
3956            );
3957            assert_eq!(summary.copy_summary.files_copied, 1);
3958            Ok(())
3959        }
3960        /// A filter-selected update file cannot authorize a replacement directory.
3961        #[tokio::test]
3962        #[traced_test]
3963        async fn filtered_update_file_swap_to_directory_never_materializes_replacement()
3964        -> Result<(), anyhow::Error> {
3965            let test_path = testutils::create_temp_dir().await?;
3966            let src = test_path.join("src");
3967            let update = test_path.join("update");
3968            let dst = test_path.join("dst");
3969            tokio::fs::write(&src, "SRC").await?;
3970            tokio::fs::write(&update, "SELECTED-UPDATE-FILE").await?;
3971
3972            let admission_limits = testutils::AdmissionLimit::new().await;
3973            admission_limits.set_files_in_flight(1);
3974            let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
3975            let src_parent = Arc::new(
3976                Dir::open_parent_dir(&test_path, congestion::Side::Source)
3977                    .await?
3978                    .into_tree(),
3979            );
3980            let dst_parent = Arc::new(
3981                Dir::open_parent_dir(&test_path, congestion::Side::Destination)
3982                    .await?
3983                    .into_tree(),
3984            );
3985            let src_handle = src_parent.child(std::ffi::OsStr::new("src")).await?;
3986            let update_handle = src_parent.child(std::ffi::OsStr::new("update")).await?;
3987
3988            let mut filter = FilterSettings::new();
3989            filter.add_exclude("src/")?;
3990            assert!(matches!(
3991                select_filtered_root(
3992                    &filter,
3993                    std::ffi::OsStr::new("src"),
3994                    src_handle.kind(),
3995                    Some(update_handle.kind()),
3996                    false,
3997                ),
3998                RootFilterSelection::WithUpdate
3999            ));
4000            let mut entry = AdmittedLinkEntry::new(src_handle, permit);
4001            entry.update_handle = Some(update_handle);
4002
4003            // replace the selected file after filtering. the replacement directory is excluded by
4004            // the same root rule and must never become the object delegated to copy.
4005            tokio::fs::remove_file(&update).await?;
4006            tokio::fs::create_dir(&update).await?;
4007            tokio::fs::write(update.join("replacement.txt"), "UNSELECTED").await?;
4008            let mut settings = common_settings(false, false);
4009            settings.filter = Some(filter);
4010
4011            let result = run_with_open_file_cleanup(
4012                &admission_limits,
4013                link_internal(
4014                    &PROGRESS,
4015                    &src_parent,
4016                    Some((&src_parent, std::ffi::OsStr::new("update"))),
4017                    Some(&dst_parent),
4018                    std::ffi::OsStr::new("src"),
4019                    &src,
4020                    &dst,
4021                    Some(&update),
4022                    std::path::Path::new(""),
4023                    UpdateRootRequirement::Optional,
4024                    &settings,
4025                    false,
4026                    LinkEntryAdmission::Filtered(entry),
4027                    copy::DeleteScanAnchor::new(&dst, std::path::Path::new("")),
4028                ),
4029            )
4030            .await?;
4031
4032            assert!(
4033                result.is_err(),
4034                "a selected file reopened as a directory must fail closed"
4035            );
4036            assert!(
4037                !dst.exists(),
4038                "a failed-closed type swap must not create a destination"
4039            );
4040            Ok(())
4041        }
4042
4043        /// A source-only symlink selected by type cannot authorize a replacement directory.
4044        #[tokio::test]
4045        #[traced_test]
4046        async fn filtered_source_only_symlink_swap_to_directory_never_materializes_replacement()
4047        -> Result<(), anyhow::Error> {
4048            let test_path = testutils::create_temp_dir().await?;
4049            let src = test_path.join("src");
4050            let update = test_path.join("update");
4051            let dst = test_path.join("dst");
4052            tokio::fs::write(test_path.join("target"), "TARGET").await?;
4053            tokio::fs::symlink("target", &src).await?;
4054            tokio::fs::create_dir(&update).await?;
4055
4056            let admission_limits = testutils::AdmissionLimit::new().await;
4057            admission_limits.set_files_in_flight(1);
4058            let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
4059            let parent = Arc::new(
4060                Dir::open_parent_dir(&test_path, congestion::Side::Source)
4061                    .await?
4062                    .into_tree(),
4063            );
4064            let dst_parent = Arc::new(
4065                Dir::open_parent_dir(&test_path, congestion::Side::Destination)
4066                    .await?
4067                    .into_tree(),
4068            );
4069            let src_handle = parent.child(std::ffi::OsStr::new("src")).await?;
4070            let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
4071            let mut filter = FilterSettings::new();
4072            filter.add_exclude("src/")?;
4073            assert!(matches!(
4074                select_filtered_root(
4075                    &filter,
4076                    std::ffi::OsStr::new("src"),
4077                    src_handle.kind(),
4078                    Some(update_handle.kind()),
4079                    false,
4080                ),
4081                RootFilterSelection::SourceOnly
4082            ));
4083            drop(update_handle);
4084            let entry = AdmittedLinkEntry::new(src_handle, permit);
4085
4086            // replace the selected symlink after the joint filter decision. the replacement
4087            // directory is excluded by that same logical root rule.
4088            tokio::fs::remove_file(&src).await?;
4089            tokio::fs::create_dir(&src).await?;
4090            tokio::fs::write(src.join("replacement.txt"), "UNSELECTED").await?;
4091            let mut settings = common_settings(false, false);
4092            settings.filter = Some(filter.clone());
4093            settings.copy_settings.filter = Some(filter);
4094
4095            run_with_open_file_cleanup(
4096                &admission_limits,
4097                link_internal(
4098                    &PROGRESS,
4099                    &parent,
4100                    Some((&parent, std::ffi::OsStr::new("update"))),
4101                    Some(&dst_parent),
4102                    std::ffi::OsStr::new("src"),
4103                    &src,
4104                    &dst,
4105                    Some(&update),
4106                    std::path::Path::new(""),
4107                    UpdateRootRequirement::Optional,
4108                    &settings,
4109                    false,
4110                    LinkEntryAdmission::Filtered(entry),
4111                    copy::DeleteScanAnchor::new(&dst, std::path::Path::new("")),
4112                ),
4113            )
4114            .await??;
4115
4116            assert!(
4117                !dst.is_dir(),
4118                "the replacement directory passed the selected symlink's filter decision"
4119            );
4120            assert_eq!(
4121                tokio::fs::read_link(&dst).await?,
4122                std::path::Path::new("target")
4123            );
4124            Ok(())
4125        }
4126
4127        /// A same-type replacement remains the by-name payload copied after admitted selection.
4128        #[tokio::test]
4129        #[traced_test]
4130        async fn admitted_update_file_swap_to_file_copies_replacement_content()
4131        -> Result<(), anyhow::Error> {
4132            let test_path = testutils::create_temp_dir().await?;
4133            let src = test_path.join("src");
4134            let update = test_path.join("update");
4135            let dst = test_path.join("dst");
4136            tokio::fs::write(&src, "S").await?;
4137            tokio::fs::write(&update, "SELECTED-UPDATE").await?;
4138
4139            let admission_limits = testutils::AdmissionLimit::new().await;
4140            admission_limits.set_files_in_flight(1);
4141            let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
4142            let parent = Arc::new(
4143                Dir::open_parent_dir(&test_path, congestion::Side::Source)
4144                    .await?
4145                    .into_tree(),
4146            );
4147            let dst_parent = Arc::new(
4148                Dir::open_parent_dir(&test_path, congestion::Side::Destination)
4149                    .await?
4150                    .into_tree(),
4151            );
4152            let src_handle = parent.child(std::ffi::OsStr::new("src")).await?;
4153            let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
4154            let mut entry = AdmittedLinkEntry::new(src_handle, permit);
4155            entry.update_handle = Some(update_handle);
4156
4157            tokio::fs::remove_file(&update).await?;
4158            tokio::fs::write(&update, "REPLACEMENT-CONTENT").await?;
4159            run_with_open_file_cleanup(
4160                &admission_limits,
4161                link_internal(
4162                    &PROGRESS,
4163                    &parent,
4164                    Some((&parent, std::ffi::OsStr::new("update"))),
4165                    Some(&dst_parent),
4166                    std::ffi::OsStr::new("src"),
4167                    &src,
4168                    &dst,
4169                    Some(&update),
4170                    std::path::Path::new(""),
4171                    UpdateRootRequirement::Optional,
4172                    &common_settings(false, false),
4173                    false,
4174                    LinkEntryAdmission::Filtered(entry),
4175                    copy::DeleteScanAnchor::new(&dst, std::path::Path::new("")),
4176                ),
4177            )
4178            .await??;
4179
4180            assert_eq!(
4181                tokio::fs::read_to_string(&dst).await?,
4182                "REPLACEMENT-CONTENT"
4183            );
4184            Ok(())
4185        }
4186
4187        /// A forced-unknown update-only file cannot authorize an excluded replacement directory.
4188        #[tokio::test]
4189        #[traced_test]
4190        async fn update_only_unknown_file_swap_to_excluded_directory_never_materializes_replacement()
4191        -> Result<(), anyhow::Error> {
4192            let test_path = testutils::create_temp_dir().await?;
4193            let update = test_path.join("update");
4194            let dst = test_path.join("dst");
4195            let admission_limits = testutils::AdmissionLimit::new().await;
4196            admission_limits.set_files_in_flight(1);
4197            tokio::fs::create_dir(&update).await?;
4198            tokio::fs::create_dir(&dst).await?;
4199            let entry_path = update.join("node");
4200            let dst_path = dst.join("node");
4201            tokio::fs::write(&entry_path, "SELECTED-UPDATE-FILE").await?;
4202            let update_parent =
4203                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
4204            let dst_parent =
4205                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4206            let mut filter = FilterSettings::new();
4207            filter.add_exclude("node/")?;
4208            let mut settings = common_settings(false, false);
4209            settings.filter = Some(filter.clone());
4210            settings.copy_settings.filter = Some(filter);
4211            let admission =
4212                walk::ensure_entry_admission(PermitKind::OpenFile, EntryAdmission::RootOrDelegated)
4213                    .await;
4214            let selected = select_exact_update_only_for_dispatch(
4215                &update_parent,
4216                std::ffi::OsStr::new("node"),
4217                admission,
4218                std::path::Path::new("node"),
4219                settings.filter.as_ref(),
4220            )
4221            .await?;
4222            let UpdateOnlyDecision::Admitted(entry) = selected else {
4223                panic!("the forced-unknown file must pass the non-directory filter")
4224            };
4225            assert_eq!(entry.kind(), EntryKind::File);
4226
4227            tokio::fs::remove_file(&entry_path).await?;
4228            tokio::fs::create_dir(&entry_path).await?;
4229            tokio::fs::write(entry_path.join("replacement.txt"), "UNSELECTED").await?;
4230            let result = run_with_open_file_cleanup(
4231                &admission_limits,
4232                delegate_copy(
4233                    &PROGRESS,
4234                    &update_parent,
4235                    Some(&dst_parent),
4236                    std::ffi::OsStr::new("node"),
4237                    &entry_path,
4238                    &dst,
4239                    std::path::Path::new("node"),
4240                    copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4241                    &settings,
4242                    false,
4243                    entry,
4244                ),
4245            )
4246            .await?;
4247
4248            assert!(
4249                result.is_err(),
4250                "a selected file reopened as a directory must fail closed"
4251            );
4252            assert!(
4253                !dst_path.exists(),
4254                "a failed-closed type swap must not create a destination"
4255            );
4256            Ok(())
4257        }
4258
4259        /// A nested source rechecks the exact type after a `DT_UNKNOWN` filter probe.
4260        #[tokio::test]
4261        #[traced_test]
4262        async fn nested_source_unknown_file_swap_to_excluded_directory_is_rechecked()
4263        -> Result<(), anyhow::Error> {
4264            let test_path = testutils::create_temp_dir().await?;
4265            let src = test_path.join("src");
4266            let dst = test_path.join("dst");
4267            tokio::fs::create_dir(&src).await?;
4268            tokio::fs::create_dir(&dst).await?;
4269            let entry_path = src.join("node");
4270            tokio::fs::write(&entry_path, "SELECTED-FILE").await?;
4271            tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4272            let src_parent =
4273                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4274            let dst_parent =
4275                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4276            let mut filter = FilterSettings::new();
4277            filter.add_exclude("node/")?;
4278            let initially_is_dir = walk::filter_is_dir(
4279                Some(&filter),
4280                &src_parent,
4281                std::ffi::OsStr::new("node"),
4282                None,
4283                false,
4284            )
4285            .await?;
4286            assert!(!initially_is_dir);
4287            assert!(
4288                walk::should_skip_entry(&Some(filter.clone()), std::path::Path::new("node"), false)
4289                    .is_none()
4290            );
4291
4292            tokio::fs::remove_file(&entry_path).await?;
4293            tokio::fs::create_dir(&entry_path).await?;
4294            tokio::fs::write(entry_path.join("replacement.txt"), "UNSELECTED").await?;
4295            let mut settings = common_settings(false, false);
4296            settings.filter = Some(filter.clone());
4297            settings.copy_settings.filter = Some(filter);
4298            let delete_settings = copy::DeleteSettings {
4299                delete_excluded: true,
4300            };
4301            let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4302            let result = crate::task_scope::scope_tasks(link_internal(
4303                &PROGRESS,
4304                &src_parent,
4305                None,
4306                Some(&dst_parent),
4307                std::ffi::OsStr::new("node"),
4308                &src,
4309                &dst,
4310                None,
4311                std::path::Path::new("node"),
4312                UpdateRootRequirement::Optional,
4313                &settings,
4314                false,
4315                EntryAdmission::RootOrDelegated.into(),
4316                copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4317            ))
4318            .await?;
4319            let mut summary = Summary::default();
4320            LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4321                .fold(&mut summary, &mut outcomes);
4322            crate::delete::prune_and_fold(
4323                &PROGRESS,
4324                &dst_parent,
4325                std::path::Path::new(""),
4326                &outcomes.expect_ready(),
4327                settings.filter.as_ref(),
4328                false,
4329                None,
4330                &mut summary.copy_summary.rm_summary,
4331            )
4332            .await?;
4333
4334            assert!(
4335                !dst.join("node").exists(),
4336                "the exact filtered result did not remove the stale outer keep decision"
4337            );
4338            assert_eq!(summary.copy_summary.directories_skipped, 1);
4339            Ok(())
4340        }
4341
4342        /// A stale excluded-directory hint cannot suppress an included file when delete will consume
4343        /// the resulting keep-set.
4344        #[tokio::test]
4345        #[traced_test]
4346        async fn destructive_source_stale_directory_hint_rechecks_included_file()
4347        -> Result<(), anyhow::Error> {
4348            let test_path = testutils::create_temp_dir().await?;
4349            let src = test_path.join("src");
4350            let dst = test_path.join("dst");
4351            tokio::fs::create_dir(&src).await?;
4352            tokio::fs::create_dir(&dst).await?;
4353            tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
4354            tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4355            let src_dir =
4356                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4357            let dst_dir =
4358                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4359
4360            let mut filter = FilterSettings::new();
4361            filter.add_exclude("node/")?;
4362            let delete_settings = copy::DeleteSettings {
4363                delete_excluded: false,
4364            };
4365            let mut settings = common_settings(false, true);
4366            settings.filter = Some(filter.clone());
4367            settings.copy_settings.filter = Some(filter);
4368            settings.copy_settings.delete = Some(delete_settings.clone());
4369            let decision = select_source_for_dispatch(
4370                Some(EntryKind::Dir),
4371                std::path::Path::new("node"),
4372                &settings,
4373                false,
4374            );
4375
4376            let mut summary = Summary::default();
4377            let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4378            match decision {
4379                SourceEntryDecision::Filtered { kind, .. } => {
4380                    summary = summary + skipped_summary_for(kind);
4381                }
4382                SourceEntryDecision::Dispatch(admission) => {
4383                    let admission =
4384                        walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
4385                    let result = crate::task_scope::scope_tasks(link_internal(
4386                        &PROGRESS,
4387                        &src_dir,
4388                        None,
4389                        Some(&dst_dir),
4390                        std::ffi::OsStr::new("node"),
4391                        &src,
4392                        &dst,
4393                        None,
4394                        std::path::Path::new("node"),
4395                        UpdateRootRequirement::Optional,
4396                        &settings,
4397                        false,
4398                        admission.into(),
4399                        copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4400                    ))
4401                    .await?;
4402                    LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4403                        .fold(&mut summary, &mut outcomes);
4404                }
4405            }
4406            crate::delete::prune_and_fold(
4407                &PROGRESS,
4408                &dst_dir,
4409                std::path::Path::new(""),
4410                &outcomes.expect_ready(),
4411                settings.filter.as_ref(),
4412                false,
4413                None,
4414                &mut summary.copy_summary.rm_summary,
4415            )
4416            .await?;
4417
4418            assert_eq!(
4419                tokio::fs::read_to_string(dst.join("node")).await?,
4420                "CURRENT-SOURCE",
4421                "the exact included file must materialize and protect its destination name"
4422            );
4423            assert_eq!(summary.hard_links_created, 1);
4424            Ok(())
4425        }
4426
4427        /// Dry-run reporting must come from the exact type rather than a stale excluded-directory
4428        /// hint.
4429        #[tokio::test]
4430        #[traced_test]
4431        async fn dry_run_source_stale_directory_hint_reports_included_file()
4432        -> Result<(), anyhow::Error> {
4433            let test_path = testutils::create_temp_dir().await?;
4434            let src = test_path.join("src");
4435            let dst = test_path.join("dst");
4436            tokio::fs::create_dir(&src).await?;
4437            tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
4438            let src_dir =
4439                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4440
4441            let mut filter = FilterSettings::new();
4442            filter.add_exclude("node/")?;
4443            let mut settings = common_settings(false, false);
4444            settings.filter = Some(filter.clone());
4445            settings.copy_settings.filter = Some(filter);
4446            settings.dry_run = Some(crate::config::DryRunMode::Brief);
4447            let decision = select_source_for_dispatch(
4448                Some(EntryKind::Dir),
4449                std::path::Path::new("node"),
4450                &settings,
4451                false,
4452            );
4453
4454            let mut summary = Summary::default();
4455            let mut outcomes = LinkChildOutcomes::new(None);
4456            match decision {
4457                SourceEntryDecision::Filtered { kind, .. } => {
4458                    summary = summary + skipped_summary_for(kind);
4459                }
4460                SourceEntryDecision::Dispatch(admission) => {
4461                    let admission =
4462                        walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
4463                    let result = crate::task_scope::scope_tasks(link_internal(
4464                        &PROGRESS,
4465                        &src_dir,
4466                        None,
4467                        None,
4468                        std::ffi::OsStr::new("node"),
4469                        &src,
4470                        &dst,
4471                        None,
4472                        std::path::Path::new("node"),
4473                        UpdateRootRequirement::Optional,
4474                        &settings,
4475                        false,
4476                        admission.into(),
4477                        copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4478                    ))
4479                    .await?;
4480                    LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4481                        .fold(&mut summary, &mut outcomes);
4482                }
4483            }
4484
4485            assert_eq!(summary.hard_links_created, 1);
4486            assert_eq!(summary.copy_summary.directories_skipped, 0);
4487            assert!(!dst.join("node").exists());
4488            Ok(())
4489        }
4490
4491        /// A stale special-file hint cannot suppress a regular file that the exact worker would
4492        /// materialize.
4493        #[tokio::test]
4494        #[traced_test]
4495        async fn skip_specials_stale_special_hint_rechecks_regular_file()
4496        -> Result<(), anyhow::Error> {
4497            let test_path = testutils::create_temp_dir().await?;
4498            let src = test_path.join("src");
4499            let dst = test_path.join("dst");
4500            tokio::fs::create_dir(&src).await?;
4501            tokio::fs::create_dir(&dst).await?;
4502            tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
4503            tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4504            let src_dir =
4505                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4506            let dst_dir =
4507                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4508
4509            let delete_settings = copy::DeleteSettings {
4510                delete_excluded: false,
4511            };
4512            let mut settings = common_settings(false, true);
4513            settings.copy_settings.skip_specials = true;
4514            settings.copy_settings.delete = Some(delete_settings.clone());
4515            let decision = select_source_for_dispatch(
4516                Some(EntryKind::Special),
4517                std::path::Path::new("node"),
4518                &settings,
4519                false,
4520            );
4521
4522            let mut summary = Summary::default();
4523            let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4524            match decision {
4525                SourceEntryDecision::Filtered { kind, .. } => {
4526                    summary = summary + skipped_summary_for(kind);
4527                }
4528                SourceEntryDecision::Dispatch(admission) => {
4529                    let admission =
4530                        walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
4531                    let result = crate::task_scope::scope_tasks(link_internal(
4532                        &PROGRESS,
4533                        &src_dir,
4534                        None,
4535                        Some(&dst_dir),
4536                        std::ffi::OsStr::new("node"),
4537                        &src,
4538                        &dst,
4539                        None,
4540                        std::path::Path::new("node"),
4541                        UpdateRootRequirement::Optional,
4542                        &settings,
4543                        false,
4544                        admission.into(),
4545                        copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4546                    ))
4547                    .await?;
4548                    LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4549                        .fold(&mut summary, &mut outcomes);
4550                }
4551            }
4552            crate::delete::prune_and_fold(
4553                &PROGRESS,
4554                &dst_dir,
4555                std::path::Path::new(""),
4556                &outcomes.expect_ready(),
4557                None,
4558                false,
4559                None,
4560                &mut summary.copy_summary.rm_summary,
4561            )
4562            .await?;
4563
4564            assert_eq!(
4565                tokio::fs::read_to_string(dst.join("node")).await?,
4566                "CURRENT-SOURCE",
4567                "the exact regular file must replace stale destination content"
4568            );
4569            assert_eq!(summary.hard_links_created, 1);
4570            assert_eq!(summary.copy_summary.specials_skipped, 0);
4571            Ok(())
4572        }
4573
4574        /// An update-only stale excluded-directory hint must be classified exactly before a delete
4575        /// keep-set is finalized.
4576        #[tokio::test]
4577        #[traced_test]
4578        async fn destructive_update_stale_directory_hint_rechecks_included_file()
4579        -> Result<(), anyhow::Error> {
4580            let test_path = testutils::create_temp_dir().await?;
4581            let update = test_path.join("update");
4582            let dst = test_path.join("dst");
4583            tokio::fs::create_dir(&update).await?;
4584            tokio::fs::create_dir(&dst).await?;
4585            tokio::fs::write(update.join("node"), "CURRENT-UPDATE").await?;
4586            tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4587            let update_dir =
4588                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
4589            let dst_dir =
4590                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4591
4592            let mut filter = FilterSettings::new();
4593            filter.add_exclude("node/")?;
4594            let delete_settings = copy::DeleteSettings {
4595                delete_excluded: false,
4596            };
4597            let mut settings = common_settings(false, true);
4598            settings.filter = Some(filter.clone());
4599            settings.copy_settings.filter = Some(filter);
4600            settings.copy_settings.delete = Some(delete_settings.clone());
4601            let decision = select_exact_update_only_for_dispatch(
4602                &update_dir,
4603                std::ffi::OsStr::new("node"),
4604                EntryAdmission::HintedDirectory,
4605                std::path::Path::new("node"),
4606                settings.filter.as_ref(),
4607            )
4608            .await?;
4609
4610            let mut summary = Summary::default();
4611            let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4612            match decision {
4613                UpdateOnlyDecision::Skipped { kind, .. } => {
4614                    summary = summary + skipped_summary_for(kind);
4615                }
4616                UpdateOnlyDecision::Admitted(entry) => {
4617                    let result = delegate_copy(
4618                        &PROGRESS,
4619                        &update_dir,
4620                        Some(&dst_dir),
4621                        std::ffi::OsStr::new("node"),
4622                        &update.join("node"),
4623                        &dst,
4624                        std::path::Path::new("node"),
4625                        copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4626                        &settings,
4627                        false,
4628                        entry,
4629                    )
4630                    .await?;
4631                    LinkTaskResult::from_update(
4632                        std::ffi::OsString::from("node"),
4633                        LinkEntryResult::selected(result),
4634                    )
4635                    .fold(&mut summary, &mut outcomes);
4636                }
4637            }
4638            crate::delete::prune_and_fold(
4639                &PROGRESS,
4640                &dst_dir,
4641                std::path::Path::new(""),
4642                &outcomes.expect_ready(),
4643                settings.filter.as_ref(),
4644                false,
4645                None,
4646                &mut summary.copy_summary.rm_summary,
4647            )
4648            .await?;
4649
4650            assert_eq!(
4651                tokio::fs::read_to_string(dst.join("node")).await?,
4652                "CURRENT-UPDATE",
4653                "the exact included update file must materialize and protect its destination name"
4654            );
4655            assert_eq!(summary.copy_summary.files_copied, 1);
4656            Ok(())
4657        }
4658
4659        /// Update-only preview reporting must also reclassify a stale excluded-directory hint.
4660        #[tokio::test]
4661        #[traced_test]
4662        async fn dry_run_update_stale_directory_hint_reports_included_file()
4663        -> Result<(), anyhow::Error> {
4664            let test_path = testutils::create_temp_dir().await?;
4665            let update = test_path.join("update");
4666            let dst = test_path.join("dst");
4667            tokio::fs::create_dir(&update).await?;
4668            tokio::fs::write(update.join("node"), "CURRENT-UPDATE").await?;
4669            let update_dir =
4670                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
4671
4672            let mut filter = FilterSettings::new();
4673            filter.add_exclude("node/")?;
4674            let mut settings = common_settings(false, false);
4675            settings.filter = Some(filter.clone());
4676            settings.copy_settings.filter = Some(filter);
4677            settings.dry_run = Some(crate::config::DryRunMode::Brief);
4678            let decision = select_exact_update_only_for_dispatch(
4679                &update_dir,
4680                std::ffi::OsStr::new("node"),
4681                EntryAdmission::HintedDirectory,
4682                std::path::Path::new("node"),
4683                settings.filter.as_ref(),
4684            )
4685            .await?;
4686
4687            let mut summary = Summary::default();
4688            let mut outcomes = LinkChildOutcomes::new(None);
4689            match decision {
4690                UpdateOnlyDecision::Skipped { kind, .. } => {
4691                    summary = summary + skipped_summary_for(kind);
4692                }
4693                UpdateOnlyDecision::Admitted(entry) => {
4694                    let result = delegate_copy(
4695                        &PROGRESS,
4696                        &update_dir,
4697                        None,
4698                        std::ffi::OsStr::new("node"),
4699                        &update.join("node"),
4700                        &dst,
4701                        std::path::Path::new("node"),
4702                        copy::DeleteScanAnchor::new(&dst, std::path::Path::new("node")),
4703                        &settings,
4704                        false,
4705                        entry,
4706                    )
4707                    .await?;
4708                    LinkTaskResult::from_update(
4709                        std::ffi::OsString::from("node"),
4710                        LinkEntryResult::selected(result),
4711                    )
4712                    .fold(&mut summary, &mut outcomes);
4713                }
4714            }
4715
4716            assert_eq!(summary.copy_summary.files_copied, 1);
4717            assert_eq!(summary.copy_summary.directories_skipped, 0);
4718            assert!(!dst.join("node").exists());
4719            Ok(())
4720        }
4721
4722        /// A jointly excluded dual root skips before validating an unused destination.
4723        #[tokio::test]
4724        #[traced_test]
4725        async fn excluded_dual_root_skips_before_destination_validation()
4726        -> Result<(), anyhow::Error> {
4727            let test_path = testutils::create_temp_dir().await?;
4728            let src_parent = test_path.join("source");
4729            let update_parent = test_path.join("update");
4730            let src = src_parent.join("blocked");
4731            let update = update_parent.join("blocked");
4732            tokio::fs::create_dir(&src_parent).await?;
4733            tokio::fs::create_dir(&update_parent).await?;
4734            tokio::fs::write(&src, "SRC").await?;
4735            tokio::fs::write(&update, "UPDATE").await?;
4736            let mut filter = FilterSettings::new();
4737            filter.add_exclude("blocked").unwrap();
4738            let mut settings = common_settings(false, false);
4739            settings.filter = Some(filter);
4740            let summary = link(
4741                &PROGRESS,
4742                &test_path,
4743                &src,
4744                std::path::Path::new("/"),
4745                &Some(update),
4746                &settings,
4747                false,
4748            )
4749            .await?;
4750            assert_eq!(summary.copy_summary.files_skipped, 1);
4751            Ok(())
4752        }
4753
4754        /// An excluded source-only root under an execute-only parent must retain the default
4755        /// path's metadata-only filter exit instead of requiring a readable parent directory.
4756        #[tokio::test]
4757        async fn excluded_source_only_root_skips_under_execute_only_parent()
4758        -> Result<(), anyhow::Error> {
4759            let test_path = testutils::create_temp_dir().await?;
4760            let parent = test_path.join("parent");
4761            let src = parent.join("src");
4762            let dst = test_path.join("dst");
4763            tokio::fs::create_dir_all(&src).await?;
4764            tokio::fs::write(src.join("leaf"), b"leaf").await?;
4765            let mut filter = FilterSettings::new();
4766            filter.add_exclude("src")?;
4767            let mut settings = common_settings(false, false);
4768            settings.filter = Some(filter.clone());
4769            settings.copy_settings.filter = Some(filter);
4770            tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o111)).await?;
4771            let result = link(&PROGRESS, &test_path, &src, &dst, &None, &settings, false).await;
4772            tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755)).await?;
4773            let summary = result?;
4774            assert_eq!(summary.copy_summary.directories_skipped, 1);
4775            assert!(!dst.exists());
4776            Ok(())
4777        }
4778
4779        /// Test that filters apply to root directories with simple exclude patterns.
4780        #[tokio::test]
4781        #[traced_test]
4782        async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
4783            let test_path = testutils::create_temp_dir().await?;
4784            // create a directory that should be excluded
4785            tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
4786            tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
4787            // create filter that excludes *_dir/ directories
4788            let mut filter = FilterSettings::new();
4789            filter.add_exclude("*_dir/").unwrap();
4790            let result = link(
4791                &PROGRESS,
4792                &test_path,
4793                &test_path.join("excluded_dir"),
4794                &test_path.join("dst"),
4795                &None,
4796                &Settings {
4797                    copy_settings: CopySettings {
4798                        reflink: Default::default(),
4799                        local_copy_handoff: Default::default(),
4800                        dereference: false,
4801                        fail_early: false,
4802                        overwrite: false,
4803                        overwrite_compare: Default::default(),
4804                        overwrite_filter: None,
4805                        ignore_existing: false,
4806                        chunk_size: 0,
4807                        skip_specials: false,
4808                        remote_copy_buffer_size: 0,
4809                        filter: None,
4810                        dry_run: None,
4811                        delete: None,
4812                    },
4813                    update_compare: Default::default(),
4814                    update_exclusive: false,
4815                    filter: Some(filter),
4816                    dry_run: None,
4817                    preserve: preserve::preserve_all(),
4818                },
4819                false,
4820            )
4821            .await?;
4822            // directory should NOT be linked because it matches exclude pattern
4823            assert_eq!(
4824                result.copy_summary.directories_created, 0,
4825                "root directory matching exclude should not be created"
4826            );
4827            assert!(
4828                !test_path.join("dst").exists(),
4829                "excluded root directory should not exist at destination"
4830            );
4831            Ok(())
4832        }
4833        /// Test that filters apply to root symlinks with simple exclude patterns.
4834        #[tokio::test]
4835        #[traced_test]
4836        async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
4837            let test_path = testutils::create_temp_dir().await?;
4838            // create a target file and a symlink to it
4839            tokio::fs::write(test_path.join("target.txt"), "content").await?;
4840            tokio::fs::symlink(
4841                test_path.join("target.txt"),
4842                test_path.join("excluded_link"),
4843            )
4844            .await?;
4845            // create filter that excludes *_link
4846            let mut filter = FilterSettings::new();
4847            filter.add_exclude("*_link").unwrap();
4848            let result = link(
4849                &PROGRESS,
4850                &test_path,
4851                &test_path.join("excluded_link"),
4852                &test_path.join("dst"),
4853                &None,
4854                &Settings {
4855                    copy_settings: CopySettings {
4856                        reflink: Default::default(),
4857                        local_copy_handoff: Default::default(),
4858                        dereference: false,
4859                        fail_early: false,
4860                        overwrite: false,
4861                        overwrite_compare: Default::default(),
4862                        overwrite_filter: None,
4863                        ignore_existing: false,
4864                        chunk_size: 0,
4865                        skip_specials: false,
4866                        remote_copy_buffer_size: 0,
4867                        filter: None,
4868                        dry_run: None,
4869                        delete: None,
4870                    },
4871                    update_compare: Default::default(),
4872                    update_exclusive: false,
4873                    filter: Some(filter),
4874                    dry_run: None,
4875                    preserve: preserve::preserve_all(),
4876                },
4877                false,
4878            )
4879            .await?;
4880            // symlink should NOT be copied because it matches exclude pattern
4881            assert_eq!(
4882                result.copy_summary.symlinks_created, 0,
4883                "root symlink matching exclude should not be created"
4884            );
4885            assert!(
4886                !test_path.join("dst").exists(),
4887                "excluded root symlink should not exist at destination"
4888            );
4889            Ok(())
4890        }
4891        /// Test combined include and exclude patterns (exclude takes precedence).
4892        #[tokio::test]
4893        #[traced_test]
4894        async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
4895            let tmp_dir = testutils::setup_test_dir().await?;
4896            let test_path = tmp_dir.as_path();
4897            // test structure from setup_test_dir:
4898            // foo/
4899            //   0.txt
4900            //   bar/ (1.txt, 2.txt, 3.txt)
4901            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
4902            // include all .txt files in bar/, but exclude 2.txt specifically
4903            let mut filter = FilterSettings::new();
4904            filter.add_include("bar/*.txt").unwrap();
4905            filter.add_exclude("bar/2.txt").unwrap();
4906            let summary = link(
4907                &PROGRESS,
4908                test_path,
4909                &test_path.join("foo"),
4910                &test_path.join("dst"),
4911                &None,
4912                &Settings {
4913                    copy_settings: CopySettings {
4914                        reflink: Default::default(),
4915                        local_copy_handoff: Default::default(),
4916                        dereference: false,
4917                        fail_early: false,
4918                        overwrite: false,
4919                        overwrite_compare: Default::default(),
4920                        overwrite_filter: None,
4921                        ignore_existing: false,
4922                        chunk_size: 0,
4923                        skip_specials: false,
4924                        remote_copy_buffer_size: 0,
4925                        filter: None,
4926                        dry_run: None,
4927                        delete: None,
4928                    },
4929                    update_compare: Default::default(),
4930                    update_exclusive: false,
4931                    filter: Some(filter),
4932                    dry_run: None,
4933                    preserve: preserve::preserve_all(),
4934                },
4935                false,
4936            )
4937            .await?;
4938            // should link: bar/1.txt, bar/3.txt = 2 hard links
4939            // should skip: bar/2.txt (excluded by pattern), 0.txt (excluded by default - no match) = 2 files
4940            assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
4941            assert_eq!(
4942                summary.copy_summary.files_skipped, 2,
4943                "should skip 2 files (bar/2.txt excluded, 0.txt no match)"
4944            );
4945            // verify
4946            assert!(
4947                test_path.join("dst/bar/1.txt").exists(),
4948                "bar/1.txt should be linked"
4949            );
4950            assert!(
4951                !test_path.join("dst/bar/2.txt").exists(),
4952                "bar/2.txt should be excluded"
4953            );
4954            assert!(
4955                test_path.join("dst/bar/3.txt").exists(),
4956                "bar/3.txt should be linked"
4957            );
4958            Ok(())
4959        }
4960        /// Test that skipped counts accurately reflect what was filtered.
4961        #[tokio::test]
4962        #[traced_test]
4963        async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
4964            let tmp_dir = testutils::setup_test_dir().await?;
4965            let test_path = tmp_dir.as_path();
4966            // test structure from setup_test_dir:
4967            // foo/
4968            //   0.txt
4969            //   bar/ (1.txt, 2.txt, 3.txt)
4970            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
4971            // exclude bar/ directory entirely
4972            let mut filter = FilterSettings::new();
4973            filter.add_exclude("bar/").unwrap();
4974            let summary = link(
4975                &PROGRESS,
4976                test_path,
4977                &test_path.join("foo"),
4978                &test_path.join("dst"),
4979                &None,
4980                &Settings {
4981                    copy_settings: CopySettings {
4982                        reflink: Default::default(),
4983                        local_copy_handoff: Default::default(),
4984                        dereference: false,
4985                        fail_early: false,
4986                        overwrite: false,
4987                        overwrite_compare: Default::default(),
4988                        overwrite_filter: None,
4989                        ignore_existing: false,
4990                        chunk_size: 0,
4991                        skip_specials: false,
4992                        remote_copy_buffer_size: 0,
4993                        filter: None,
4994                        dry_run: None,
4995                        delete: None,
4996                    },
4997                    update_compare: Default::default(),
4998                    update_exclusive: false,
4999                    filter: Some(filter),
5000                    dry_run: None,
5001                    preserve: preserve::preserve_all(),
5002                },
5003                false,
5004            )
5005            .await?;
5006            // linked: 0.txt (1 hard link), baz/4.txt (1 hard link)
5007            // symlinks copied: 5.txt, 6.txt
5008            // skipped: bar directory (1 dir)
5009            assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
5010            assert_eq!(
5011                summary.copy_summary.symlinks_created, 2,
5012                "should copy 2 symlinks"
5013            );
5014            assert_eq!(
5015                summary.copy_summary.directories_skipped, 1,
5016                "should skip 1 directory (bar)"
5017            );
5018            // bar should not exist in dst
5019            assert!(
5020                !test_path.join("dst/bar").exists(),
5021                "bar directory should not be linked"
5022            );
5023            Ok(())
5024        }
5025        /// Test that empty directories are not created when they were only traversed to look
5026        /// for matches (regression test for bug where --include='foo' would create empty dir baz).
5027        #[tokio::test]
5028        #[traced_test]
5029        async fn test_empty_dir_not_created_when_only_traversed() -> Result<(), anyhow::Error> {
5030            let test_path = testutils::create_temp_dir().await?;
5031            // create structure:
5032            // src/
5033            //   foo (file)
5034            //   bar (file)
5035            //   baz/ (empty directory)
5036            let src_path = test_path.join("src");
5037            tokio::fs::create_dir(&src_path).await?;
5038            tokio::fs::write(src_path.join("foo"), "content").await?;
5039            tokio::fs::write(src_path.join("bar"), "content").await?;
5040            tokio::fs::create_dir(src_path.join("baz")).await?;
5041            // include only 'foo' file
5042            let mut filter = FilterSettings::new();
5043            filter.add_include("foo").unwrap();
5044            let summary = link(
5045                &PROGRESS,
5046                &test_path,
5047                &src_path,
5048                &test_path.join("dst"),
5049                &None,
5050                &Settings {
5051                    copy_settings: copy::Settings {
5052                        reflink: Default::default(),
5053                        local_copy_handoff: Default::default(),
5054                        dereference: false,
5055                        fail_early: false,
5056                        overwrite: false,
5057                        overwrite_compare: Default::default(),
5058                        overwrite_filter: None,
5059                        ignore_existing: false,
5060                        chunk_size: 0,
5061                        skip_specials: false,
5062                        remote_copy_buffer_size: 0,
5063                        filter: None,
5064                        dry_run: None,
5065                        delete: None,
5066                    },
5067                    update_compare: Default::default(),
5068                    update_exclusive: false,
5069                    filter: Some(filter),
5070                    dry_run: None,
5071                    preserve: preserve::preserve_all(),
5072                },
5073                false,
5074            )
5075            .await?;
5076            // only 'foo' should be linked
5077            assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5078            assert_eq!(
5079                summary.copy_summary.directories_created, 1,
5080                "should create only root directory (not empty 'baz')"
5081            );
5082            // verify foo was linked
5083            assert!(
5084                test_path.join("dst").join("foo").exists(),
5085                "foo should be linked"
5086            );
5087            // verify bar was not linked (not matching include pattern)
5088            assert!(
5089                !test_path.join("dst").join("bar").exists(),
5090                "bar should not be linked"
5091            );
5092            // verify empty baz directory was NOT created
5093            assert!(
5094                !test_path.join("dst").join("baz").exists(),
5095                "empty baz directory should NOT be created"
5096            );
5097            Ok(())
5098        }
5099        /// Test that directories with only non-matching content are not created at destination.
5100        /// This is different from empty directories - the source dir has content but none matches.
5101        #[tokio::test]
5102        #[traced_test]
5103        async fn test_dir_with_nonmatching_content_not_created() -> Result<(), anyhow::Error> {
5104            let test_path = testutils::create_temp_dir().await?;
5105            // create structure:
5106            // src/
5107            //   foo (file)
5108            //   baz/
5109            //     qux (file - doesn't match 'foo')
5110            //     quux (file - doesn't match 'foo')
5111            let src_path = test_path.join("src");
5112            tokio::fs::create_dir(&src_path).await?;
5113            tokio::fs::write(src_path.join("foo"), "content").await?;
5114            tokio::fs::create_dir(src_path.join("baz")).await?;
5115            tokio::fs::write(src_path.join("baz").join("qux"), "content").await?;
5116            tokio::fs::write(src_path.join("baz").join("quux"), "content").await?;
5117            // include only 'foo' file
5118            let mut filter = FilterSettings::new();
5119            filter.add_include("foo").unwrap();
5120            let summary = link(
5121                &PROGRESS,
5122                &test_path,
5123                &src_path,
5124                &test_path.join("dst"),
5125                &None,
5126                &Settings {
5127                    copy_settings: copy::Settings {
5128                        reflink: Default::default(),
5129                        local_copy_handoff: Default::default(),
5130                        dereference: false,
5131                        fail_early: false,
5132                        overwrite: false,
5133                        overwrite_compare: Default::default(),
5134                        overwrite_filter: None,
5135                        ignore_existing: false,
5136                        chunk_size: 0,
5137                        skip_specials: false,
5138                        remote_copy_buffer_size: 0,
5139                        filter: None,
5140                        dry_run: None,
5141                        delete: None,
5142                    },
5143                    update_compare: Default::default(),
5144                    update_exclusive: false,
5145                    filter: Some(filter),
5146                    dry_run: None,
5147                    preserve: preserve::preserve_all(),
5148                },
5149                false,
5150            )
5151            .await?;
5152            // only 'foo' should be linked
5153            assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5154            assert_eq!(
5155                summary.copy_summary.files_skipped, 2,
5156                "should skip 2 files (qux and quux)"
5157            );
5158            assert_eq!(
5159                summary.copy_summary.directories_created, 1,
5160                "should create only root directory (not 'baz' with non-matching content)"
5161            );
5162            // verify foo was linked
5163            assert!(
5164                test_path.join("dst").join("foo").exists(),
5165                "foo should be linked"
5166            );
5167            // verify baz directory was NOT created (even though source baz has content)
5168            assert!(
5169                !test_path.join("dst").join("baz").exists(),
5170                "baz directory should NOT be created (no matching content inside)"
5171            );
5172            Ok(())
5173        }
5174        /// Test that empty directories are not reported as created in dry-run mode
5175        /// when they were only traversed.
5176        #[tokio::test]
5177        #[traced_test]
5178        async fn test_dry_run_empty_dir_not_reported_as_created() -> Result<(), anyhow::Error> {
5179            let test_path = testutils::create_temp_dir().await?;
5180            // create structure:
5181            // src/
5182            //   foo (file)
5183            //   bar (file)
5184            //   baz/ (empty directory)
5185            let src_path = test_path.join("src");
5186            tokio::fs::create_dir(&src_path).await?;
5187            tokio::fs::write(src_path.join("foo"), "content").await?;
5188            tokio::fs::write(src_path.join("bar"), "content").await?;
5189            tokio::fs::create_dir(src_path.join("baz")).await?;
5190            // include only 'foo' file
5191            let mut filter = FilterSettings::new();
5192            filter.add_include("foo").unwrap();
5193            let summary = link(
5194                &PROGRESS,
5195                &test_path,
5196                &src_path,
5197                &test_path.join("dst"),
5198                &None,
5199                &Settings {
5200                    copy_settings: copy::Settings {
5201                        reflink: Default::default(),
5202                        local_copy_handoff: Default::default(),
5203                        dereference: false,
5204                        fail_early: false,
5205                        overwrite: false,
5206                        overwrite_compare: Default::default(),
5207                        overwrite_filter: None,
5208                        ignore_existing: false,
5209                        chunk_size: 0,
5210                        skip_specials: false,
5211                        remote_copy_buffer_size: 0,
5212                        filter: None,
5213                        dry_run: None,
5214                        delete: None,
5215                    },
5216                    update_compare: Default::default(),
5217                    update_exclusive: false,
5218                    filter: Some(filter),
5219                    dry_run: Some(crate::config::DryRunMode::Explain),
5220                    preserve: preserve::preserve_all(),
5221                },
5222                false,
5223            )
5224            .await?;
5225            // only 'foo' should be reported as would-be-linked
5226            assert_eq!(
5227                summary.hard_links_created, 1,
5228                "should report only 'foo' would be linked"
5229            );
5230            assert_eq!(
5231                summary.copy_summary.directories_created, 1,
5232                "should report only root directory would be created (not empty 'baz')"
5233            );
5234            // verify nothing was actually created (dry-run mode)
5235            assert!(
5236                !test_path.join("dst").exists(),
5237                "dst should not exist in dry-run"
5238            );
5239            Ok(())
5240        }
5241        /// Test that existing directories are NOT removed when using --overwrite,
5242        /// even if nothing is linked into them due to filters.
5243        #[tokio::test]
5244        #[traced_test]
5245        async fn test_existing_dir_not_removed_with_overwrite() -> Result<(), anyhow::Error> {
5246            let test_path = testutils::create_temp_dir().await?;
5247            // create source structure:
5248            // src/
5249            //   foo (file)
5250            //   bar (file)
5251            //   baz/ (empty directory)
5252            let src_path = test_path.join("src");
5253            tokio::fs::create_dir(&src_path).await?;
5254            tokio::fs::write(src_path.join("foo"), "content").await?;
5255            tokio::fs::write(src_path.join("bar"), "content").await?;
5256            tokio::fs::create_dir(src_path.join("baz")).await?;
5257            // create destination with baz directory already existing
5258            let dst_path = test_path.join("dst");
5259            tokio::fs::create_dir(&dst_path).await?;
5260            tokio::fs::create_dir(dst_path.join("baz")).await?;
5261            // add a marker file inside dst/baz to verify we don't touch it
5262            tokio::fs::write(dst_path.join("baz").join("marker.txt"), "existing").await?;
5263            // include only 'foo' file - baz should not match
5264            let mut filter = FilterSettings::new();
5265            filter.add_include("foo").unwrap();
5266            let summary = link(
5267                &PROGRESS,
5268                &test_path,
5269                &src_path,
5270                &dst_path,
5271                &None,
5272                &Settings {
5273                    copy_settings: copy::Settings {
5274                        reflink: Default::default(),
5275                        local_copy_handoff: Default::default(),
5276                        dereference: false,
5277                        fail_early: false,
5278                        overwrite: true, // enable overwrite mode
5279                        overwrite_compare: Default::default(),
5280                        overwrite_filter: None,
5281                        ignore_existing: false,
5282                        chunk_size: 0,
5283                        skip_specials: false,
5284                        remote_copy_buffer_size: 0,
5285                        filter: None,
5286                        dry_run: None,
5287                        delete: None,
5288                    },
5289                    update_compare: Default::default(),
5290                    update_exclusive: false,
5291                    filter: Some(filter),
5292                    dry_run: None,
5293                    preserve: preserve::preserve_all(),
5294                },
5295                false,
5296            )
5297            .await?;
5298            // foo should be linked
5299            assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5300            // dst and baz should be unchanged (both already existed)
5301            assert_eq!(
5302                summary.copy_summary.directories_unchanged, 2,
5303                "root dst and baz directories should be unchanged"
5304            );
5305            assert_eq!(
5306                summary.copy_summary.directories_created, 0,
5307                "should not create any directories"
5308            );
5309            // verify foo was linked
5310            assert!(dst_path.join("foo").exists(), "foo should be linked");
5311            // verify bar was NOT linked
5312            assert!(!dst_path.join("bar").exists(), "bar should not be linked");
5313            // verify existing baz directory still exists with its content
5314            assert!(
5315                dst_path.join("baz").exists(),
5316                "existing baz directory should still exist"
5317            );
5318            assert!(
5319                dst_path.join("baz").join("marker.txt").exists(),
5320                "existing content in baz should still exist"
5321            );
5322            Ok(())
5323        }
5324
5325        async fn delegated_empty_directory_case(
5326            dry_run: bool,
5327            directly_included: bool,
5328        ) -> anyhow::Result<()> {
5329            for relative in ["docs", "a/docs"] {
5330                let test_path = testutils::create_temp_dir().await?;
5331                let src = test_path.join("src");
5332                let update = test_path.join("update");
5333                let dst = test_path.join("dst");
5334                tokio::fs::create_dir_all(src.join("a")).await?;
5335                tokio::fs::create_dir_all(update.join(relative)).await?;
5336                tokio::fs::write(update.join(relative).join("readme.md"), "FILTERED").await?;
5337                let mut filter = FilterSettings::new();
5338                filter.add_include("*.rs")?;
5339                if directly_included {
5340                    filter.add_include(&format!("/{relative}"))?;
5341                }
5342                let mut settings = common_settings(false, false);
5343                settings.filter = Some(filter.clone());
5344                settings.copy_settings.filter = Some(filter);
5345                settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
5346                settings.copy_settings.dry_run = settings.dry_run;
5347                let summary = link(
5348                    &PROGRESS,
5349                    &test_path,
5350                    &src,
5351                    &dst,
5352                    &Some(update.clone()),
5353                    &settings,
5354                    false,
5355                )
5356                .await?;
5357                let expected_dirs = if directly_included {
5358                    1 + std::path::Path::new(relative).components().count()
5359                } else {
5360                    1
5361                };
5362                assert_eq!(summary.copy_summary.directories_created, expected_dirs);
5363                assert_eq!(summary.copy_summary.files_copied, 0);
5364                assert_eq!(summary.copy_summary.files_skipped, 1);
5365                assert_eq!(summary.hard_links_created, 0);
5366                assert_eq!(dst.exists(), !dry_run, "the true root must be retained");
5367                assert_eq!(dst.join(relative).exists(), !dry_run && directly_included);
5368                assert!(!dst.join(relative).join("readme.md").exists());
5369                if !directly_included {
5370                    assert!(
5371                        !dst.join("a").exists(),
5372                        "empty ancestors must also be removed"
5373                    );
5374                }
5375                // the same filtered directory passed as the user's copy operand IS a true root
5376                let copy_dst = test_path.join("copy-root");
5377                let summary = copy::copy(
5378                    &PROGRESS,
5379                    &update.join(relative),
5380                    &copy_dst,
5381                    &settings.copy_settings,
5382                    &settings.preserve,
5383                    false,
5384                )
5385                .await?;
5386                assert_eq!(summary.directories_created, 1);
5387                assert_eq!(copy_dst.exists(), !dry_run);
5388            }
5389            Ok(())
5390        }
5391
5392        #[tokio::test]
5393        async fn delegated_traversal_only_directories_are_removed() -> anyhow::Result<()> {
5394            delegated_empty_directory_case(false, false).await
5395        }
5396
5397        #[tokio::test]
5398        async fn delegated_traversal_only_directories_are_not_counted_in_dry_run()
5399        -> anyhow::Result<()> {
5400            delegated_empty_directory_case(true, false).await
5401        }
5402
5403        #[tokio::test]
5404        async fn delegated_directly_included_empty_directories_are_kept() -> anyhow::Result<()> {
5405            delegated_empty_directory_case(false, true).await?;
5406            delegated_empty_directory_case(true, true).await
5407        }
5408
5409        #[tokio::test]
5410        async fn delegated_reused_traversal_only_directory_is_kept() -> anyhow::Result<()> {
5411            let test_path = testutils::create_temp_dir().await?;
5412            let src = test_path.join("src");
5413            let update = test_path.join("update");
5414            let dst = test_path.join("dst");
5415            tokio::fs::create_dir(&src).await?;
5416            tokio::fs::create_dir_all(update.join("docs")).await?;
5417            tokio::fs::create_dir_all(dst.join("docs")).await?;
5418            tokio::fs::write(update.join("docs/readme.md"), "FILTERED").await?;
5419            tokio::fs::write(dst.join("docs/sentinel"), "KEEP").await?;
5420            let mut filter = FilterSettings::new();
5421            filter.add_include("*.rs")?;
5422            let mut settings = common_settings(false, true);
5423            settings.copy_settings.filter = Some(filter.clone());
5424            settings.filter = Some(filter);
5425            let summary = link(
5426                &PROGRESS,
5427                &test_path,
5428                &src,
5429                &dst,
5430                &Some(update),
5431                &settings,
5432                false,
5433            )
5434            .await?;
5435            assert_eq!(summary.copy_summary.directories_created, 0);
5436            assert_eq!(summary.copy_summary.directories_unchanged, 2);
5437            assert_eq!(tokio::fs::read(dst.join("docs/sentinel")).await?, b"KEEP");
5438            assert!(!dst.join("docs/readme.md").exists());
5439            Ok(())
5440        }
5441
5442        #[tokio::test]
5443        async fn delegated_empty_directory_cleanup_preserves_child_errors() -> anyhow::Result<()> {
5444            for dry_run in [false, true] {
5445                let test_path = testutils::create_temp_dir().await?;
5446                let src = test_path.join("src");
5447                let update = test_path.join("update");
5448                let dst = test_path.join("dst");
5449                tokio::fs::create_dir(&src).await?;
5450                tokio::fs::create_dir_all(update.join("docs")).await?;
5451                let _socket = std::os::unix::net::UnixListener::bind(update.join("docs/bad.rs"))?;
5452                let mut filter = FilterSettings::new();
5453                filter.add_include("*.rs")?;
5454                let mut settings = common_settings(false, false);
5455                settings.copy_settings.filter = Some(filter.clone());
5456                settings.filter = Some(filter);
5457                settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
5458                settings.copy_settings.dry_run = settings.dry_run;
5459                let error = link(
5460                    &PROGRESS,
5461                    &test_path,
5462                    &src,
5463                    &dst,
5464                    &Some(update),
5465                    &settings,
5466                    false,
5467                )
5468                .await
5469                .expect_err("empty-directory cleanup must preserve a failed child");
5470                assert!(format!("{:#}", error.source).contains("unsupported src file type"));
5471                assert_eq!(error.summary.copy_summary.directories_created, 1);
5472                assert_eq!(error.summary.copy_summary.files_copied, 0);
5473                assert!(!dst.join("docs").exists());
5474                assert_eq!(dst.exists(), !dry_run);
5475            }
5476            Ok(())
5477        }
5478
5479        /// Regression: an update-only entry matching an `--exclude` pattern must NOT be copied to
5480        /// the destination when `--delete` is OFF. The fd-based link delegates update-only entries
5481        /// to `copy::copy_child` with an already-filtered admission, so the update loop must evaluate
5482        /// the filter itself — independently of `--delete` — and skip excluded entries before
5483        /// delegation
5484        #[tokio::test]
5485        #[traced_test]
5486        async fn update_only_excluded_entry_not_copied_without_delete() -> Result<(), anyhow::Error>
5487        {
5488            let test_path = testutils::create_temp_dir().await?;
5489            // src has `keep.txt`; update has `keep.txt` (also in src) plus update-only `extra.txt`
5490            // and `wanted.txt`. With `--exclude extra.txt` and NO `--delete`, `extra.txt` must be
5491            // skipped while `wanted.txt` is copied.
5492            let src = test_path.join("src");
5493            let update = test_path.join("update");
5494            let dst = test_path.join("dst");
5495            tokio::fs::create_dir(&src).await?;
5496            tokio::fs::create_dir(&update).await?;
5497            tokio::fs::write(src.join("keep.txt"), "keep").await?;
5498            tokio::fs::write(update.join("keep.txt"), "keep").await?;
5499            tokio::fs::write(update.join("extra.txt"), "EXCLUDED").await?;
5500            tokio::fs::write(update.join("wanted.txt"), "wanted").await?;
5501
5502            let mut filter = FilterSettings::new();
5503            filter.add_exclude("extra.txt").unwrap();
5504            let mut settings = common_settings(false, false);
5505            settings.filter = Some(filter);
5506            // --delete is OFF (the bug only manifests with delete off).
5507            assert!(settings.copy_settings.delete.is_none());
5508
5509            let summary = link(
5510                &PROGRESS,
5511                &test_path,
5512                &src,
5513                &dst,
5514                &Some(update.clone()),
5515                &settings,
5516                false,
5517            )
5518            .await?;
5519
5520            assert!(
5521                !dst.join("extra.txt").exists(),
5522                "update-only entry matching --exclude must NOT be copied when --delete is off"
5523            );
5524            assert!(
5525                dst.join("wanted.txt").exists(),
5526                "non-excluded update-only entry should be copied"
5527            );
5528            assert!(dst.join("keep.txt").exists(), "shared entry should exist");
5529            assert_eq!(
5530                summary.copy_summary.files_skipped, 1,
5531                "the excluded update-only file should be counted skipped"
5532            );
5533            Ok(())
5534        }
5535
5536        /// Verify a hard-link relationship between two paths by inode + device identity.
5537        fn are_hardlinked(a: &std::path::Path, b: &std::path::Path) -> bool {
5538            use std::os::unix::fs::MetadataExt;
5539            match (std::fs::symlink_metadata(a), std::fs::symlink_metadata(b)) {
5540                (Ok(ma), Ok(mb)) => ma.ino() == mb.ino() && ma.dev() == mb.dev(),
5541                _ => false,
5542            }
5543        }
5544
5545        /// The chatgpt-codex re-review scenario (PR #247): in rlink's dual-tree walk the source
5546        /// loop evaluates the filter against the SOURCE entry's type. When `src/cache` is a FILE
5547        /// and `update/cache` is a DIRECTORY, a dir-only exclude `cache/` passes the src file (a
5548        /// dir-only pattern doesn't match a file), so `link_internal` runs and hits its
5549        /// type-mismatch branch. Before the fix that branch unconditionally delegated a copy of the
5550        /// UPDATE entry — and `copy_child` does not re-apply the top-level filter to the delegated
5551        /// root — so the excluded `cache/` directory was copied. The fix re-checks the filter using
5552        /// the UPDATE entry's type; the excluded update is dropped and, under union (`--update`)
5553        /// semantics, the src `cache` FILE is materialized instead.
5554        ///
5555        /// This test FAILS without the fix: `dst/cache` is created as the excluded update directory
5556        /// (and the src file is not materialized).
5557        #[tokio::test]
5558        #[traced_test]
5559        async fn type_mismatch_excluded_update_dir_not_copied_src_file_kept()
5560        -> Result<(), anyhow::Error> {
5561            let test_path = testutils::create_temp_dir().await?;
5562            let src = test_path.join("src");
5563            let update = test_path.join("update");
5564            let dst = test_path.join("dst");
5565            tokio::fs::create_dir(&src).await?;
5566            tokio::fs::create_dir(&update).await?;
5567            // src `cache` is a FILE; update `cache` is a DIRECTORY (the type mismatch).
5568            tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
5569            tokio::fs::create_dir(update.join("cache")).await?;
5570            tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
5571            // a non-conflicting shared file to confirm normal linking still happens.
5572            tokio::fs::write(src.join("keep.txt"), "keep").await?;
5573            tokio::fs::write(update.join("keep.txt"), "keep").await?;
5574            // pin an identical mtime (incl. nsec) on both `keep.txt` copies so the
5575            // size+mtime `update_compare` deterministically treats them as unchanged and
5576            // hard-links from src. Two separate writes can otherwise land on different
5577            // nanoseconds, flakily comparing as changed and copying instead (the bytes are
5578            // identical either way) — see PR #247 CI flake on test-musl-debug.
5579            let keep_mtime = filetime::FileTime::from_unix_time(1_700_000_000, 0);
5580            filetime::set_file_mtime(src.join("keep.txt"), keep_mtime)?;
5581            filetime::set_file_mtime(update.join("keep.txt"), keep_mtime)?;
5582
5583            let mut filter = FilterSettings::new();
5584            filter.add_exclude("cache/").unwrap(); // dir-only: matches a dir `cache`, not a file
5585            let mut settings = common_settings(false, false);
5586            settings.filter = Some(filter);
5587            assert!(settings.copy_settings.delete.is_none());
5588
5589            let summary = link(
5590                &PROGRESS,
5591                &test_path,
5592                &src,
5593                &dst,
5594                &Some(update.clone()),
5595                &settings,
5596                false,
5597            )
5598            .await?;
5599
5600            // the excluded update directory must NOT be copied.
5601            assert!(
5602                !dst.join("cache").join("inner.dat").exists(),
5603                "excluded update directory `cache/` must not be copied"
5604            );
5605            assert!(
5606                !dst.join("cache").is_dir(),
5607                "dst/cache must not be the excluded update directory"
5608            );
5609            // the src `cache` FILE stands (union semantics) and is hard-linked from src.
5610            assert!(
5611                dst.join("cache").is_file(),
5612                "src `cache` file must be materialized when the update dir is excluded"
5613            );
5614            assert_eq!(
5615                tokio::fs::read_to_string(dst.join("cache")).await?,
5616                "SRC-FILE"
5617            );
5618            assert!(
5619                are_hardlinked(&src.join("cache"), &dst.join("cache")),
5620                "the src `cache` file must be hard-linked into the destination"
5621            );
5622            assert!(
5623                dst.join("keep.txt").exists(),
5624                "shared entry should still link"
5625            );
5626            // `cache` (src file, union) and `keep.txt` (unchanged) are both hard-linked from src;
5627            // nothing is copied. Exactly one directory is created — the `dst` root — proving the
5628            // excluded `cache/` subtree added no directory.
5629            assert_eq!(summary.hard_links_created, 2);
5630            assert_eq!(summary.copy_summary.files_copied, 0);
5631            assert_eq!(
5632                summary.copy_summary.directories_created, 1,
5633                "only the dst root is created; the excluded `cache/` dir must not be"
5634            );
5635            Ok(())
5636        }
5637
5638        /// The REVERSE type mismatch (the symmetric code path): `src/data` is a DIRECTORY and
5639        /// `update/data` is a FILE. The dir-only include `data/` matches the directory form of the
5640        /// name but not the file form, and `data/**` includes the directory's contents. So the src
5641        /// `data` directory (and its `inner.txt`) passes the filter and the src loop spawns the
5642        /// worker, while the update `data` FILE is `ExcludedByDefault` (no include matches a file
5643        /// named `data`). The type-mismatch branch re-checks the filter using the update FILE's
5644        /// type, finds it excluded, and (union semantics) materializes the src DIRECTORY instead of
5645        /// copying the excluded update file. Without the fix the excluded update file would replace
5646        /// the src directory at the destination.
5647        #[tokio::test]
5648        #[traced_test]
5649        async fn reverse_type_mismatch_excluded_update_file_not_copied_src_dir_kept()
5650        -> Result<(), anyhow::Error> {
5651            let test_path = testutils::create_temp_dir().await?;
5652            let src = test_path.join("src");
5653            let update = test_path.join("update");
5654            let dst = test_path.join("dst");
5655            tokio::fs::create_dir(&src).await?;
5656            tokio::fs::create_dir(&update).await?;
5657            // src `data` is a DIRECTORY (with a file inside); update `data` is a FILE.
5658            tokio::fs::create_dir(src.join("data")).await?;
5659            tokio::fs::write(src.join("data").join("inner.txt"), "SRC-DIR-CONTENT").await?;
5660            tokio::fs::write(update.join("data"), "UPDATE-FILE-EXCLUDED").await?;
5661
5662            // `data/` (dir-only) includes the directory form of the name; `data/**` includes its
5663            // contents. The update FILE `data` matches neither and is excluded by type — the
5664            // symmetric form of the bot's scenario.
5665            let mut filter = FilterSettings::new();
5666            filter.add_include("data/").unwrap();
5667            filter.add_include("data/**").unwrap();
5668            let mut settings = common_settings(false, false);
5669            settings.filter = Some(filter);
5670            assert!(settings.copy_settings.delete.is_none());
5671
5672            link(
5673                &PROGRESS,
5674                &test_path,
5675                &src,
5676                &dst,
5677                &Some(update.clone()),
5678                &settings,
5679                false,
5680            )
5681            .await?;
5682
5683            // the excluded update FILE must NOT overwrite/replace the src directory.
5684            assert!(
5685                dst.join("data").is_dir(),
5686                "src `data` directory must be materialized when the update file is excluded"
5687            );
5688            assert!(
5689                dst.join("data").join("inner.txt").exists(),
5690                "src directory contents must be linked through"
5691            );
5692            assert!(
5693                are_hardlinked(
5694                    &src.join("data").join("inner.txt"),
5695                    &dst.join("data").join("inner.txt")
5696                ),
5697                "src directory's file must be hard-linked into the destination"
5698            );
5699            Ok(())
5700        }
5701
5702        /// `--update-exclusive` + the type-mismatch scenario: src `cache` is a FILE, update `cache`
5703        /// is a DIRECTORY excluded by `cache/`. Under exclusive mode only the (filter-passing)
5704        /// update set materializes, so an EXCLUDED update entry materializes NOTHING — the src is
5705        /// not materialized (it is not a fallback under exclusivity), and no stale src copy is left.
5706        /// This mirrors the NotFound-under-exclusive case (`return Ok(Default::default())`).
5707        #[tokio::test]
5708        #[traced_test]
5709        async fn type_mismatch_excluded_update_dir_update_exclusive_materializes_nothing()
5710        -> Result<(), anyhow::Error> {
5711            let test_path = testutils::create_temp_dir().await?;
5712            let src = test_path.join("src");
5713            let update = test_path.join("update");
5714            let dst = test_path.join("dst");
5715            tokio::fs::create_dir(&src).await?;
5716            tokio::fs::create_dir(&update).await?;
5717            tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
5718            tokio::fs::create_dir(update.join("cache")).await?;
5719            tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
5720            // a filter-passing update-only file proves the rest of the exclusive copy still works.
5721            tokio::fs::write(update.join("wanted.txt"), "wanted").await?;
5722
5723            let mut filter = FilterSettings::new();
5724            filter.add_exclude("cache/").unwrap();
5725            let mut settings = common_settings(false, false);
5726            settings.update_exclusive = true;
5727            settings.filter = Some(filter);
5728
5729            link(
5730                &PROGRESS,
5731                &test_path,
5732                &src,
5733                &dst,
5734                &Some(update.clone()),
5735                &settings,
5736                false,
5737            )
5738            .await?;
5739
5740            assert!(
5741                !dst.join("cache").exists(),
5742                "under --update-exclusive an excluded-update type-mismatch must materialize nothing \
5743                 (no excluded dir, no stale src file)"
5744            );
5745            assert!(
5746                dst.join("wanted.txt").exists(),
5747                "filter-passing update-only entries are still copied under --update-exclusive"
5748            );
5749            Ok(())
5750        }
5751
5752        /// `--delete` + the type-mismatch scenario under normal `--update`: the src `cache` FILE is
5753        /// materialized (union) and MUST be retained by the keep-set — never materialized-then-pruned
5754        /// — while a pre-existing extraneous dst entry is removed. Also confirms the excluded update
5755        /// directory leaves no leftover. `prune_extraneous` would otherwise prune the dst `cache`
5756        /// file (a dir-only `cache/` exclude does not protect a file), so correctness depends on
5757        /// `cache` staying in the keep-set.
5758        #[tokio::test]
5759        #[traced_test]
5760        async fn type_mismatch_excluded_update_dir_delete_keeps_src_file()
5761        -> Result<(), anyhow::Error> {
5762            let test_path = testutils::create_temp_dir().await?;
5763            let src = test_path.join("src");
5764            let update = test_path.join("update");
5765            let dst = test_path.join("dst");
5766            tokio::fs::create_dir(&src).await?;
5767            tokio::fs::create_dir(&update).await?;
5768            tokio::fs::create_dir(&dst).await?;
5769            tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
5770            tokio::fs::create_dir(update.join("cache")).await?;
5771            tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
5772            // pre-existing extraneous dst entry that --delete should prune.
5773            tokio::fs::write(dst.join("stale.txt"), "stale").await?;
5774
5775            let mut filter = FilterSettings::new();
5776            filter.add_exclude("cache/").unwrap();
5777            let mut settings = common_settings(false, true); // --delete implies --overwrite
5778            settings.filter = Some(filter);
5779            settings.copy_settings.delete = Some(copy::DeleteSettings {
5780                delete_excluded: false,
5781            });
5782
5783            link(
5784                &PROGRESS,
5785                &test_path,
5786                &src,
5787                &dst,
5788                &Some(update.clone()),
5789                &settings,
5790                false,
5791            )
5792            .await?;
5793
5794            assert!(
5795                dst.join("cache").is_file(),
5796                "src `cache` file must survive --delete (kept in the keep-set, not pruned)"
5797            );
5798            assert_eq!(
5799                tokio::fs::read_to_string(dst.join("cache")).await?,
5800                "SRC-FILE"
5801            );
5802            assert!(
5803                !dst.join("cache").is_dir(),
5804                "the excluded update directory must leave no leftover"
5805            );
5806            assert!(
5807                !dst.join("stale.txt").exists(),
5808                "extraneous dst entry must be pruned by --delete"
5809            );
5810            Ok(())
5811        }
5812    }
5813    mod dry_run_tests {
5814        use super::*;
5815
5816        #[tokio::test]
5817        async fn update_delete_preview_keeps_direct_and_delegated_pruning_beneath_outer_dst()
5818        -> Result<(), anyhow::Error> {
5819            let root = testutils::create_temp_dir().await?;
5820            let src = root.join("src");
5821            let update = root.join("update");
5822            let outside = root.join("outside");
5823            let dst = root.join("dst");
5824            tokio::fs::create_dir_all(src.join("direct")).await?;
5825            tokio::fs::create_dir_all(update.join("delegated")).await?;
5826            tokio::fs::create_dir_all(outside.join("direct")).await?;
5827            tokio::fs::create_dir_all(outside.join("delegated")).await?;
5828            tokio::fs::write(outside.join("direct/stale"), "DIRECT-OUTSIDE").await?;
5829            tokio::fs::write(outside.join("delegated/stale"), "DELEGATED-OUTSIDE").await?;
5830            tokio::fs::symlink(&outside, &dst).await?;
5831            let mut settings = common_settings(false, true);
5832            settings.dry_run = Some(crate::config::DryRunMode::Brief);
5833            settings.copy_settings.dry_run = settings.dry_run;
5834            settings.copy_settings.delete = Some(copy::DeleteSettings {
5835                delete_excluded: false,
5836            });
5837            let summary = link(
5838                &PROGRESS,
5839                &root,
5840                &src,
5841                &dst,
5842                &Some(update.clone()),
5843                &settings,
5844                false,
5845            )
5846            .await?;
5847            assert_eq!(summary.copy_summary.rm_summary.files_removed, 0);
5848            assert_eq!(
5849                tokio::fs::read_to_string(outside.join("direct/stale")).await?,
5850                "DIRECT-OUTSIDE"
5851            );
5852            assert_eq!(
5853                tokio::fs::read_to_string(outside.join("delegated/stale")).await?,
5854                "DELEGATED-OUTSIDE"
5855            );
5856
5857            let real_dst = root.join("real-dst");
5858            tokio::fs::create_dir_all(real_dst.join("direct")).await?;
5859            tokio::fs::create_dir_all(real_dst.join("delegated")).await?;
5860            tokio::fs::write(real_dst.join("delegated/stale"), "INSIDE-STALE").await?;
5861            let real_summary = link(
5862                &PROGRESS,
5863                &root,
5864                &src,
5865                &real_dst,
5866                &Some(update),
5867                &settings,
5868                false,
5869            )
5870            .await?;
5871            assert_eq!(real_summary.copy_summary.rm_summary.files_removed, 1);
5872            assert_eq!(
5873                tokio::fs::read_to_string(real_dst.join("delegated/stale")).await?,
5874                "INSIDE-STALE"
5875            );
5876            Ok(())
5877        }
5878
5879        #[tokio::test]
5880        async fn update_exclusive_delete_preview_keeps_selected_shared_file()
5881        -> Result<(), anyhow::Error> {
5882            let root = testutils::create_temp_dir().await?;
5883            let src = root.join("src");
5884            let update = root.join("update");
5885            let dst = root.join("dst");
5886            tokio::fs::create_dir(&src).await?;
5887            tokio::fs::create_dir(&update).await?;
5888            tokio::fs::create_dir(&dst).await?;
5889            tokio::fs::write(src.join("shared"), b"old").await?;
5890            tokio::fs::write(update.join("shared"), b"replacement").await?;
5891            tokio::fs::write(dst.join("shared"), b"destination").await?;
5892            tokio::fs::write(dst.join("stale"), b"stale").await?;
5893
5894            let mut settings = common_settings(false, false);
5895            settings.update_exclusive = true;
5896            settings.dry_run = Some(crate::config::DryRunMode::Brief);
5897            settings.copy_settings.dry_run = settings.dry_run;
5898            settings.copy_settings.delete = Some(copy::DeleteSettings {
5899                delete_excluded: false,
5900            });
5901
5902            let summary = link(
5903                &PROGRESS,
5904                &root,
5905                &src,
5906                &dst,
5907                &Some(update),
5908                &settings,
5909                false,
5910            )
5911            .await?;
5912
5913            assert_eq!(summary.hard_links_created, 0);
5914            assert_eq!(summary.copy_summary.files_copied, 1);
5915            assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
5916            assert!(dst.join("shared").exists());
5917            assert!(dst.join("stale").exists());
5918            Ok(())
5919        }
5920
5921        #[tokio::test]
5922        async fn update_exclusive_delete_preview_omits_source_only_file()
5923        -> Result<(), anyhow::Error> {
5924            let root = testutils::create_temp_dir().await?;
5925            let src = root.join("src");
5926            let update = root.join("update");
5927            let dst = root.join("dst");
5928            tokio::fs::create_dir(&src).await?;
5929            tokio::fs::create_dir(&update).await?;
5930            tokio::fs::create_dir(&dst).await?;
5931            tokio::fs::write(src.join("source-only"), b"source").await?;
5932            tokio::fs::write(dst.join("source-only"), b"destination").await?;
5933
5934            let mut settings = common_settings(false, false);
5935            settings.update_exclusive = true;
5936            settings.dry_run = Some(crate::config::DryRunMode::Brief);
5937            settings.copy_settings.dry_run = settings.dry_run;
5938            settings.copy_settings.delete = Some(copy::DeleteSettings {
5939                delete_excluded: false,
5940            });
5941
5942            let summary = link(
5943                &PROGRESS,
5944                &root,
5945                &src,
5946                &dst,
5947                &Some(update),
5948                &settings,
5949                false,
5950            )
5951            .await?;
5952
5953            assert_eq!(summary.hard_links_created, 0);
5954            assert_eq!(summary.copy_summary.files_copied, 0);
5955            assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
5956            assert!(dst.join("source-only").exists());
5957            Ok(())
5958        }
5959
5960        /// Test that dry-run mode for files doesn't create hard links.
5961        #[tokio::test]
5962        #[traced_test]
5963        async fn test_dry_run_file_does_not_create_link() -> Result<(), anyhow::Error> {
5964            let tmp_dir = testutils::setup_test_dir().await?;
5965            let test_path = tmp_dir.as_path();
5966            let src_file = test_path.join("foo/0.txt");
5967            let dst_file = test_path.join("dst_link.txt");
5968            // verify destination doesn't exist
5969            assert!(
5970                !dst_file.exists(),
5971                "destination should not exist before dry-run"
5972            );
5973            let summary = link(
5974                &PROGRESS,
5975                test_path,
5976                &src_file,
5977                &dst_file,
5978                &None,
5979                &Settings {
5980                    copy_settings: CopySettings {
5981                        reflink: Default::default(),
5982                        local_copy_handoff: Default::default(),
5983                        dereference: false,
5984                        fail_early: false,
5985                        overwrite: false,
5986                        overwrite_compare: Default::default(),
5987                        overwrite_filter: None,
5988                        ignore_existing: false,
5989                        chunk_size: 0,
5990                        skip_specials: false,
5991                        remote_copy_buffer_size: 0,
5992                        filter: None,
5993                        dry_run: None,
5994                        delete: None,
5995                    },
5996                    update_compare: Default::default(),
5997                    update_exclusive: false,
5998                    filter: None,
5999                    dry_run: Some(crate::config::DryRunMode::Brief),
6000                    preserve: preserve::preserve_all(),
6001                },
6002                false,
6003            )
6004            .await?;
6005            // verify destination still doesn't exist
6006            assert!(!dst_file.exists(), "dry-run should not create hard link");
6007            // verify summary reports what would be created
6008            assert_eq!(
6009                summary.hard_links_created, 1,
6010                "dry-run should report 1 hard link that would be created"
6011            );
6012            Ok(())
6013        }
6014        /// Test that dry-run mode for directories doesn't create the destination directory.
6015        #[tokio::test]
6016        #[traced_test]
6017        async fn test_dry_run_directory_does_not_create_destination() -> Result<(), anyhow::Error> {
6018            let tmp_dir = testutils::setup_test_dir().await?;
6019            let test_path = tmp_dir.as_path();
6020            let dst_path = test_path.join("nonexistent_dst");
6021            // verify destination doesn't exist
6022            assert!(
6023                !dst_path.exists(),
6024                "destination should not exist before dry-run"
6025            );
6026            let summary = link(
6027                &PROGRESS,
6028                test_path,
6029                &test_path.join("foo"),
6030                &dst_path,
6031                &None,
6032                &Settings {
6033                    copy_settings: CopySettings {
6034                        reflink: Default::default(),
6035                        local_copy_handoff: Default::default(),
6036                        dereference: false,
6037                        fail_early: false,
6038                        overwrite: false,
6039                        overwrite_compare: Default::default(),
6040                        overwrite_filter: None,
6041                        ignore_existing: false,
6042                        chunk_size: 0,
6043                        skip_specials: false,
6044                        remote_copy_buffer_size: 0,
6045                        filter: None,
6046                        dry_run: None,
6047                        delete: None,
6048                    },
6049                    update_compare: Default::default(),
6050                    update_exclusive: false,
6051                    filter: None,
6052                    dry_run: Some(crate::config::DryRunMode::Brief),
6053                    preserve: preserve::preserve_all(),
6054                },
6055                false,
6056            )
6057            .await?;
6058            // verify destination still doesn't exist
6059            assert!(
6060                !dst_path.exists(),
6061                "dry-run should not create destination directory"
6062            );
6063            // verify summary reports what would be created
6064            assert!(
6065                summary.hard_links_created > 0,
6066                "dry-run should report hard links that would be created"
6067            );
6068            Ok(())
6069        }
6070        /// Test that dry-run mode correctly reports symlinks (not as hard links).
6071        #[tokio::test]
6072        #[traced_test]
6073        async fn test_dry_run_symlinks_counted_correctly() -> Result<(), anyhow::Error> {
6074            let tmp_dir = testutils::setup_test_dir().await?;
6075            let test_path = tmp_dir.as_path();
6076            // baz contains: 4.txt (file), 5.txt (symlink), 6.txt (symlink)
6077            let src_path = test_path.join("foo/baz");
6078            let dst_path = test_path.join("dst_baz");
6079            // verify destination doesn't exist
6080            assert!(
6081                !dst_path.exists(),
6082                "destination should not exist before dry-run"
6083            );
6084            let summary = link(
6085                &PROGRESS,
6086                test_path,
6087                &src_path,
6088                &dst_path,
6089                &None,
6090                &Settings {
6091                    copy_settings: CopySettings {
6092                        reflink: Default::default(),
6093                        local_copy_handoff: Default::default(),
6094                        dereference: false,
6095                        fail_early: false,
6096                        overwrite: false,
6097                        overwrite_compare: Default::default(),
6098                        overwrite_filter: None,
6099                        ignore_existing: false,
6100                        chunk_size: 0,
6101                        skip_specials: false,
6102                        remote_copy_buffer_size: 0,
6103                        filter: None,
6104                        dry_run: None,
6105                        delete: None,
6106                    },
6107                    update_compare: Default::default(),
6108                    update_exclusive: false,
6109                    filter: None,
6110                    dry_run: Some(crate::config::DryRunMode::Brief),
6111                    preserve: preserve::preserve_all(),
6112                },
6113                false,
6114            )
6115            .await?;
6116            // verify destination still doesn't exist
6117            assert!(!dst_path.exists(), "dry-run should not create destination");
6118            // baz contains 1 regular file (4.txt) and 2 symlinks (5.txt, 6.txt)
6119            assert_eq!(
6120                summary.hard_links_created, 1,
6121                "dry-run should report 1 hard link (for 4.txt)"
6122            );
6123            assert_eq!(
6124                summary.copy_summary.symlinks_created, 2,
6125                "dry-run should report 2 symlinks (5.txt and 6.txt)"
6126            );
6127            Ok(())
6128        }
6129    }
6130
6131    /// Verify that fail-early preserves the summary from the failing subtree.
6132    ///
6133    /// Regression test: the fail-early return path in the join loop must
6134    /// accumulate error.summary from the failing child into the parent's
6135    /// link_summary. Without this, directories_created from the child subtree
6136    /// would be lost.
6137    #[tokio::test]
6138    #[traced_test]
6139    async fn test_fail_early_preserves_summary_from_failing_subtree() -> Result<(), anyhow::Error> {
6140        let tmp_dir = testutils::create_temp_dir().await?;
6141        let test_path = tmp_dir.as_path();
6142        // src/sub/  has a file and an unreadable subdirectory:
6143        //   src/sub/good.txt            <-- links successfully
6144        //   src/sub/unreadable_dir/     <-- mode 000, can't be traversed
6145        //     src/sub/unreadable_dir/f.txt
6146        let src_dir = test_path.join("src");
6147        let sub_dir = src_dir.join("sub");
6148        let bad_dir = sub_dir.join("unreadable_dir");
6149        tokio::fs::create_dir_all(&bad_dir).await?;
6150        tokio::fs::write(sub_dir.join("good.txt"), "content").await?;
6151        tokio::fs::write(bad_dir.join("f.txt"), "data").await?;
6152        tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o000)).await?;
6153        let dst_dir = test_path.join("dst");
6154        let result = link(
6155            &PROGRESS,
6156            test_path,
6157            &src_dir,
6158            &dst_dir,
6159            &None,
6160            &Settings {
6161                copy_settings: CopySettings {
6162                    fail_early: true,
6163                    ..common_settings(false, false).copy_settings
6164                },
6165                ..common_settings(false, false)
6166            },
6167            false,
6168        )
6169        .await;
6170        // restore permissions for cleanup
6171        tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o755)).await?;
6172        let error = result.expect_err("link should fail due to unreadable directory");
6173        // sub/'s link_internal created dst/sub/ (directories_created=1) before
6174        // its join loop encountered the unreadable_dir error. that directory
6175        // creation must be reflected in the error summary propagated up to the
6176        // top-level caller.
6177        assert!(
6178            error.summary.copy_summary.directories_created >= 2,
6179            "fail-early summary should include directories from the failing subtree, \
6180             got directories_created={} (expected >= 2: dst/ and dst/sub/)",
6181            error.summary.copy_summary.directories_created
6182        );
6183        Ok(())
6184    }
6185
6186    #[tokio::test]
6187    #[traced_test]
6188    async fn skip_specials_skips_socket_in_link() -> Result<(), anyhow::Error> {
6189        let tmp_dir = testutils::setup_test_dir().await?;
6190        let test_path = tmp_dir.as_path();
6191        let src = test_path.join("src_dir");
6192        let dst = test_path.join("dst_dir");
6193        tokio::fs::create_dir(&src).await?;
6194        tokio::fs::write(src.join("file.txt"), "hello").await?;
6195        let _listener = std::os::unix::net::UnixListener::bind(src.join("test.sock"))?;
6196        let mut settings = common_settings(false, false);
6197        settings.copy_settings.skip_specials = true;
6198        let summary = link(&PROGRESS, test_path, &src, &dst, &None, &settings, false).await?;
6199        assert_eq!(summary.hard_links_created, 1);
6200        assert_eq!(summary.copy_summary.specials_skipped, 1);
6201        assert!(dst.join("file.txt").exists());
6202        assert!(!dst.join("test.sock").exists());
6203        Ok(())
6204    }
6205
6206    #[tokio::test]
6207    #[traced_test]
6208    async fn delete_skips_pruning_when_link_has_errors() -> Result<(), anyhow::Error> {
6209        let tmp_dir = testutils::setup_test_dir().await?;
6210        let test_path = tmp_dir.as_path();
6211        let src = test_path.join("foo");
6212        let dst = test_path.join("bar");
6213        // baseline link establishes the destination (no delete)
6214        link(
6215            &PROGRESS,
6216            test_path,
6217            &src,
6218            &dst,
6219            &None,
6220            &common_settings(false, false),
6221            false,
6222        )
6223        .await?;
6224        // an extraneous file that --delete would normally prune
6225        tokio::fs::write(dst.join("extraneous.txt"), b"junk").await?;
6226        // make a source sub-directory unreadable so traversal fails (fail_early is false).
6227        // a directory is used because --overwrite with mtime-equal files skips copying
6228        // identical files; a directory's read_dir fails unconditionally when mode is 0o000.
6229        let unreadable = src.join("baz");
6230        let original = tokio::fs::metadata(&unreadable).await?.permissions();
6231        tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
6232
6233        let delete_settings = Settings {
6234            copy_settings: CopySettings {
6235                overwrite: true,
6236                fail_early: false,
6237                delete: Some(copy::DeleteSettings {
6238                    delete_excluded: false,
6239                }),
6240                ..common_settings(false, true).copy_settings
6241            },
6242            ..common_settings(false, true)
6243        };
6244        let result = link(
6245            &PROGRESS,
6246            test_path,
6247            &src,
6248            &dst,
6249            &None,
6250            &delete_settings,
6251            false,
6252        )
6253        .await;
6254
6255        tokio::fs::set_permissions(&unreadable, original).await?;
6256
6257        assert!(
6258            result.is_err(),
6259            "link of the unreadable directory should fail"
6260        );
6261        assert!(
6262            dst.join("extraneous.txt").exists(),
6263            "pruning must be skipped when the link/update pass reported errors"
6264        );
6265        assert!(logs_contain(
6266            "because entry processing failed or did not provide complete exact names"
6267        ));
6268        Ok(())
6269    }
6270
6271    #[tokio::test]
6272    #[traced_test]
6273    async fn skip_specials_top_level_socket_in_link() -> Result<(), anyhow::Error> {
6274        let tmp_dir = testutils::setup_test_dir().await?;
6275        let test_path = tmp_dir.as_path();
6276        let src_socket = test_path.join("test.sock");
6277        let dst = test_path.join("dst.sock");
6278        let _listener = std::os::unix::net::UnixListener::bind(&src_socket)?;
6279        let mut settings = common_settings(false, false);
6280        settings.copy_settings.skip_specials = true;
6281        let summary = link(
6282            &PROGRESS,
6283            test_path,
6284            &src_socket,
6285            &dst,
6286            &None,
6287            &settings,
6288            false,
6289        )
6290        .await?;
6291        assert_eq!(summary.copy_summary.specials_skipped, 1);
6292        assert_eq!(summary.hard_links_created, 0);
6293        assert!(!dst.exists());
6294        Ok(())
6295    }
6296
6297    /// Stress tests exercising max-files-in-flight saturation during link.
6298    mod max_files_in_flight_tests {
6299        use super::*;
6300
6301        fn available_open_file_capacity(capacity: usize) -> usize {
6302            let waker = futures::task::noop_waker();
6303            let mut context = std::task::Context::from_waker(&waker);
6304            let mut permits = Vec::new();
6305            for _ in 0..capacity {
6306                let mut permit = Box::pin(throttle::open_file_permit());
6307                match std::future::Future::poll(permit.as_mut(), &mut context) {
6308                    std::task::Poll::Ready(permit) => permits.push(permit),
6309                    std::task::Poll::Pending => break,
6310                }
6311            }
6312            permits.len()
6313        }
6314
6315        async fn reacquire_all_open_file_capacity(
6316            admission: &testutils::AdmissionLimit,
6317            capacity: usize,
6318        ) -> Result<(), anyhow::Error> {
6319            let permits = admission
6320                .run_with_timeout(std::time::Duration::from_secs(20), async {
6321                    let mut permits = Vec::new();
6322                    for _ in 0..capacity {
6323                        permits.push(throttle::open_file_permit().await);
6324                    }
6325                    permits
6326                })
6327                .await
6328                .context("link operation did not return all open-file capacity")?;
6329            drop(permits);
6330            Ok(())
6331        }
6332
6333        #[tokio::test]
6334        async fn update_directory_transition_retains_exact_handle_and_held_admission()
6335        -> anyhow::Result<()> {
6336            use std::os::fd::AsRawFd as _;
6337
6338            let root = testutils::create_temp_dir().await?;
6339            tokio::fs::write(root.join("source"), b"source").await?;
6340            tokio::fs::create_dir(root.join("update")).await?;
6341            let admission = testutils::AdmissionLimit::new().await;
6342            admission.set_files_in_flight(1);
6343            let parent = Dir::open_root_dir(&root, false, congestion::Side::Source).await?;
6344            let src_handle = parent.child(std::ffi::OsStr::new("source")).await?;
6345            let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
6346            let src_fd = src_handle.as_fd().as_raw_fd();
6347            let update_fd = update_handle.as_fd().as_raw_fd();
6348            let src_probe = testutils::FdIdentityProbe::capture(src_fd);
6349            let update_probe = testutils::FdIdentityProbe::capture(update_fd);
6350            let (src_probe, update_probe) = match (src_probe, update_probe) {
6351                (Ok(src_probe), Ok(update_probe)) => (src_probe, update_probe),
6352                (src_probe, update_probe) => {
6353                    let probe_error = match src_probe {
6354                        Err(error) => error,
6355                        Ok(_) => match update_probe {
6356                            Err(error) => error,
6357                            Ok(_) => {
6358                                unreachable!("at least one fd identity probe must have failed")
6359                            }
6360                        },
6361                    };
6362                    drop(src_handle);
6363                    drop(update_handle);
6364                    drop(parent);
6365                    drop(admission);
6366                    let cleanup_result = tokio::fs::remove_dir_all(root).await;
6367                    return match cleanup_result {
6368                        Ok(()) => Err(probe_error.into()),
6369                        Err(cleanup_error) => Err(anyhow::Error::new(probe_error).context(
6370                            format!("link fd-lifetime fixture did not clean up: {cleanup_error:#}"),
6371                        )),
6372                    };
6373                }
6374            };
6375            let mut entry = AdmittedLinkEntry::new(
6376                src_handle,
6377                Some(LeafPermit::OpenFile(throttle::open_file_permit().await)),
6378            );
6379            entry.update_handle = Some(update_handle);
6380
6381            let update_entry = entry.into_update_entry();
6382            let retained_directory = update_entry.kind() == EntryKind::Dir;
6383            let transferred_held_admission = update_entry.admission().is_some();
6384            // retain probe errors until the direct owner and its admission have both quiesced.
6385            let source_closed = src_probe.original_is_closed();
6386            let update_stayed_open = update_probe.original_is_closed().map(|closed| !closed);
6387            let mut next_permit = Box::pin(throttle::open_file_permit());
6388            let (capacity_stayed_held, early_permit) = match futures::poll!(next_permit.as_mut()) {
6389                std::task::Poll::Pending => (true, None),
6390                std::task::Poll::Ready(permit) => (false, Some(permit)),
6391            };
6392            drop(update_entry);
6393            let update_closed = update_probe.original_is_closed();
6394            let reacquire_result = match early_permit {
6395                Some(permit) => Ok(permit),
6396                None => {
6397                    tokio::time::timeout(std::time::Duration::from_secs(1), next_permit.as_mut())
6398                        .await
6399                        .context("the delegated directory did not return open-file capacity")
6400                }
6401            };
6402            let reacquire_result = reacquire_result.map(drop);
6403            drop(parent);
6404            drop(admission);
6405            let cleanup_result = tokio::fs::remove_dir_all(root).await;
6406            let source_closed = source_closed?;
6407            let update_stayed_open = update_stayed_open?;
6408            let update_closed = update_closed?;
6409            reacquire_result?;
6410            cleanup_result?;
6411            assert!(
6412                retained_directory,
6413                "the admitted update owner lost its authoritative directory type"
6414            );
6415            assert!(transferred_held_admission);
6416            assert!(source_closed);
6417            assert!(update_stayed_open);
6418            assert!(update_closed);
6419            assert!(
6420                capacity_stayed_held,
6421                "the admitted update owner released capacity before copy dispatch"
6422            );
6423            Ok(())
6424        }
6425
6426        /// A reliable file hint lets the rlink filter skip before open-file admission.
6427        #[tokio::test]
6428        async fn filtered_hinted_file_does_not_wait_for_admission() -> Result<(), anyhow::Error> {
6429            let root = testutils::create_temp_dir().await?;
6430            let src = root.join("src");
6431            tokio::fs::create_dir(&src).await?;
6432            tokio::fs::write(src.join("leaf"), b"x").await?;
6433            let admission = testutils::AdmissionLimit::new().await;
6434            admission.set_files_in_flight(1);
6435            let held = throttle::open_file_permit().await;
6436            let src_dir =
6437                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6438            let hints = src_dir.read_entries().await?;
6439            assert_eq!(
6440                hints,
6441                vec![(std::ffi::OsString::from("leaf"), Some(EntryKind::File))],
6442                "the fixture filesystem must provide the reliable hint this test exercises"
6443            );
6444            let mut filter = crate::filter::FilterSettings::new();
6445            filter.add_exclude("leaf")?;
6446            let mut settings = common_settings(false, false);
6447            settings.filter = Some(filter.clone());
6448            settings.copy_settings.filter = Some(filter);
6449            let dst = root.join("dst");
6450            let operation = link_dir_contents(
6451                &PROGRESS,
6452                &src_dir,
6453                None,
6454                None,
6455                None,
6456                std::ffi::OsStr::new("dst"),
6457                &src,
6458                &dst,
6459                None,
6460                std::path::Path::new(""),
6461                &src,
6462                &dst,
6463                false,
6464                false,
6465                None,
6466                &settings,
6467                Summary::default(),
6468                SourceEntries::Live,
6469                UpdateEntries::Live,
6470                None,
6471            );
6472            let result = admission
6473                .run_with_timeout(std::time::Duration::from_secs(1), operation)
6474                .await;
6475            drop(held);
6476            let summary = result.context("rlink filter skip waited for open-file admission")??;
6477            assert_eq!(summary.copy_summary.files_skipped, 1);
6478            assert_eq!(summary.hard_links_created, 0);
6479            Ok(())
6480        }
6481
6482        /// A reliable update-only file hint lets the filter skip before copy admission.
6483        #[tokio::test]
6484        async fn filtered_hinted_update_file_does_not_wait_for_admission()
6485        -> Result<(), anyhow::Error> {
6486            let root = testutils::create_temp_dir().await?;
6487            let src = root.join("src");
6488            let update = root.join("update");
6489            tokio::fs::create_dir(&src).await?;
6490            tokio::fs::create_dir(&update).await?;
6491            tokio::fs::write(update.join("leaf"), b"x").await?;
6492            let admission = testutils::AdmissionLimit::new().await;
6493            admission.set_files_in_flight(1);
6494            let held = throttle::open_file_permit().await;
6495            let src_dir =
6496                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6497            let update_dir =
6498                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
6499            let hints = update_dir.read_entries().await?;
6500            assert_eq!(
6501                hints,
6502                vec![(std::ffi::OsString::from("leaf"), Some(EntryKind::File))],
6503                "the fixture filesystem must provide the reliable hint this test exercises"
6504            );
6505            let mut filter = crate::filter::FilterSettings::new();
6506            filter.add_exclude("leaf")?;
6507            let mut settings = common_settings(false, false);
6508            settings.filter = Some(filter.clone());
6509            settings.copy_settings.filter = Some(filter);
6510            let dst = root.join("dst");
6511            let operation = crate::task_scope::scope_tasks(link_dir_contents(
6512                &PROGRESS,
6513                &src_dir,
6514                Some(&update_dir),
6515                None,
6516                None,
6517                std::ffi::OsStr::new("dst"),
6518                &src,
6519                &dst,
6520                Some(&update),
6521                std::path::Path::new(""),
6522                &src,
6523                &dst,
6524                false,
6525                false,
6526                None,
6527                &settings,
6528                Summary::default(),
6529                SourceEntries::Live,
6530                UpdateEntries::Live,
6531                None,
6532            ));
6533            let result = admission
6534                .run_with_timeout(std::time::Duration::from_secs(1), operation)
6535                .await;
6536            drop(held);
6537            let summary =
6538                result.context("rlink update filter skip waited for open-file admission")??;
6539            assert_eq!(summary.copy_summary.files_skipped, 1);
6540            assert_eq!(summary.copy_summary.files_copied, 0);
6541            Ok(())
6542        }
6543
6544        #[test]
6545        fn source_directory_hint_requires_admission_only_for_a_dual_tree_decision() {
6546            assert!(matches!(
6547                source_entry_admission(Some(EntryKind::Dir), true),
6548                EntryAdmission::RootOrDelegated
6549            ));
6550            assert!(matches!(
6551                source_entry_admission(Some(EntryKind::Dir), false),
6552                EntryAdmission::HintedDirectory
6553            ));
6554        }
6555
6556        /// Rlink preserves a positive directory hint through its worker dispatch.
6557        #[tokio::test]
6558        async fn hinted_directory_classifies_while_pool_is_saturated() -> Result<(), anyhow::Error>
6559        {
6560            let root = testutils::create_temp_dir().await?;
6561            let src_path = root.join("src");
6562            let dst_path = root.join("dst");
6563            tokio::fs::create_dir(&src_path).await?;
6564            let admission = testutils::AdmissionLimit::new().await;
6565            admission.set_files_in_flight(1);
6566            let held = throttle::open_file_permit().await;
6567            let src_parent = Arc::new(
6568                Dir::open_parent_dir(&root, congestion::Side::Source)
6569                    .await?
6570                    .into_tree(),
6571            );
6572            let mut settings = common_settings(false, false);
6573            settings.dry_run = Some(crate::config::DryRunMode::Brief);
6574            settings.copy_settings.dry_run = settings.dry_run;
6575            let result = admission
6576                .run_with_timeout(
6577                    std::time::Duration::from_secs(1),
6578                    link_internal(
6579                        &PROGRESS,
6580                        &src_parent,
6581                        None,
6582                        None,
6583                        std::ffi::OsStr::new("src"),
6584                        &src_path,
6585                        &dst_path,
6586                        None,
6587                        std::path::Path::new(""),
6588                        UpdateRootRequirement::Optional,
6589                        &settings,
6590                        false,
6591                        walk::EntryAdmission::HintedDirectory.into(),
6592                        copy::DeleteScanAnchor::new(&dst_path, std::path::Path::new("")),
6593                    ),
6594                )
6595                .await;
6596            drop(held);
6597            let summary = result.context("hinted rlink directory waited for admission")??;
6598            assert_eq!(summary.summary.copy_summary.directories_created, 1);
6599            Ok(())
6600        }
6601
6602        /// A separate update counterpart makes a source-directory hint insufficient to classify
6603        /// the combined link decision without leaf admission.
6604        #[tokio::test(flavor = "current_thread")]
6605        async fn hinted_source_with_update_admits_before_source_classification()
6606        -> Result<(), anyhow::Error> {
6607            let root = testutils::create_temp_dir().await?;
6608            let src_root = root.join("src");
6609            let update_root = root.join("update");
6610            let dst_root = root.join("dst");
6611            tokio::fs::create_dir(&src_root).await?;
6612            tokio::fs::create_dir(&update_root).await?;
6613            tokio::fs::create_dir(src_root.join("entry")).await?;
6614            tokio::fs::write(update_root.join("entry"), b"x").await?;
6615
6616            let admission = testutils::AdmissionLimit::new().await;
6617            admission.set_files_in_flight(1);
6618            let stat_resource =
6619                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
6620            admission.set_max_ops_in_flight(stat_resource, 1);
6621            let src_parent =
6622                Arc::new(Dir::open_root_dir(&src_root, false, congestion::Side::Source).await?);
6623            let update_parent =
6624                Arc::new(Dir::open_root_dir(&update_root, false, congestion::Side::Source).await?);
6625            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
6626            let mut settings = common_settings(false, false);
6627            settings.dry_run = Some(crate::config::DryRunMode::Brief);
6628            settings.copy_settings.dry_run = settings.dry_run;
6629
6630            let operation = link_internal(
6631                &PROGRESS,
6632                &src_parent,
6633                Some((&update_parent, std::ffi::OsStr::new("entry"))),
6634                None,
6635                std::ffi::OsStr::new("entry"),
6636                &src_root,
6637                &dst_root,
6638                Some(&update_root),
6639                std::path::Path::new("entry"),
6640                UpdateRootRequirement::Optional,
6641                &settings,
6642                false,
6643                EntryAdmission::HintedDirectory.into(),
6644                copy::DeleteScanAnchor::new(&dst_root, std::path::Path::new("entry")),
6645            );
6646            tokio::pin!(operation);
6647            assert!(
6648                futures::poll!(operation.as_mut()).is_pending(),
6649                "source classification must stop at the saturated Stat gate"
6650            );
6651            let mut permit_probe = Box::pin(throttle::open_file_permit());
6652            let admitted_before_source = futures::poll!(permit_probe.as_mut()).is_pending();
6653            drop(permit_probe);
6654
6655            drop(held_stat);
6656            let summary = admission
6657                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
6658                .await
6659                .context("rlink did not resume after source classification was released")??;
6660            assert!(
6661                admitted_before_source,
6662                "the hinted source opened before admission for its separate update decision"
6663            );
6664            assert_eq!(summary.summary.copy_summary.files_copied, 1);
6665            Ok(())
6666        }
6667
6668        /// An update-only directory preserves its hint through delegation into copy.
6669        #[tokio::test]
6670        async fn hinted_update_directory_classifies_while_pool_is_saturated()
6671        -> Result<(), anyhow::Error> {
6672            let root = testutils::create_temp_dir().await?;
6673            let src = root.join("src");
6674            let update = root.join("update");
6675            let dst = root.join("dst");
6676            tokio::fs::create_dir(&src).await?;
6677            tokio::fs::create_dir(&update).await?;
6678            tokio::fs::create_dir(update.join("dir")).await?;
6679            let admission = testutils::AdmissionLimit::new().await;
6680            admission.set_files_in_flight(1);
6681            let held = throttle::open_file_permit().await;
6682            let src_dir =
6683                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6684            let update_dir =
6685                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
6686            let mut settings = common_settings(false, false);
6687            settings.dry_run = Some(crate::config::DryRunMode::Brief);
6688            settings.copy_settings.dry_run = settings.dry_run;
6689            let operation = crate::task_scope::scope_tasks(link_dir_contents(
6690                &PROGRESS,
6691                &src_dir,
6692                Some(&update_dir),
6693                None,
6694                None,
6695                std::ffi::OsStr::new("dst"),
6696                &src,
6697                &dst,
6698                Some(&update),
6699                std::path::Path::new(""),
6700                &src,
6701                &dst,
6702                false,
6703                false,
6704                None,
6705                &settings,
6706                Summary::default(),
6707                SourceEntries::Live,
6708                UpdateEntries::Live,
6709                None,
6710            ));
6711            let result = admission
6712                .run_with_timeout(std::time::Duration::from_secs(1), operation)
6713                .await;
6714            drop(held);
6715            let summary =
6716                result.context("hinted update directory waited for delegated copy admission")??;
6717            assert_eq!(summary.copy_summary.directories_created, 1);
6718            Ok(())
6719        }
6720
6721        /// Public root setup must reserve open-file capacity before strict probes or operand-parent
6722        /// opens. A filtered root otherwise returns before `link_internal` reaches its admission
6723        /// point, and concurrent callers can bypass the budget entirely.
6724        #[tokio::test]
6725        async fn filtered_public_root_waits_for_admission_before_setup() -> Result<(), anyhow::Error>
6726        {
6727            let root = testutils::create_temp_dir().await?;
6728            let src = root.join("src");
6729            let dst = root.join("dst");
6730            tokio::fs::write(&src, b"x").await?;
6731            let mut filter = crate::filter::FilterSettings::new();
6732            filter.add_exclude("src")?;
6733            let mut settings = common_settings(false, false);
6734            settings.filter = Some(filter.clone());
6735            settings.copy_settings.filter = Some(filter);
6736            let admission = testutils::AdmissionLimit::new().await;
6737            admission.set_files_in_flight(1);
6738            let stat_resource =
6739                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
6740            admission.set_max_ops_in_flight(stat_resource, 1);
6741            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
6742            let operation = link(&PROGRESS, &root, &src, &dst, &None, &settings, false);
6743            tokio::pin!(operation);
6744            let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
6745            let mut second_permit = Box::pin(throttle::open_file_permit());
6746            let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
6747            drop(second_permit);
6748            drop(held_stat);
6749            let result = admission
6750                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
6751                .await;
6752            assert!(
6753                stopped_at_stat_gate,
6754                "rlink root did not reach the held stat gate"
6755            );
6756            let summary =
6757                result.context("rlink root did not resume after stat capacity was released")??;
6758            assert!(
6759                !setup_bypassed_admission,
6760                "rlink performed root setup before open-file admission"
6761            );
6762            assert_eq!(summary.copy_summary.files_skipped, 1);
6763            Ok(())
6764        }
6765
6766        /// A root or delegated rlink worker without a caller-supplied guard must reserve capacity
6767        /// before opening its source classification handle.
6768        #[tokio::test]
6769        async fn root_acquires_capacity_before_classification() -> Result<(), anyhow::Error> {
6770            let root = testutils::create_temp_dir().await?;
6771            let src_path = root.join("src");
6772            let dst_path = root.join("dst");
6773            tokio::fs::write(&src_path, b"x").await?;
6774            let admission = testutils::AdmissionLimit::new().await;
6775            let src_parent = Arc::new(
6776                Dir::open_parent_dir(&root, congestion::Side::Source)
6777                    .await?
6778                    .into_tree(),
6779            );
6780            let mut settings = common_settings(false, false);
6781            settings.dry_run = Some(crate::config::DryRunMode::Brief);
6782            settings.copy_settings.dry_run = settings.dry_run;
6783            admission.set_files_in_flight(1);
6784            let stat_resource =
6785                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
6786            admission.set_max_ops_in_flight(stat_resource, 1);
6787            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
6788            let operation = link_internal(
6789                &PROGRESS,
6790                &src_parent,
6791                None,
6792                None,
6793                std::ffi::OsStr::new("src"),
6794                &src_path,
6795                &dst_path,
6796                None,
6797                std::path::Path::new(""),
6798                UpdateRootRequirement::Optional,
6799                &settings,
6800                false,
6801                EntryAdmission::RootOrDelegated.into(),
6802                copy::DeleteScanAnchor::new(&dst_path, std::path::Path::new("")),
6803            );
6804            tokio::pin!(operation);
6805            let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
6806            let mut second_permit = Box::pin(throttle::open_file_permit());
6807            let classification_bypassed_admission =
6808                futures::poll!(second_permit.as_mut()).is_ready();
6809            drop(second_permit);
6810            drop(held_stat);
6811            let result = admission
6812                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
6813                .await;
6814            assert!(
6815                stopped_at_stat_gate,
6816                "rlink root did not reach the held stat gate"
6817            );
6818            assert!(
6819                !classification_bypassed_admission,
6820                "rlink reached fd-based classification before open-file admission"
6821            );
6822            let summary = result.context(
6823                "rlink root did not resume after classification capacity was released",
6824            )??;
6825            assert_eq!(summary.summary.hard_links_created, 1);
6826            Ok(())
6827        }
6828
6829        /// A hard-link leaf must retain its admission guard through the actual
6830        /// fd-bearing `linkat`, not release it after source/update classification.
6831        #[tokio::test]
6832        async fn hard_link_holds_open_file_capacity_until_link_finishes()
6833        -> Result<(), anyhow::Error> {
6834            let root = testutils::create_temp_dir().await?;
6835            let src_root = root.join("src");
6836            let dst_root = root.join("dst");
6837            tokio::fs::create_dir(&src_root).await?;
6838            tokio::fs::create_dir(&dst_root).await?;
6839            tokio::fs::write(src_root.join("entry"), b"x").await?;
6840            let src_parent =
6841                Arc::new(Dir::open_root_dir(&src_root, false, congestion::Side::Source).await?);
6842            let dst_parent = Arc::new(
6843                Dir::open_root_dir(&dst_root, false, congestion::Side::Destination).await?,
6844            );
6845            let admission = testutils::AdmissionLimit::new().await;
6846            admission.set_files_in_flight(1);
6847            let permit = Some(LeafPermit::OpenFile(throttle::open_file_permit().await));
6848            let hard_link_resource = throttle::Resource::meta(
6849                throttle::Side::Destination,
6850                throttle::MetadataOp::HardLink,
6851            );
6852            admission.set_max_ops_in_flight(hard_link_resource, 1);
6853            let held_hard_link = throttle::ops_in_flight_permit(hard_link_resource).await;
6854            let dst_entry = dst_root.join("entry");
6855            let task_dst_entry = dst_entry.clone();
6856            let mut task = tokio::spawn(async move {
6857                link_internal(
6858                    &PROGRESS,
6859                    &src_parent,
6860                    None,
6861                    Some(&dst_parent),
6862                    std::ffi::OsStr::new("entry"),
6863                    &src_root.join("entry"),
6864                    &task_dst_entry,
6865                    None,
6866                    std::path::Path::new(""),
6867                    UpdateRootRequirement::Optional,
6868                    &common_settings(false, false),
6869                    true,
6870                    EntryAdmission::from(permit).into(),
6871                    copy::DeleteScanAnchor::new(&task_dst_entry, std::path::Path::new("")),
6872                )
6873                .await
6874            });
6875            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6876            let second_permit = tokio::time::timeout(
6877                std::time::Duration::from_millis(500),
6878                throttle::open_file_permit(),
6879            )
6880            .await;
6881            let released_before_link_finished = second_permit.is_ok();
6882            drop(second_permit);
6883            drop(held_hard_link);
6884            let task_result = admission
6885                .run_with_timeout(std::time::Duration::from_secs(20), &mut task)
6886                .await
6887                .context("hard link did not resume after metadata capacity was released")?;
6888            let summary = task_result?.map_err(|error| error.source)?;
6889            assert!(
6890                !released_before_link_finished,
6891                "hard-link work released its open-file permit before linkat completed"
6892            );
6893            assert_eq!(summary.summary.hard_links_created, 1);
6894            assert!(dst_entry.exists());
6895            Ok(())
6896        }
6897
6898        /// Deep + wide link: a directory tree deeper than the files-in-flight limit, with files at every
6899        /// level. Verifies directories do not retain leaf admission across recursion.
6900        #[tokio::test]
6901        #[traced_test]
6902        async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
6903        -> Result<(), anyhow::Error> {
6904            let tmp_dir = testutils::create_temp_dir().await?;
6905            let src = tmp_dir.join("src");
6906            let dst = tmp_dir.join("dst");
6907            let depth = 20;
6908            let files_per_level = 5;
6909            let limit = 1;
6910            // create a directory chain deeper than the permit limit, with files at each level
6911            let mut dir = src.clone();
6912            for level in 0..depth {
6913                tokio::fs::create_dir_all(&dir).await?;
6914                for f in 0..files_per_level {
6915                    tokio::fs::write(
6916                        dir.join(format!("f{}_{}.txt", level, f)),
6917                        format!("L{}F{}", level, f),
6918                    )
6919                    .await?;
6920                }
6921                dir = dir.join(format!("d{}", level));
6922            }
6923            let admission = testutils::AdmissionLimit::new().await;
6924            admission.set_files_in_flight(limit);
6925            let summary = admission
6926                .run_with_timeout(
6927                    std::time::Duration::from_secs(30),
6928                    link(
6929                        &PROGRESS,
6930                        tmp_dir.as_path(),
6931                        &src,
6932                        &dst,
6933                        &None,
6934                        &common_settings(false, false),
6935                        false,
6936                    ),
6937                )
6938                .await
6939                .context("link timed out — possible deadlock")?
6940                .context("link failed")?;
6941            assert_eq!(summary.hard_links_created, depth * files_per_level);
6942            assert_eq!(summary.copy_summary.directories_created, depth);
6943            // spot-check that hard links work by reading content at a few levels
6944            let mut check_dir = dst.clone();
6945            for level in 0..depth {
6946                let content =
6947                    tokio::fs::read_to_string(check_dir.join(format!("f{}_0.txt", level))).await?;
6948                assert_eq!(content, format!("L{}F0", level));
6949                check_dir = check_dir.join(format!("d{}", level));
6950            }
6951            Ok(())
6952        }
6953
6954        /// Matching source/update directories release cap-one admission before direct recursion.
6955        /// Retaining the permit in [`AdmittedLinkEntry::close_for_directory`] would leave the next
6956        /// directory in this chain waiting forever for the only slot.
6957        #[tokio::test]
6958        #[traced_test]
6959        async fn matching_dual_directory_chain_releases_admission_before_recursion()
6960        -> Result<(), anyhow::Error> {
6961            let tmp_dir = testutils::create_temp_dir().await?;
6962            let src = tmp_dir.join("src");
6963            let update = tmp_dir.join("update");
6964            let dst = tmp_dir.join("dst");
6965            tokio::fs::create_dir(&src).await?;
6966            tokio::fs::create_dir(&update).await?;
6967            let depth = 12;
6968            let mut src_dir = src.clone();
6969            let mut update_dir = update.clone();
6970            for level in 0..depth {
6971                let name = format!("d{level}");
6972                src_dir.push(&name);
6973                update_dir.push(&name);
6974                tokio::fs::create_dir(&src_dir).await?;
6975                tokio::fs::create_dir(&update_dir).await?;
6976            }
6977            let admission = testutils::AdmissionLimit::new().await;
6978            admission.set_files_in_flight(1);
6979            let summary = admission
6980                .run_with_timeout(
6981                    std::time::Duration::from_secs(5),
6982                    link(
6983                        &PROGRESS,
6984                        tmp_dir.as_path(),
6985                        &src,
6986                        &dst,
6987                        &Some(update),
6988                        &common_settings(false, false),
6989                        false,
6990                    ),
6991                )
6992                .await
6993                .context("link timed out — direct dual-directory recursion retained admission")?
6994                .context("link failed")?;
6995            assert_eq!(summary.copy_summary.directories_created, depth + 1);
6996            assert!(
6997                src_dir
6998                    .strip_prefix(&src)
6999                    .is_ok_and(|tail| dst.join(tail).is_dir())
7000            );
7001            Ok(())
7002        }
7003
7004        /// A file-type-changed directory must release transferred admission before recursion.
7005        ///
7006        /// Scenario: many src entries are regular files (so the spawn loop
7007        /// pre-acquires files-in-flight permits for them), but the corresponding
7008        /// `update` entries are directories (file types differ). link_internal
7009        /// then closes the source comparison handle and transfers the selected update handle plus
7010        /// admission into `copy_child`. The copy driver dispatches that exact classification and
7011        /// releases admission before directory descent; retaining it while children acquire would
7012        /// deadlock against a saturated pool.
7013        #[tokio::test]
7014        #[traced_test]
7015        async fn type_changed_directory_releases_admission_before_recursion()
7016        -> Result<(), anyhow::Error> {
7017            let tmp_dir = testutils::create_temp_dir().await?;
7018            let src = tmp_dir.join("src");
7019            let update = tmp_dir.join("update");
7020            let dst = tmp_dir.join("dst");
7021            tokio::fs::create_dir(&src).await?;
7022            tokio::fs::create_dir(&update).await?;
7023            let n = 8;
7024            // src/eN: regular files. update/eN: directories with inner files.
7025            // file types differ -> link takes the !is_file_type_same branch
7026            // -> calls copy::copy(update/eN, dst/eN).
7027            for i in 0..n {
7028                tokio::fs::write(src.join(format!("e{}", i)), format!("src-{}", i)).await?;
7029                let upd_subdir = update.join(format!("e{}", i));
7030                tokio::fs::create_dir(&upd_subdir).await?;
7031                for j in 0..3 {
7032                    tokio::fs::write(
7033                        upd_subdir.join(format!("inner_{}.txt", j)),
7034                        format!("upd-{}-{}", i, j),
7035                    )
7036                    .await?;
7037                }
7038            }
7039            // saturate the pool so retaining delegated admission during descent blocks child work.
7040            let admission = testutils::AdmissionLimit::new().await;
7041            admission.set_files_in_flight(2);
7042            let summary = admission
7043                .run_with_timeout(
7044                    std::time::Duration::from_secs(30),
7045                    link(
7046                        &PROGRESS,
7047                        tmp_dir.as_path(),
7048                        &src,
7049                        &dst,
7050                        &Some(update.clone()),
7051                        &common_settings(false, false),
7052                        false,
7053                    ),
7054                )
7055                .await
7056                .context(
7057                    "link timed out — delegated admission was retained during directory descent",
7058                )?
7059                .context("link failed")?;
7060            // every entry was a type-mismatch -> copied from update.
7061            // copy::copy on a directory creates the dir and copies inner files.
7062            assert_eq!(summary.copy_summary.directories_created, n + 1); // +1 for dst itself
7063            assert_eq!(summary.copy_summary.files_copied, n * 3);
7064            // verify content came from update, not src
7065            for i in 0..n {
7066                for j in 0..3 {
7067                    let content =
7068                        tokio::fs::read_to_string(dst.join(format!("e{}/inner_{}.txt", i, j)))
7069                            .await?;
7070                    assert_eq!(content, format!("upd-{}-{}", i, j));
7071                }
7072            }
7073            Ok(())
7074        }
7075
7076        async fn check_update_read_error(
7077            fail_early: bool,
7078            child_error: bool,
7079        ) -> anyhow::Result<()> {
7080            use std::os::unix::fs::MetadataExt as _;
7081
7082            let root = testutils::create_temp_dir().await?;
7083            let src = root.join("src");
7084            let update = root.join("update");
7085            let dst = root.join("dst");
7086            for path in [&src, &update, &dst] {
7087                tokio::fs::create_dir(path).await?;
7088            }
7089            tokio::fs::write(src.join("first"), b"first").await?;
7090            let (second, _socket) = if child_error {
7091                tokio::fs::create_dir(src.join("sub")).await?;
7092                tokio::fs::write(src.join("sub/good"), b"good").await?;
7093                (
7094                    "sub/good",
7095                    Some(std::os::unix::net::UnixListener::bind(
7096                        src.join("sub/bad.sock"),
7097                    )?),
7098                )
7099            } else {
7100                tokio::fs::write(src.join("second"), b"second").await?;
7101                ("second", None)
7102            };
7103            tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
7104            tokio::fs::set_permissions(&update, std::fs::Permissions::from_mode(0o751)).await?;
7105            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
7106            let admission = testutils::AdmissionLimit::new().await;
7107            admission.set_files_in_flight(2);
7108            let resource = throttle::Resource::meta(
7109                throttle::Side::Destination,
7110                throttle::MetadataOp::HardLink,
7111            );
7112            admission.set_max_ops_in_flight(resource, 1);
7113            let held_link = throttle::ops_in_flight_permit(resource).await;
7114            let src_dir =
7115                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7116            let update_dir =
7117                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7118            let dst_dir =
7119                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7120            let dst_parent =
7121                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7122            let mut settings = common_settings(false, false);
7123            settings.copy_settings.fail_early = fail_early;
7124            settings.copy_settings.delete = Some(copy::DeleteSettings {
7125                delete_excluded: false,
7126            });
7127            let progress = Box::leak(Box::new(progress::Progress::new()));
7128            let (trigger_error, read_error) = tokio::sync::oneshot::channel();
7129            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7130                progress,
7131                &src_dir,
7132                Some(&update_dir),
7133                Some(&dst_dir),
7134                Some(&dst_parent),
7135                std::ffi::OsStr::new("dst"),
7136                &src,
7137                &dst,
7138                Some(&update),
7139                std::path::Path::new(""),
7140                &src,
7141                &dst,
7142                true,
7143                false,
7144                None,
7145                &settings,
7146                Summary {
7147                    copy_summary: copy::Summary {
7148                        directories_created: 1,
7149                        ..Default::default()
7150                    },
7151                    ..Default::default()
7152                },
7153                SourceEntries::Injected(vec![
7154                    (std::ffi::OsString::from("first"), Some(EntryKind::File)),
7155                    if child_error {
7156                        (std::ffi::OsString::from("sub"), Some(EntryKind::Dir))
7157                    } else {
7158                        (std::ffi::OsString::from("second"), Some(EntryKind::File))
7159                    },
7160                ]),
7161                UpdateEntries::InjectedReadError(read_error),
7162                None,
7163            ));
7164            tokio::pin!(operation);
7165            // the read error is held until real source workers have started and retain both
7166            // permits. the hard-link gate prevents their destination syscalls from completing.
7167            let started = tokio::time::timeout(std::time::Duration::from_secs(5), async {
7168                loop {
7169                    assert!(futures::poll!(operation.as_mut()).is_pending());
7170                    let status = progress.ops.get();
7171                    if status.started >= if child_error { 3 } else { 2 }
7172                        && available_open_file_capacity(2) == 0
7173                    {
7174                        break;
7175                    }
7176                    tokio::task::yield_now().await;
7177                }
7178            })
7179            .await;
7180            trigger_error
7181                .send(std::io::Error::from_raw_os_error(libc::EIO))
7182                .unwrap();
7183            let gated_result = tokio::time::timeout(
7184                std::time::Duration::from_millis(if fail_early { 1000 } else { 100 }),
7185                operation.as_mut(),
7186            )
7187            .await;
7188            let returned_while_gated = gated_result.is_ok();
7189            drop(held_link);
7190            let result = match gated_result {
7191                Ok(result) => result,
7192                Err(_) => {
7193                    admission
7194                        .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7195                        .await?
7196                }
7197            };
7198            reacquire_all_open_file_capacity(&admission, 2).await?;
7199            started.context("source workers did not start while update enumeration was pending")?;
7200            assert_eq!(
7201                returned_while_gated, fail_early,
7202                "only fail-early may cancel pending source workers"
7203            );
7204            let error = result.expect_err("update enumeration must fail");
7205            let message = format!("{:#}", error.source);
7206            assert!(
7207                message.contains(&std::io::Error::from_raw_os_error(libc::EIO).to_string()),
7208                "{message}"
7209            );
7210            if !child_error {
7211                assert!(message.contains(update.to_str().unwrap()), "{message}");
7212                assert_eq!(
7213                    error
7214                        .source
7215                        .downcast_ref::<std::io::Error>()
7216                        .unwrap()
7217                        .raw_os_error(),
7218                    Some(libc::EIO)
7219                );
7220            }
7221            assert_eq!(
7222                error.summary.hard_links_created,
7223                if fail_early { 0 } else { 2 }
7224            );
7225            assert_eq!(
7226                error.summary.copy_summary.directories_created,
7227                if child_error { 2 } else { 1 }
7228            );
7229            assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
7230            assert_eq!(
7231                tokio::fs::read(dst.join("must-survive")).await?,
7232                b"extraneous"
7233            );
7234            assert_eq!(
7235                tokio::fs::metadata(&dst).await?.mode() & 0o777,
7236                if fail_early { 0o700 } else { 0o751 }
7237            );
7238            for name in ["first", second] {
7239                if fail_early {
7240                    assert!(!dst.join(name).exists());
7241                } else {
7242                    let source = tokio::fs::metadata(src.join(name)).await?;
7243                    let destination = tokio::fs::metadata(dst.join(name)).await?;
7244                    assert_eq!(
7245                        (source.dev(), source.ino()),
7246                        (destination.dev(), destination.ino())
7247                    );
7248                }
7249            }
7250            if child_error {
7251                assert!(message.contains("unsupported"), "{message}");
7252            }
7253            Ok(())
7254        }
7255
7256        #[tokio::test(flavor = "current_thread")]
7257        async fn update_read_error_drains_pending_source_workers() -> anyhow::Result<()> {
7258            check_update_read_error(false, false).await
7259        }
7260
7261        #[tokio::test(flavor = "current_thread")]
7262        async fn update_read_error_folds_failed_child_partial_summary() -> anyhow::Result<()> {
7263            check_update_read_error(false, true).await
7264        }
7265
7266        #[tokio::test(flavor = "current_thread")]
7267        async fn update_read_error_fail_early_cancels_pending_source_workers() -> anyhow::Result<()>
7268        {
7269            check_update_read_error(true, false).await
7270        }
7271
7272        #[tokio::test]
7273        async fn source_read_error_finalizes_without_dispatching_update_entries()
7274        -> anyhow::Result<()> {
7275            use std::os::unix::fs::MetadataExt as _;
7276
7277            for with_update in [false, true] {
7278                for fail_early in [false, true] {
7279                    let root = testutils::create_temp_dir().await?;
7280                    let src = root.join("src");
7281                    let update = root.join("update");
7282                    let dst = root.join("dst");
7283                    for path in [&src, &update, &dst] {
7284                        tokio::fs::create_dir(path).await?;
7285                    }
7286                    tokio::fs::write(src.join("same"), b"source").await?;
7287                    tokio::fs::write(update.join("same"), b"different update").await?;
7288                    tokio::fs::write(update.join("update-only"), b"update-only").await?;
7289                    tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
7290                    for (path, mode) in [(&src, 0o750), (&update, 0o751), (&dst, 0o700)] {
7291                        tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
7292                            .await?;
7293                    }
7294                    let src_dir =
7295                        Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7296                    let update_dir = Arc::new(
7297                        Dir::open_root_dir(&update, false, congestion::Side::Source).await?,
7298                    );
7299                    let dst_dir = Arc::new(
7300                        Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?,
7301                    );
7302                    let dst_parent = Arc::new(
7303                        Dir::open_root_dir(&root, false, congestion::Side::Destination).await?,
7304                    );
7305                    let mut settings = common_settings(false, false);
7306                    settings.copy_settings.fail_early = fail_early;
7307                    settings.copy_settings.delete = Some(copy::DeleteSettings {
7308                        delete_excluded: false,
7309                    });
7310                    let error = crate::task_scope::scope_tasks(link_dir_contents(
7311                        &PROGRESS,
7312                        &src_dir,
7313                        with_update.then_some(&update_dir),
7314                        Some(&dst_dir),
7315                        Some(&dst_parent),
7316                        std::ffi::OsStr::new("dst"),
7317                        &src,
7318                        &dst,
7319                        with_update.then_some(update.as_path()),
7320                        std::path::Path::new(""),
7321                        &src,
7322                        &dst,
7323                        true,
7324                        false,
7325                        None,
7326                        &settings,
7327                        Summary {
7328                            copy_summary: copy::Summary {
7329                                directories_created: 1,
7330                                ..Default::default()
7331                            },
7332                            ..Default::default()
7333                        },
7334                        SourceEntries::InjectedReadError(std::io::Error::from_raw_os_error(
7335                            libc::EIO,
7336                        )),
7337                        UpdateEntries::Live,
7338                        None,
7339                    ))
7340                    .await
7341                    .expect_err("source enumeration must fail");
7342                    assert!(format!("{:#}", error.source).contains(src.to_str().unwrap()));
7343                    assert_eq!(
7344                        error
7345                            .source
7346                            .downcast_ref::<std::io::Error>()
7347                            .unwrap()
7348                            .raw_os_error(),
7349                        Some(libc::EIO)
7350                    );
7351                    assert_eq!(error.summary.copy_summary.directories_created, 1);
7352                    assert_eq!(error.summary.hard_links_created, 0);
7353                    assert_eq!(error.summary.copy_summary.files_copied, 0);
7354                    assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
7355                    assert!(!dst.join("same").exists());
7356                    assert!(!dst.join("update-only").exists());
7357                    assert_eq!(
7358                        tokio::fs::read(dst.join("must-survive")).await?,
7359                        b"extraneous"
7360                    );
7361                    assert_eq!(
7362                        tokio::fs::metadata(&dst).await?.mode() & 0o777,
7363                        if fail_early {
7364                            0o700
7365                        } else if with_update {
7366                            0o751
7367                        } else {
7368                            0o750
7369                        }
7370                    );
7371                }
7372            }
7373            Ok(())
7374        }
7375
7376        #[tokio::test]
7377        async fn source_read_error_finishes_empty_directory_cleanup() -> anyhow::Result<()> {
7378            for dry_run in [false, true] {
7379                let root = testutils::create_temp_dir().await?;
7380                let src = root.join("src");
7381                let dst = root.join("dst");
7382                let dst_sub = dst.join("sub");
7383                tokio::fs::create_dir(&src).await?;
7384                tokio::fs::create_dir(&dst).await?;
7385                if !dry_run {
7386                    tokio::fs::create_dir(&dst_sub).await?;
7387                }
7388                let src_dir =
7389                    Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7390                let dst_parent =
7391                    Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7392                let dst_dir = if dry_run {
7393                    None
7394                } else {
7395                    Some(Arc::new(
7396                        Dir::open_root_dir(&dst_sub, false, congestion::Side::Destination).await?,
7397                    ))
7398                };
7399                let mut settings = common_settings(false, false);
7400                let mut filter = crate::filter::FilterSettings::new();
7401                filter.add_include("*.match")?;
7402                settings.filter = Some(filter.clone());
7403                settings.copy_settings.filter = Some(filter);
7404                settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
7405                settings.copy_settings.dry_run = settings.dry_run;
7406                let error = crate::task_scope::scope_tasks(link_dir_contents(
7407                    &PROGRESS,
7408                    &src_dir,
7409                    None,
7410                    dst_dir.as_ref(),
7411                    (!dry_run).then_some(&dst_parent),
7412                    std::ffi::OsStr::new("sub"),
7413                    &src,
7414                    &dst,
7415                    None,
7416                    std::path::Path::new("sub"),
7417                    &src,
7418                    &dst_sub,
7419                    true,
7420                    true,
7421                    None,
7422                    &settings,
7423                    Summary {
7424                        copy_summary: copy::Summary {
7425                            directories_created: 1,
7426                            ..Default::default()
7427                        },
7428                        ..Default::default()
7429                    },
7430                    SourceEntries::InjectedReadError(std::io::Error::from_raw_os_error(libc::EIO)),
7431                    UpdateEntries::Live,
7432                    None,
7433                ))
7434                .await
7435                .expect_err("cleanup must preserve the read error");
7436                assert_eq!(
7437                    error
7438                        .source
7439                        .downcast_ref::<std::io::Error>()
7440                        .unwrap()
7441                        .raw_os_error(),
7442                    Some(libc::EIO)
7443                );
7444                assert_eq!(error.summary.copy_summary.directories_created, 0);
7445                assert!(!dst_sub.exists());
7446            }
7447            Ok(())
7448        }
7449
7450        /// A completed source error must be reaped while the producer waits to admit a later
7451        /// entry. Otherwise two blocked symlink workers can retain the whole pool forever.
7452        #[tokio::test(flavor = "current_thread")]
7453        async fn source_fail_early_reaps_error_while_later_admission_is_saturated()
7454        -> Result<(), anyhow::Error> {
7455            let root = testutils::create_temp_dir().await?;
7456            let src = root.join("src");
7457            let dst = root.join("dst");
7458            tokio::fs::create_dir(&src).await?;
7459            tokio::fs::create_dir(&dst).await?;
7460            tokio::fs::write(src.join("vanished"), b"vanished").await?;
7461            tokio::fs::symlink("target-a", src.join("blocked-a")).await?;
7462            tokio::fs::symlink("target-b", src.join("blocked-b")).await?;
7463            tokio::fs::write(src.join("later"), b"later").await?;
7464            tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
7465            let admission = testutils::AdmissionLimit::new().await;
7466            admission.set_files_in_flight(2);
7467            let stat_resource =
7468                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7469            admission.set_max_ops_in_flight(stat_resource, 1);
7470            let readlink_resource =
7471                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::ReadLink);
7472            admission.set_max_ops_in_flight(readlink_resource, 1);
7473            let src_dir =
7474                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7475            let dst_dir =
7476                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7477            let dst_parent =
7478                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7479            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7480            let mut held_readlink = Some(throttle::ops_in_flight_permit(readlink_resource).await);
7481            let mut filter = crate::filter::FilterSettings::new();
7482            filter.add_exclude("never/")?;
7483            let mut settings = common_settings(false, false);
7484            settings.filter = Some(filter.clone());
7485            settings.copy_settings.filter = Some(filter);
7486            settings.copy_settings.fail_early = true;
7487            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7488                &PROGRESS,
7489                &src_dir,
7490                None,
7491                Some(&dst_dir),
7492                Some(&dst_parent),
7493                std::ffi::OsStr::new("dst"),
7494                &src,
7495                &dst,
7496                None,
7497                std::path::Path::new(""),
7498                &src,
7499                &dst,
7500                false,
7501                false,
7502                None,
7503                &settings,
7504                Summary::default(),
7505                SourceEntries::Injected(vec![
7506                    (std::ffi::OsString::from("vanished"), Some(EntryKind::File)),
7507                    (
7508                        std::ffi::OsString::from("blocked-a"),
7509                        Some(EntryKind::Symlink),
7510                    ),
7511                    (
7512                        std::ffi::OsString::from("blocked-b"),
7513                        Some(EntryKind::Symlink),
7514                    ),
7515                    (std::ffi::OsString::from("later"), Some(EntryKind::File)),
7516                ]),
7517                UpdateEntries::Live,
7518                None,
7519            ));
7520            tokio::pin!(operation);
7521            let mut completed_while_gated = None;
7522            let saturated = tokio::time::timeout(std::time::Duration::from_secs(5), async {
7523                loop {
7524                    if let std::task::Poll::Ready(output) = futures::poll!(operation.as_mut()) {
7525                        completed_while_gated = Some(output);
7526                        return;
7527                    }
7528                    if available_open_file_capacity(2) == 0 {
7529                        return;
7530                    }
7531                    tokio::task::yield_now().await;
7532                }
7533            })
7534            .await;
7535            let remove_result = tokio::fs::remove_file(src.join("vanished")).await;
7536            drop(held_stat);
7537            if let Some(output) = completed_while_gated {
7538                drop(held_readlink.take());
7539                reacquire_all_open_file_capacity(&admission, 2).await?;
7540                return Err(anyhow!(
7541                    "source link completed before its gated workers saturated admission: {:?}",
7542                    output.err().map(|error| format!("{:#}", error.source))
7543                ));
7544            }
7545            if let Err(error) = saturated {
7546                drop(held_readlink.take());
7547                let _ = admission
7548                    .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7549                    .await;
7550                reacquire_all_open_file_capacity(&admission, 2).await?;
7551                return Err(error).context("source workers did not saturate open-file admission");
7552            }
7553            if let Err(error) = remove_result {
7554                drop(held_readlink.take());
7555                let _ = admission
7556                    .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7557                    .await;
7558                reacquire_all_open_file_capacity(&admission, 2).await?;
7559                return Err(error).context("failed to remove the injected source entry");
7560            }
7561            let result =
7562                tokio::time::timeout(std::time::Duration::from_secs(1), operation.as_mut()).await;
7563            drop(held_readlink.take());
7564            if result.is_err() {
7565                let _ = admission
7566                    .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7567                    .await;
7568            }
7569            reacquire_all_open_file_capacity(&admission, 2).await?;
7570            let error = result
7571                .context("fail-early source error was not reaped during admission")?
7572                .expect_err("the vanished source entry must fail the link");
7573            assert!(format!("{:#}", error.source).contains("vanished"));
7574            assert!(!dst.join("later").exists());
7575            assert!(!dst.join("uninjected").exists());
7576            Ok(())
7577        }
7578
7579        /// Unknown source classification errors are child errors, so keep-going must still run
7580        /// later siblings and fold the successful work into the combined result.
7581        #[tokio::test(flavor = "current_thread")]
7582        async fn source_error_keeps_going_without_pruning_partial_collection()
7583        -> Result<(), anyhow::Error> {
7584            let root = testutils::create_temp_dir().await?;
7585            let src = root.join("src");
7586            let dst = root.join("dst");
7587            tokio::fs::create_dir(&src).await?;
7588            tokio::fs::create_dir(&dst).await?;
7589            tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
7590            tokio::fs::write(src.join("first"), b"first").await?;
7591            tokio::fs::write(src.join("last"), b"last").await?;
7592            tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
7593            let admission = testutils::AdmissionLimit::new().await;
7594            admission.set_files_in_flight(3);
7595            let src_dir =
7596                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7597            let dst_dir =
7598                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7599            let dst_parent =
7600                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7601            let mut filter = crate::filter::FilterSettings::new();
7602            filter.add_exclude("never/")?;
7603            let mut settings = common_settings(false, false);
7604            settings.copy_settings.delete = Some(copy::DeleteSettings {
7605                delete_excluded: false,
7606            });
7607            settings.filter = Some(filter.clone());
7608            settings.copy_settings.filter = Some(filter);
7609            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7610                &PROGRESS,
7611                &src_dir,
7612                None,
7613                Some(&dst_dir),
7614                Some(&dst_parent),
7615                std::ffi::OsStr::new("dst"),
7616                &src,
7617                &dst,
7618                None,
7619                std::path::Path::new(""),
7620                &src,
7621                &dst,
7622                false,
7623                false,
7624                None,
7625                &settings,
7626                Summary::default(),
7627                SourceEntries::Injected(vec![
7628                    (std::ffi::OsString::from("first"), None),
7629                    (std::ffi::OsString::from("vanished"), None),
7630                    (std::ffi::OsString::from("last"), None),
7631                ]),
7632                UpdateEntries::Live,
7633                None,
7634            ));
7635            let result = admission
7636                .run_with_timeout(std::time::Duration::from_secs(20), operation)
7637                .await;
7638            reacquire_all_open_file_capacity(&admission, 3).await?;
7639            let error = result
7640                .context("keep-going unknown-source link did not terminate")?
7641                .expect_err("the injected vanished source must fail");
7642            assert_eq!(error.summary.hard_links_created, 2);
7643            assert_eq!(tokio::fs::read(dst.join("first")).await?, b"first");
7644            assert_eq!(tokio::fs::read(dst.join("last")).await?, b"last");
7645            assert!(!dst.join("uninjected").exists());
7646            assert_eq!(
7647                tokio::fs::read(dst.join("must-survive")).await?,
7648                b"extraneous"
7649            );
7650            assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
7651            Ok(())
7652        }
7653
7654        /// An excluded unknown directory must be counted from its exact worker classification,
7655        /// never from a fallback file kind in the producer loop.
7656        #[tokio::test]
7657        async fn source_unknown_excluded_directory_uses_directory_skip_accounting()
7658        -> Result<(), anyhow::Error> {
7659            let root = testutils::create_temp_dir().await?;
7660            let src = root.join("src");
7661            let dst = root.join("dst");
7662            tokio::fs::create_dir(&src).await?;
7663            tokio::fs::create_dir(&dst).await?;
7664            tokio::fs::create_dir(src.join("node")).await?;
7665            tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
7666            let src_dir =
7667                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7668            let dst_dir =
7669                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7670            let dst_parent =
7671                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7672            let mut filter = crate::filter::FilterSettings::new();
7673            filter.add_exclude("node/")?;
7674            let mut settings = common_settings(false, false);
7675            settings.filter = Some(filter.clone());
7676            settings.copy_settings.filter = Some(filter);
7677            let summary = crate::task_scope::scope_tasks(link_dir_contents(
7678                &PROGRESS,
7679                &src_dir,
7680                None,
7681                Some(&dst_dir),
7682                Some(&dst_parent),
7683                std::ffi::OsStr::new("dst"),
7684                &src,
7685                &dst,
7686                None,
7687                std::path::Path::new(""),
7688                &src,
7689                &dst,
7690                false,
7691                false,
7692                None,
7693                &settings,
7694                Summary::default(),
7695                SourceEntries::Injected(vec![(std::ffi::OsString::from("node"), None)]),
7696                UpdateEntries::Live,
7697                None,
7698            ))
7699            .await?;
7700            assert_eq!(summary.copy_summary.directories_skipped, 1);
7701            assert_eq!(summary.copy_summary.files_skipped, 0);
7702            assert!(!dst.join("node").exists());
7703            assert!(!dst.join("uninjected").exists());
7704            Ok(())
7705        }
7706
7707        /// Unknown source entries must be admitted and spawned independently before either exact
7708        /// classification completes.
7709        #[tokio::test(flavor = "current_thread")]
7710        async fn source_unknown_workers_classify_concurrently() -> Result<(), anyhow::Error> {
7711            let root = testutils::create_temp_dir().await?;
7712            let src = root.join("src");
7713            let dst = root.join("dst");
7714            tokio::fs::create_dir(&src).await?;
7715            tokio::fs::create_dir(&dst).await?;
7716            tokio::fs::write(src.join("first"), b"first").await?;
7717            tokio::fs::write(src.join("second"), b"second").await?;
7718            tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
7719            let admission = testutils::AdmissionLimit::new().await;
7720            admission.set_files_in_flight(2);
7721            let stat_resource =
7722                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7723            admission.set_max_ops_in_flight(stat_resource, 1);
7724            let src_dir =
7725                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7726            let dst_dir =
7727                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7728            let dst_parent =
7729                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7730            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7731            let mut filter = crate::filter::FilterSettings::new();
7732            filter.add_exclude("never/")?;
7733            let mut settings = common_settings(false, false);
7734            settings.filter = Some(filter.clone());
7735            settings.copy_settings.filter = Some(filter);
7736            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7737                &PROGRESS,
7738                &src_dir,
7739                None,
7740                Some(&dst_dir),
7741                Some(&dst_parent),
7742                std::ffi::OsStr::new("dst"),
7743                &src,
7744                &dst,
7745                None,
7746                std::path::Path::new(""),
7747                &src,
7748                &dst,
7749                false,
7750                false,
7751                None,
7752                &settings,
7753                Summary::default(),
7754                SourceEntries::Injected(vec![
7755                    (std::ffi::OsString::from("first"), None),
7756                    (std::ffi::OsString::from("second"), None),
7757                ]),
7758                UpdateEntries::Live,
7759                None,
7760            ));
7761            tokio::pin!(operation);
7762            let mut completed_while_gated = None;
7763            let concurrent = tokio::time::timeout(std::time::Duration::from_secs(5), async {
7764                loop {
7765                    if let std::task::Poll::Ready(output) = futures::poll!(operation.as_mut()) {
7766                        completed_while_gated = Some(output);
7767                        return;
7768                    }
7769                    if available_open_file_capacity(2) == 0 {
7770                        return;
7771                    }
7772                    tokio::task::yield_now().await;
7773                }
7774            })
7775            .await;
7776            drop(held_stat);
7777            let task_result = admission
7778                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7779                .await;
7780            reacquire_all_open_file_capacity(&admission, 2).await?;
7781            if let Some(output) = completed_while_gated {
7782                return Err(anyhow!(
7783                    "unknown source link completed before gated classifications: {:?}",
7784                    output.err().map(|error| format!("{:#}", error.source))
7785                ));
7786            }
7787            concurrent.context("unknown source workers did not classify concurrently")?;
7788            let summary = task_result
7789                .context("unknown source classifications did not resume after stat release")??;
7790            assert_eq!(summary.hard_links_created, 2);
7791            assert!(!dst.join("uninjected").exists());
7792            Ok(())
7793        }
7794
7795        /// Included update-only file hints must be admitted and spawned independently before
7796        /// either worker's exact classification completes.
7797        #[tokio::test(flavor = "current_thread")]
7798        async fn update_only_workers_classify_concurrently() -> Result<(), anyhow::Error> {
7799            let root = testutils::create_temp_dir().await?;
7800            let src = root.join("src");
7801            let update = root.join("update");
7802            let dst = root.join("dst");
7803            tokio::fs::create_dir(&src).await?;
7804            tokio::fs::create_dir(&update).await?;
7805            tokio::fs::create_dir(&dst).await?;
7806            tokio::fs::write(update.join("first"), b"first").await?;
7807            tokio::fs::write(update.join("second"), b"second").await?;
7808            tokio::fs::write(update.join("uninjected"), b"uninjected").await?;
7809
7810            let admission = testutils::AdmissionLimit::new().await;
7811            admission.set_files_in_flight(2);
7812            let src_dir =
7813                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7814            let update_dir =
7815                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7816            let dst_dir =
7817                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7818            let dst_parent =
7819                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7820            let stat_resource =
7821                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7822            admission.set_max_ops_in_flight(stat_resource, 1);
7823            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7824            let mut filter = crate::filter::FilterSettings::new();
7825            filter.add_exclude("never/")?;
7826            let mut settings = common_settings(false, false);
7827            settings.filter = Some(filter.clone());
7828            settings.copy_settings.filter = Some(filter);
7829            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7830                &PROGRESS,
7831                &src_dir,
7832                Some(&update_dir),
7833                Some(&dst_dir),
7834                Some(&dst_parent),
7835                std::ffi::OsStr::new("dst"),
7836                &src,
7837                &dst,
7838                Some(&update),
7839                std::path::Path::new(""),
7840                &src,
7841                &dst,
7842                false,
7843                false,
7844                None,
7845                &settings,
7846                Summary::default(),
7847                SourceEntries::Live,
7848                UpdateEntries::Injected(vec![
7849                    (std::ffi::OsString::from("first"), Some(EntryKind::File)),
7850                    (std::ffi::OsString::from("second"), Some(EntryKind::File)),
7851                ]),
7852                None,
7853            ));
7854            tokio::pin!(operation);
7855            let available_while_classifying = loop {
7856                assert!(
7857                    futures::poll!(operation.as_mut()).is_pending(),
7858                    "update-only link completed while exact classifications were gated"
7859                );
7860                let mut available = Vec::new();
7861                for _ in 0..2 {
7862                    let mut probe = Box::pin(throttle::open_file_permit());
7863                    match futures::poll!(probe.as_mut()) {
7864                        std::task::Poll::Ready(permit) => available.push(permit),
7865                        std::task::Poll::Pending => break,
7866                    }
7867                }
7868                let count = available.len();
7869                drop(available);
7870                if count < 2 {
7871                    break count;
7872                }
7873                tokio::task::yield_now().await;
7874            };
7875            drop(held_stat);
7876            assert!(
7877                available_while_classifying == 0,
7878                "the first exact update-only classification serialized its sibling"
7879            );
7880            let summary = admission
7881                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7882                .await
7883                .context("update-only classifications did not resume after stat release")??;
7884            assert_eq!(summary.copy_summary.files_copied, 2);
7885            Ok(())
7886        }
7887
7888        /// A vanished update-only classification is a child error: keep-going still materializes
7889        /// both successful siblings and folds their summaries into the returned combined error.
7890        #[tokio::test(flavor = "current_thread")]
7891        async fn update_only_classification_error_keeps_going_and_folds_siblings()
7892        -> Result<(), anyhow::Error> {
7893            let root = testutils::create_temp_dir().await?;
7894            let src = root.join("src");
7895            let update = root.join("update");
7896            let dst = root.join("dst");
7897            tokio::fs::create_dir(&src).await?;
7898            tokio::fs::create_dir(&update).await?;
7899            tokio::fs::create_dir(&dst).await?;
7900            for name in ["first", "middle", "last"] {
7901                tokio::fs::write(update.join(name), name.as_bytes()).await?;
7902            }
7903            tokio::fs::write(update.join("uninjected"), b"uninjected").await?;
7904
7905            let admission = testutils::AdmissionLimit::new().await;
7906            admission.set_files_in_flight(3);
7907            let src_dir =
7908                Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7909            let update_dir =
7910                Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7911            let dst_dir =
7912                Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7913            let dst_parent =
7914                Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7915            let stat_resource =
7916                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7917            admission.set_max_ops_in_flight(stat_resource, 1);
7918            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7919            let vanished = std::ffi::OsString::from("middle");
7920            let successful = [
7921                std::ffi::OsString::from("first"),
7922                std::ffi::OsString::from("last"),
7923            ];
7924            let settings = common_settings(false, false);
7925            let operation = crate::task_scope::scope_tasks(link_dir_contents(
7926                &PROGRESS,
7927                &src_dir,
7928                Some(&update_dir),
7929                Some(&dst_dir),
7930                Some(&dst_parent),
7931                std::ffi::OsStr::new("dst"),
7932                &src,
7933                &dst,
7934                Some(&update),
7935                std::path::Path::new(""),
7936                &src,
7937                &dst,
7938                false,
7939                false,
7940                None,
7941                &settings,
7942                Summary::default(),
7943                SourceEntries::Live,
7944                UpdateEntries::Injected(vec![
7945                    (std::ffi::OsString::from("first"), Some(EntryKind::File)),
7946                    (std::ffi::OsString::from("middle"), Some(EntryKind::File)),
7947                    (std::ffi::OsString::from("last"), Some(EntryKind::File)),
7948                ]),
7949                None,
7950            ));
7951            tokio::pin!(operation);
7952            loop {
7953                assert!(
7954                    futures::poll!(operation.as_mut()).is_pending(),
7955                    "update-only link completed while exact classifications were gated"
7956                );
7957                let mut available = Vec::new();
7958                for _ in 0..3 {
7959                    let mut probe = Box::pin(throttle::open_file_permit());
7960                    match futures::poll!(probe.as_mut()) {
7961                        std::task::Poll::Ready(permit) => available.push(permit),
7962                        std::task::Poll::Pending => break,
7963                    }
7964                }
7965                let count = available.len();
7966                drop(available);
7967                if count < 3 {
7968                    break;
7969                }
7970                tokio::task::yield_now().await;
7971            }
7972            tokio::fs::remove_file(update.join(&vanished)).await?;
7973            drop(held_stat);
7974            let error = admission
7975                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7976                .await
7977                .context("keep-going update-only link did not terminate")?
7978                .expect_err("the vanished update-only entry classification must fail");
7979            assert_eq!(
7980                error.summary.copy_summary.files_copied, 2,
7981                "the combined error summary must include both successful siblings"
7982            );
7983            assert!(format!("{:#}", error.source).contains(vanished.to_string_lossy().as_ref()));
7984            for name in successful {
7985                assert_eq!(
7986                    tokio::fs::read(dst.join(&name)).await?,
7987                    name.as_encoded_bytes(),
7988                    "successful sibling {name:?} did not materialize"
7989                );
7990            }
7991            assert!(!dst.join(vanished).exists());
7992            Ok(())
7993        }
7994
7995        /// Update-only scheduling must stop before spawning a second fd-bearing copy when the
7996        /// first owns all open-file capacity. The ReadLink gate keeps that first worker live long
7997        /// enough to observe the number of started entry tasks deterministically.
7998        #[tokio::test]
7999        async fn update_only_spawning_stops_at_open_file_capacity() -> Result<(), anyhow::Error> {
8000            let tmp_dir = testutils::create_temp_dir().await?;
8001            let src = tmp_dir.join("src");
8002            let update = tmp_dir.join("update");
8003            let dst = tmp_dir.join("dst");
8004            tokio::fs::create_dir(&src).await?;
8005            tokio::fs::create_dir(&update).await?;
8006            let n = 8;
8007            for i in 0..n {
8008                tokio::fs::symlink(format!("target-{i}"), update.join(format!("u{i}"))).await?;
8009            }
8010            let progress: &'static progress::Progress =
8011                Box::leak(Box::new(progress::Progress::new()));
8012            let admission = testutils::AdmissionLimit::new().await;
8013            admission.set_files_in_flight(1);
8014            let readlink_resource =
8015                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::ReadLink);
8016            admission.set_max_ops_in_flight(readlink_resource, 1);
8017            let held_readlink = throttle::ops_in_flight_permit(readlink_resource).await;
8018            let mut task = tokio::spawn(async move {
8019                link(
8020                    progress,
8021                    &tmp_dir,
8022                    &src,
8023                    &dst,
8024                    &Some(update),
8025                    &common_settings(false, false),
8026                    false,
8027                )
8028                .await
8029            });
8030            let first_worker = tokio::time::timeout(std::time::Duration::from_secs(20), async {
8031                loop {
8032                    if progress.ops.get().started >= 2 {
8033                        break;
8034                    }
8035                    tokio::task::yield_now().await;
8036                }
8037            })
8038            .await;
8039            if let Err(error) = first_worker {
8040                drop(held_readlink);
8041                admission.quiesce(&mut task).await;
8042                return Err(error).context("the first update-only worker did not start");
8043            }
8044            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
8045            let started_while_blocked = progress.ops.get().started;
8046            drop(held_readlink);
8047            let task_result = admission
8048                .run_with_timeout(std::time::Duration::from_secs(20), &mut task)
8049                .await
8050                .context("update-only copies did not resume after ReadLink was released")?;
8051            let summary = task_result?.map_err(|error| error.source)?;
8052            assert_eq!(
8053                started_while_blocked, 2,
8054                "root plus exactly one admitted update-only worker should be live"
8055            );
8056            assert_eq!(summary.copy_summary.symlinks_created, n);
8057            Ok(())
8058        }
8059
8060        /// Regression: the update-only entries loop must transfer open-file admission into
8061        /// copy_child without deadlocking against copy's own classification or rm's pending-meta.
8062        ///
8063        /// Scenario: update has many regular files that don't exist in src.
8064        /// The loop at site 3 spawns a copy::copy task per entry under a
8065        /// saturated files-in-flight pool. Each outer iteration transfers its guard into copy_child, so
8066        /// delegated classification does not reacquire while the caller retains capacity.
8067        #[tokio::test]
8068        #[traced_test]
8069        async fn update_only_entries_bounded_no_deadlock() -> Result<(), anyhow::Error> {
8070            let tmp_dir = testutils::create_temp_dir().await?;
8071            let src = tmp_dir.join("src");
8072            let update = tmp_dir.join("update");
8073            let dst = tmp_dir.join("dst");
8074            tokio::fs::create_dir(&src).await?;
8075            tokio::fs::create_dir(&update).await?;
8076            // src is empty; update has many regular files. Every update entry
8077            // is "missing in src" -> hits the site-3 spawn loop.
8078            let n = 50;
8079            for i in 0..n {
8080                tokio::fs::write(update.join(format!("u{}", i)), format!("upd-{}", i)).await?;
8081            }
8082            let admission = testutils::AdmissionLimit::new().await;
8083            admission.set_files_in_flight(2);
8084            let summary = admission
8085                .run_with_timeout(
8086                    std::time::Duration::from_secs(30),
8087                    link(
8088                        &PROGRESS,
8089                        tmp_dir.as_path(),
8090                        &src,
8091                        &dst,
8092                        &Some(update.clone()),
8093                        &common_settings(false, false),
8094                        false,
8095                    ),
8096                )
8097                .await
8098                .context("link timed out — site-3 spawn loop deadlock")?
8099                .context("link failed")?;
8100            // dst gets the src directory plus a copy of every update file
8101            assert_eq!(summary.copy_summary.directories_created, 1);
8102            assert_eq!(summary.copy_summary.files_copied, n);
8103            for i in 0..n {
8104                let content = tokio::fs::read_to_string(dst.join(format!("u{}", i))).await?;
8105                assert_eq!(content, format!("upd-{}", i));
8106            }
8107            Ok(())
8108        }
8109
8110        /// Regression for update-only copy ↔ rm cross-pool self-deadlock.
8111        ///
8112        /// Scenario: update has many entries not in src; dst already has
8113        /// directories at those same names; the user passes --overwrite. Each
8114        /// update-only task delegates through `copy_child` / `copy_file_fd`, whose
8115        /// `remove_existing` invokes `rm_child` to remove the preexisting destination directory.
8116        /// rm draws from PendingMeta. If the outer task also held PendingMeta across delegated copy,
8117        /// every running task would hold a permit while waiting on inner rm to acquire one — a
8118        /// self-deadlock once the pool is saturated.
8119        #[tokio::test]
8120        #[traced_test]
8121        async fn update_only_overwrite_preexisting_dirs_no_deadlock() -> Result<(), anyhow::Error> {
8122            let tmp_dir = testutils::create_temp_dir().await?;
8123            let src = tmp_dir.join("src");
8124            let update = tmp_dir.join("update");
8125            let dst = tmp_dir.join("dst");
8126            tokio::fs::create_dir(&src).await?;
8127            tokio::fs::create_dir(&update).await?;
8128            tokio::fs::create_dir(&dst).await?;
8129            let n = 12;
8130            for i in 0..n {
8131                // update/uN is a regular file (site 3 will copy it).
8132                tokio::fs::write(update.join(format!("u{}", i)), format!("upd-{}", i)).await?;
8133                // dst/uN is a preexisting directory with inner files. With
8134                // --overwrite, `remove_existing` invokes `rm_child` to wipe it, which recurses under
8135                // PendingMeta admission
8136                let dst_subdir = dst.join(format!("u{}", i));
8137                tokio::fs::create_dir(&dst_subdir).await?;
8138                for j in 0..3 {
8139                    tokio::fs::write(
8140                        dst_subdir.join(format!("inner_{}.txt", j)),
8141                        format!("old-{}-{}", i, j),
8142                    )
8143                    .await?;
8144                }
8145            }
8146            // saturate both pools to force the deadlock if the cycle existed.
8147            let admission = testutils::AdmissionLimit::new().await;
8148            admission.set_files_in_flight(2);
8149            let summary = admission
8150                .run_with_timeout(
8151                    std::time::Duration::from_secs(30),
8152                    link(
8153                        &PROGRESS,
8154                        tmp_dir.as_path(),
8155                        &src,
8156                        &dst,
8157                        &Some(update.clone()),
8158                        &common_settings(false, true), // overwrite=true
8159                        false,
8160                    ),
8161                )
8162                .await
8163                .context("link timed out — pending-meta self-deadlock between site 3 and inner rm")?
8164                .context("link failed")?;
8165            // each preexisting dst/uN directory gets removed and replaced
8166            // with a regular-file copy from update/uN.
8167            assert_eq!(summary.copy_summary.files_copied, n);
8168            assert_eq!(summary.copy_summary.rm_summary.files_removed, n * 3);
8169            assert_eq!(summary.copy_summary.rm_summary.directories_removed, n);
8170            // verify content came from update
8171            for i in 0..n {
8172                let content = tokio::fs::read_to_string(dst.join(format!("u{}", i))).await?;
8173                assert_eq!(content, format!("upd-{}", i));
8174            }
8175            Ok(())
8176        }
8177    }
8178
8179    /// TOCTOU hardening: a source entry being hard-linked is concurrently swapped between a real
8180    /// regular file and a symlink to a sentinel OUTSIDE the source tree. rlink classifies the entry
8181    /// via `child` (fstat) before acting and links the pinned inode inode-exactly
8182    /// (`hard_link_handle_at`), so a swap is either caught (the entry is linked/copied as a symlink,
8183    /// or the op fails closed) or the real file is hard-linked. The sentinel's secret content must
8184    /// NEVER appear at the destination as a regular file, and the sentinel inode must never gain a
8185    /// new hard link.
8186    mod race_tests {
8187        use super::*;
8188
8189        // Repeatedly swap `dir/entry_name` between a real regular file (content `REAL_CONTENT`) and
8190        // a symlink pointing at `sentinel`, using rename so each individual state is atomic. Runs on
8191        // a dedicated OS thread so it makes progress regardless of the tokio runtime's scheduling.
8192        fn spawn_file_symlink_swapper(
8193            dir: std::path::PathBuf,
8194            entry_name: &'static str,
8195            sentinel: std::path::PathBuf,
8196            stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
8197        ) -> std::thread::JoinHandle<()> {
8198            std::thread::spawn(move || {
8199                let entry = dir.join(entry_name);
8200                let staged_real = dir.join("__staged_real");
8201                let staged_link = dir.join("__staged_link");
8202                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
8203                    let _ = std::fs::remove_file(&staged_real);
8204                    if std::fs::write(&staged_real, b"REAL_CONTENT").is_err() {
8205                        continue;
8206                    }
8207                    let _ = std::fs::rename(&staged_real, &entry);
8208                    let _ = std::fs::remove_file(&staged_link);
8209                    let _ = std::os::unix::fs::symlink(&sentinel, &staged_link);
8210                    let _ = std::fs::rename(&staged_link, &entry);
8211                }
8212            })
8213        }
8214
8215        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8216        #[traced_test]
8217        async fn hard_link_entry_swap_never_leaks_sentinel() -> Result<(), anyhow::Error> {
8218            let tmp_dir = testutils::create_temp_dir().await?;
8219            let test_path = tmp_dir.as_path();
8220            // sentinel lives OUTSIDE the source tree with distinctive content; we also track its
8221            // hard-link count to prove `linkat(flags=0)` never gives it a new hard link.
8222            let sentinel = test_path.join("sentinel_secret");
8223            tokio::fs::write(&sentinel, "SENTINEL_SECRET_CONTENT").await?;
8224            let sentinel_links_before = {
8225                use std::os::unix::fs::MetadataExt;
8226                tokio::fs::symlink_metadata(&sentinel).await?.nlink()
8227            };
8228            let src = test_path.join("src");
8229            let sub = src.join("sub");
8230            tokio::fs::create_dir(&src).await?;
8231            tokio::fs::create_dir(&sub).await?;
8232            tokio::fs::write(sub.join("entry"), "REAL_CONTENT").await?;
8233
8234            let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
8235            let swapper =
8236                spawn_file_symlink_swapper(sub.clone(), "entry", sentinel.clone(), stop.clone());
8237
8238            // overwrite=true so each iteration's destination need not be empty; no update tree, so
8239            // `src/sub/entry` takes the hard-link path (or copy-as-symlink when caught mid-swap).
8240            let settings = common_settings(false, true);
8241            let mut caught_swaps = 0usize;
8242            let mut linked_real = 0usize;
8243            for i in 0..200 {
8244                let dst = test_path.join(format!("dst_{i}"));
8245                let result = tokio::time::timeout(
8246                    std::time::Duration::from_secs(30),
8247                    link(&PROGRESS, test_path, &src, &dst, &None, &settings, false),
8248                )
8249                .await
8250                .expect("link must not hang under concurrent swapping");
8251                match result {
8252                    Ok(_) => {}
8253                    Err(_) => caught_swaps += 1, // a swap was caught mid-link (failed closed)
8254                }
8255                // CORE ASSERTION: if a regular file landed at the destination it holds the REAL
8256                // content — never the sentinel's secret. The entry may instead be a symlink
8257                // (linkat made a hard link to the symlink inode, or copy reproduced the symlink) or
8258                // be absent. A symlink that resolves to the sentinel is fine: it is a link, not a
8259                // copy of the secret bytes, and it did not give the sentinel a new hard link.
8260                let entry_dst = dst.join("sub").join("entry");
8261                if let Ok(md) = tokio::fs::symlink_metadata(&entry_dst).await
8262                    && md.file_type().is_file()
8263                {
8264                    let content = tokio::fs::read_to_string(&entry_dst).await?;
8265                    assert_ne!(
8266                        content, "SENTINEL_SECRET_CONTENT",
8267                        "iteration {i}: sentinel content leaked into the destination as a regular file"
8268                    );
8269                    assert_eq!(
8270                        content, "REAL_CONTENT",
8271                        "iteration {i}: a regular destination file must hold the real content"
8272                    );
8273                    linked_real += 1;
8274                }
8275                let _ = tokio::fs::remove_dir_all(&dst).await;
8276            }
8277
8278            stop.store(true, std::sync::atomic::Ordering::Relaxed);
8279            swapper.join().expect("swapper thread panicked");
8280
8281            // the sentinel must never have gained a hard link from a `linkat` that followed the
8282            // swapped-in symlink (flags=0 links the symlink inode itself, not its target).
8283            let sentinel_links_after = {
8284                use std::os::unix::fs::MetadataExt;
8285                tokio::fs::symlink_metadata(&sentinel).await?.nlink()
8286            };
8287            assert_eq!(
8288                sentinel_links_after, sentinel_links_before,
8289                "the sentinel file must never gain a hard link (linkat must not follow the symlink)"
8290            );
8291            // sanity: the run did observable work (this is not the safety assertion — the safety
8292            // assertions above hold on every iteration regardless of timing).
8293            tracing::info!(
8294                "link file/symlink swap: caught_swaps={caught_swaps}, linked_real={linked_real}"
8295            );
8296            assert!(
8297                caught_swaps + linked_real > 0,
8298                "expected at least one observable outcome across 200 iterations"
8299            );
8300            Ok(())
8301        }
8302    }
8303}