Skip to main content

common/
delete.rs

1//! rsync-style `--delete` (mirror) support: remove destination entries that
2//! have no counterpart in the source directory.
3
4use std::ffi::OsString;
5use std::sync::Arc;
6
7use anyhow::Context;
8
9use crate::progress;
10use crate::safedir::Dir;
11
12/// Settings controlling rsync-style `--delete` (mirror) behavior.
13///
14/// Present (`Some`) only when `--delete` was requested. `None` means the
15/// destination is never enumerated and no pruning work is done, so the default
16/// copy path pays nothing for this feature.
17#[derive(Debug, Clone)]
18pub struct DeleteSettings {
19    /// Also remove destination entries that match an exclude pattern
20    /// (rsync `--delete-excluded`). When false, excluded entries are protected.
21    pub delete_excluded: bool,
22}
23
24/// Complete exact child-name evidence, sealed with the settings that consume it.
25///
26/// Rlink captures settings when collection starts; copy binds its own settings at completion.
27/// The storage can be ordered names from copy or a hashed set from rlink; pruning requires the
28/// hashed form. Once sealed, the private fields keep those settings and names together.
29#[derive(Debug)]
30pub(crate) struct DeleteKeepSet<N> {
31    settings: DeleteSettings,
32    names: N,
33}
34
35impl<N> DeleteKeepSet<N> {
36    /// Seal a completed, exact collection. Call only at a successful traversal boundary.
37    fn from_complete(settings: DeleteSettings, names: N) -> Self {
38        Self { settings, names }
39    }
40}
41
42impl<'a> DeleteKeepSet<&'a [OsString]> {
43    /// Borrow evidence that only a successful delete-collecting walk can produce. Ordinary
44    /// collected names and successful non-collecting walks cannot authorize pruning.
45    fn from_processed(
46        settings: &DeleteSettings,
47        processed: &'a crate::walk_driver::ProcessedChildren,
48    ) -> Option<Self> {
49        processed
50            .delete_names()
51            .map(|names| Self::from_complete(settings.clone(), names))
52    }
53    /// Hash borrowed names only once a destination exists to prune.
54    pub(crate) fn hashed(&self) -> DeleteKeepSet<std::collections::HashSet<&'a std::ffi::OsStr>> {
55        DeleteKeepSet::from_complete(
56            self.settings.clone(),
57            self.names.iter().map(OsString::as_os_str).collect(),
58        )
59    }
60}
61
62/// One completion decision owns both prune authorization and the discarded-evidence warning.
63pub(crate) enum DeleteDecision<N> {
64    NotRequested,
65    Discarded,
66    Ready(DeleteKeepSet<N>),
67}
68
69impl<N> DeleteDecision<N> {
70    pub(crate) fn into_ready(self, dst_path: &std::path::Path) -> Option<DeleteKeepSet<N>> {
71        match self {
72            Self::NotRequested => None,
73            Self::Discarded => {
74                tracing::warn!(
75                    "skipping --delete pruning of {:?} because entry processing failed or did not provide complete exact names",
76                    dst_path
77                );
78                None
79            }
80            Self::Ready(keep) => Some(keep),
81        }
82    }
83}
84
85impl<'a> DeleteDecision<&'a [OsString]> {
86    /// Only a successful exact collection can authorize pruning. An exact empty collection is
87    /// valid evidence; failed traversal, ordinary names, and omitted collection are not.
88    pub(crate) fn from_processed(
89        settings: &DeleteSettings,
90        processed: Option<&'a crate::walk_driver::ProcessedChildren>,
91    ) -> Self {
92        match processed.and_then(|processed| DeleteKeepSet::from_processed(settings, processed)) {
93            Some(keep) => Self::Ready(keep),
94            None => Self::Discarded,
95        }
96    }
97}
98
99/// Outcomes of rlink's source/update pass: errors always, and exact names when deletion is enabled.
100///
101/// This is the directory's keep-going error sink even without `--delete`. After all workers have
102/// been joined, completion returns both the deletion decision and the errors needed by finalization.
103pub(crate) struct LinkChildOutcomes {
104    errors: crate::error_collector::ErrorCollector,
105    inner: Option<(DeleteSettings, std::collections::HashSet<OsString>)>,
106}
107
108impl LinkChildOutcomes {
109    pub(crate) fn new(settings: Option<&DeleteSettings>) -> Self {
110        Self {
111            inner: settings.map(|settings| (settings.clone(), std::collections::HashSet::new())),
112            errors: crate::error_collector::ErrorCollector::default(),
113        }
114    }
115    pub(crate) fn record_exact(&mut self, name: OsString) {
116        if let Some((_, names)) = &mut self.inner {
117            names.insert(name);
118        }
119    }
120    /// Record traversal and worker errors even when deletion was not requested.
121    pub(crate) fn record_error(&self, error: anyhow::Error) {
122        self.errors.push(error);
123    }
124    /// Consume the directory's names and their own errors after every source/update worker has
125    /// been joined. The returned errors remain available for keep-going finalization.
126    pub(crate) fn finish(
127        self,
128    ) -> (
129        DeleteDecision<std::collections::HashSet<OsString>>,
130        crate::error_collector::ErrorCollector,
131    ) {
132        let decision = match self.inner {
133            None => DeleteDecision::NotRequested,
134            Some(_) if self.errors.has_errors() => DeleteDecision::Discarded,
135            Some((settings, names)) => {
136                DeleteDecision::Ready(DeleteKeepSet::from_complete(settings, names))
137            }
138        };
139        (decision, self.errors)
140    }
141    #[cfg(test)]
142    pub(crate) fn expect_ready(self) -> DeleteKeepSet<std::collections::HashSet<OsString>> {
143        let (decision, errors) = self.finish();
144        if let Some(error) = errors.into_error() {
145            panic!("expected successful child outcomes: {error:#}");
146        }
147        match decision {
148            DeleteDecision::Ready(keep) => keep,
149            DeleteDecision::NotRequested | DeleteDecision::Discarded => {
150                panic!("expected completed delete-name collection")
151            }
152        }
153    }
154    #[cfg(test)]
155    pub(crate) fn as_set(&self) -> Option<&std::collections::HashSet<OsString>> {
156        self.inner.as_ref().map(|(_, names)| names)
157    }
158}
159
160/// Remove entries in the already-open destination directory `dst_dir` whose names are not in
161/// `keep` (the source entry names that passed the filter for this directory).
162///
163/// The destination is enumerated and pruned entirely through `dst_dir`'s pinned file descriptor:
164/// entries come from `dst_dir.read_entries()` and each extraneous entry is removed via
165/// `rm::rm_child` (fd-relative, `O_NOFOLLOW` descent). The destination path is never
166/// re-resolved, so a privileged prune cannot be redirected by a concurrent symlink swap into
167/// deleting a tree outside the destination — the classic mirror-delete symlink race fails closed.
168/// The caller is responsible for opening `dst_dir` `O_NOFOLLOW`: in a real copy it is the held
169/// destination directory; in `--dry-run` (where the create-or-overwrite step is skipped and the
170/// path could still be a symlink-to-directory) the caller opens it `O_NOFOLLOW|O_DIRECTORY`, which
171/// fails closed on a symlink or non-directory before prune is ever invoked.
172///
173/// `relative_dir` is this directory's path relative to the source root, used to match destination
174/// entries against `filter` for exclude-protection. Excluded destination entries are protected
175/// (kept) unless the keep-set's `delete_excluded` setting is set. Honors `dry_run` (reports without
176/// removing, via `rm::rm_child`).
177async fn prune_extraneous<K>(
178    prog_track: &'static progress::Progress,
179    dst_dir: &Arc<Dir>,
180    relative_dir: &std::path::Path,
181    keep: &DeleteKeepSet<std::collections::HashSet<K>>,
182    filter: Option<&crate::filter::FilterSettings>,
183    fail_early: bool,
184    dry_run: Option<crate::config::DryRunMode>,
185) -> Result<crate::rm::Summary, crate::rm::Error>
186where
187    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
188{
189    let DeleteKeepSet {
190        settings: delete_settings,
191        names: keep,
192    } = keep;
193    let summary = crate::rm::Summary::default();
194    // enumerate the destination through its pinned fd (no path re-resolution). `d_type` remains a
195    // scheduling hint only: exclude protection classifies under admission and transfers that exact
196    // handle into rm, while unfiltered removal lets the shared driver classify at dispatch.
197    let entries = dst_dir
198        .read_entries()
199        .await
200        .with_context(|| "failed scanning destination directory for deletion".to_string())
201        .map_err(|err| crate::rm::Error::new(err, summary))?;
202    prune_entries(
203        prog_track,
204        dst_dir,
205        relative_dir,
206        keep,
207        filter,
208        delete_settings,
209        fail_early,
210        dry_run,
211        entries,
212    )
213    .await
214}
215
216/// Select the held real or preview directory, reporting the shared no-directory skip policy.
217pub(crate) fn select_scan_dir<'a>(
218    dst_dir: Option<&'a Arc<Dir>>,
219    preview_dir: Option<&'a Arc<Dir>>,
220    dst_path: &std::path::Path,
221) -> Option<&'a Arc<Dir>> {
222    let scan_dir = dst_dir.or(preview_dir);
223    if scan_dir.is_none() {
224        tracing::debug!(
225            "skipping --delete pruning of {:?}: no destination directory to scan",
226            dst_path
227        );
228    }
229    scan_dir
230}
231
232/// Prune through a held destination and fold successful or partial removal counts exactly once.
233/// The caller retains its fail-early/finalization policy; the original error chain is returned.
234#[allow(clippy::too_many_arguments)]
235pub(crate) async fn prune_and_fold<K>(
236    prog_track: &'static progress::Progress,
237    dst_dir: &Arc<Dir>,
238    relative_dir: &std::path::Path,
239    keep: &DeleteKeepSet<std::collections::HashSet<K>>,
240    filter: Option<&crate::filter::FilterSettings>,
241    fail_early: bool,
242    dry_run: Option<crate::config::DryRunMode>,
243    summary: &mut crate::rm::Summary,
244) -> Result<(), anyhow::Error>
245where
246    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
247{
248    match prune_extraneous(
249        prog_track,
250        dst_dir,
251        relative_dir,
252        keep,
253        filter,
254        fail_early,
255        dry_run,
256    )
257    .await
258    {
259        Ok(removed) => {
260            *summary = *summary + removed;
261            Ok(())
262        }
263        Err(error) => {
264            *summary = *summary + error.summary;
265            Err(error.source)
266        }
267    }
268}
269
270/// Apply prune decisions to an already-enumerated destination directory.
271///
272/// Production callers arrive through [`prune_extraneous`]. Separating enumeration lets tests
273/// inject stale and `DT_UNKNOWN` hints deterministically without requiring an NFS/FUSE fixture.
274#[allow(clippy::too_many_arguments)]
275async fn prune_entries<K>(
276    prog_track: &'static progress::Progress,
277    dst_dir: &Arc<Dir>,
278    relative_dir: &std::path::Path,
279    keep: &std::collections::HashSet<K>,
280    filter: Option<&crate::filter::FilterSettings>,
281    delete_settings: &DeleteSettings,
282    fail_early: bool,
283    dry_run: Option<crate::config::DryRunMode>,
284    entries: Vec<(OsString, Option<crate::walk::EntryKind>)>,
285) -> Result<crate::rm::Summary, crate::rm::Error>
286where
287    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
288{
289    let mut summary = crate::rm::Summary::default();
290    let errors = crate::error_collector::ErrorCollector::default();
291    for (name, hint) in entries {
292        let result: Result<crate::rm::Summary, crate::rm::Error> = async {
293            if keep.contains(name.as_os_str()) {
294                return Ok(Default::default());
295            }
296            // the entry's path relative to the destination (mirror) root: anchors filter matching
297            // and reconstructs the display path inside `rm_child`. Computed once and reused below.
298            let rel = relative_dir.join(&name);
299            let protect_excluded = !delete_settings.delete_excluded && filter.is_some();
300            let mut admitted_entry = None;
301            // an exclude-protection decision authorizes deletion, so `d_type` is never authoritative
302            // here. Classify once under admission and transfer this exact handle into rm; otherwise a
303            // stale File hint for a real directory could bypass a dir-only exclude such as `cache/`.
304            let is_dir = if protect_excluded {
305                let admission = crate::walk::ensure_entry_admission(
306                    crate::walk::PermitKind::PendingMeta,
307                    crate::walk::EntryAdmission::RootOrDelegated,
308                )
309                .await;
310                let entry =
311                    crate::walk::classify_admitted_entry(dst_dir, &name, admission.into_permit())
312                        .await
313                        .with_context(|| format!("failed reading metadata from {rel:?}"))
314                        .map_err(|error| crate::rm::Error::new(error, Default::default()))?;
315                let is_dir = entry.kind() == crate::walk::EntryKind::Dir;
316                admitted_entry = Some(entry);
317                is_dir
318            } else {
319                false
320            };
321            // exclude-protection: keep destination entries the filter would exclude,
322            // unless --delete-excluded was requested.
323            if !delete_settings.delete_excluded
324                && let Some(filter) = filter
325                && !matches!(
326                    filter.should_include(&rel, is_dir),
327                    crate::filter::FilterResult::Included
328                )
329            {
330                tracing::debug!("protecting excluded destination entry {:?}", rel);
331                return Ok(Default::default());
332            }
333            // Protect excluded descendants when removing an extraneous directory: rm::rm_child
334            // applies the filter recursively (skipping excluded entries), so an extra dir containing
335            // e.g. `*.log` files keeps them and survives non-empty — upholding the documented
336            // "excluded files are protected by default" guarantee (and matching rsync). With
337            // --delete-excluded we pass no filter so the whole subtree is removed. The filter is
338            // anchored at the destination (mirror) root, so the entry's destination-root-relative
339            // path `relative_dir.join(name)` matches path/anchored patterns like `cache/*.log`
340            // correctly.
341            let rm_settings = crate::rm::Settings {
342                fail_early,
343                filter: if delete_settings.delete_excluded {
344                    None
345                } else {
346                    filter.cloned()
347                },
348                time_filter: None,
349                dry_run,
350            };
351            match admitted_entry {
352                Some(entry) => {
353                    crate::rm::rm_child_admitted_entry(
354                        prog_track,
355                        dst_dir,
356                        &name,
357                        &rel,
358                        &rm_settings,
359                        entry,
360                    )
361                    .await
362                }
363                None => {
364                    let admission = crate::walk::ensure_entry_admission(
365                        crate::walk::PermitKind::PendingMeta,
366                        crate::walk::EntryAdmission::from_hint(hint),
367                    )
368                    .await;
369                    crate::rm::rm_child_admitted(
370                        prog_track,
371                        dst_dir,
372                        &name,
373                        &rel,
374                        &rm_settings,
375                        admission,
376                    )
377                    .await
378                }
379            }
380        }
381        .await;
382        match result {
383            Ok(rm_summary) => {
384                summary = summary + rm_summary;
385            }
386            Err(err) => {
387                summary = summary + err.summary;
388                if fail_early {
389                    return Err(crate::rm::Error::new(err.source, summary));
390                }
391                errors.push(err.source);
392            }
393        }
394    }
395    if let Some(err) = errors.into_error() {
396        return Err(crate::rm::Error::new(err, summary));
397    }
398    Ok(summary)
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use std::collections::HashSet;
405    use tracing_test::traced_test;
406
407    static PROGRESS: std::sync::LazyLock<progress::Progress> =
408        std::sync::LazyLock::new(progress::Progress::new);
409
410    fn delete_settings(delete_excluded: bool) -> DeleteSettings {
411        DeleteSettings { delete_excluded }
412    }
413
414    #[test]
415    fn failed_collection_cannot_authorize_pruning() {
416        let settings = delete_settings(true);
417        let mut collecting = LinkChildOutcomes::new(Some(&settings));
418        collecting.record_exact(OsString::from("completed-child"));
419        collecting.record_error(anyhow::anyhow!("a later child failed"));
420        let (decision, errors) = collecting.finish();
421        assert!(matches!(decision, DeleteDecision::Discarded));
422        assert!(
423            errors.has_errors(),
424            "finalization must retain the traversal error"
425        );
426    }
427
428    #[test]
429    fn completed_collection_keeps_its_settings_and_empty_is_valid() {
430        for delete_excluded in [false, true] {
431            let settings = delete_settings(delete_excluded);
432            let (decision, errors) = LinkChildOutcomes::new(Some(&settings)).finish();
433            let DeleteDecision::Ready(keep) = decision else {
434                panic!("completed empty collection must authorize pruning")
435            };
436            assert!(!errors.has_errors());
437            assert!(keep.names.is_empty());
438            assert_eq!(keep.settings.delete_excluded, delete_excluded);
439        }
440        let mut collecting = LinkChildOutcomes::new(None);
441        collecting.record_exact(OsString::from("ignored"));
442        let (decision, errors) = collecting.finish();
443        assert!(matches!(decision, DeleteDecision::NotRequested));
444        assert!(!errors.has_errors());
445    }
446
447    #[test]
448    fn collection_preserves_errors_without_delete() {
449        let mut collecting = LinkChildOutcomes::new(None);
450        collecting.record_exact(OsString::from("unretained"));
451        collecting.record_error(
452            anyhow::Error::from(std::io::Error::from_raw_os_error(libc::EACCES))
453                .context("source enumeration failed"),
454        );
455        let (decision, errors) = collecting.finish();
456        assert!(matches!(decision, DeleteDecision::NotRequested));
457        let error = errors
458            .into_error()
459            .expect("non-delete failures must survive completion");
460        assert_eq!(
461            error
462                .downcast_ref::<std::io::Error>()
463                .unwrap()
464                .raw_os_error(),
465            Some(libc::EACCES)
466        );
467        assert!(format!("{error:#}").contains("source enumeration failed"));
468    }
469
470    #[tokio::test]
471    async fn prune_completion_folds_success_and_partial_counts_once() -> anyhow::Result<()> {
472        use std::os::unix::fs::PermissionsExt;
473        for (block_parent_removal, fail_early) in [(false, false), (true, false), (true, true)] {
474            if block_parent_removal && nix::unistd::geteuid().is_root() {
475                eprintln!("skipping permission-denial case: root bypasses directory permissions");
476                continue;
477            }
478            let tmp = tempfile::tempdir()?;
479            let dst = tmp.path().join("dst");
480            for child in ["extra1", "extra2"] {
481                tokio::fs::create_dir_all(dst.join(child)).await?;
482                tokio::fs::write(dst.join(child).join("file"), b"abc").await?;
483            }
484            let dir = open_dst(&dst).await?;
485            if block_parent_removal {
486                tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o500)).await?;
487            }
488            let keep =
489                DeleteKeepSet::from_complete(delete_settings(false), HashSet::<OsString>::new());
490            let mut summary = crate::rm::Summary {
491                files_removed: 7,
492                bytes_removed: 11,
493                directories_removed: 2,
494                ..Default::default()
495            };
496            let result = prune_and_fold(
497                &PROGRESS,
498                &dir,
499                std::path::Path::new(""),
500                &keep,
501                None,
502                fail_early,
503                None,
504                &mut summary,
505            )
506            .await;
507            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
508            let removed = if block_parent_removal && fail_early {
509                1
510            } else {
511                2
512            };
513            assert_eq!(summary.files_removed, 7 + removed);
514            assert_eq!(summary.bytes_removed, 11 + 3 * removed as u64);
515            assert_eq!(
516                ["extra1", "extra2"]
517                    .iter()
518                    .filter(|child| dst.join(child).join("file").exists())
519                    .count(),
520                2 - removed,
521            );
522            if block_parent_removal {
523                let error = result.expect_err("parent permissions must prevent the final rmdir");
524                assert_eq!(
525                    error
526                        .downcast_ref::<std::io::Error>()
527                        .unwrap()
528                        .raw_os_error(),
529                    Some(libc::EACCES),
530                );
531                assert_eq!(summary.directories_removed, 2);
532                assert!(dst.join("extra1").is_dir());
533                assert!(dst.join("extra2").is_dir());
534            } else {
535                result?;
536                assert_eq!(summary.directories_removed, 4);
537                assert!(!dst.join("extra1").exists());
538                assert!(!dst.join("extra2").exists());
539            }
540        }
541        Ok(())
542    }
543
544    /// Open `dst` as the destination directory `Dir` prune operates through, mirroring the copy/link
545    /// call sites (`O_NOFOLLOW|O_DIRECTORY`, Destination side).
546    async fn open_dst(dst: &std::path::Path) -> anyhow::Result<Arc<Dir>> {
547        Ok(Arc::new(
548            Dir::open_root_dir(dst, false, congestion::Side::Destination).await?,
549        ))
550    }
551
552    mod max_files_in_flight_tests {
553        use super::*;
554
555        /// Delete protection must classify the entry it will remove rather than trust `d_type`.
556        #[tokio::test]
557        async fn stale_file_hint_cannot_bypass_dir_only_exclude() -> anyhow::Result<()> {
558            let tmp = tempfile::tempdir()?;
559            let dst = tmp.path().join("dst");
560            tokio::fs::create_dir_all(dst.join("cache")).await?;
561            tokio::fs::write(dst.join("cache").join("child"), b"protected").await?;
562            let admission = crate::testutils::AdmissionLimit::new().await;
563            admission.set_files_in_flight(1);
564            let dst_dir = open_dst(&dst).await?;
565            let mut filter = crate::filter::FilterSettings::new();
566            filter.add_exclude("cache/")?;
567            let result = admission
568                .run_with_timeout(
569                    std::time::Duration::from_secs(20),
570                    prune_entries(
571                        &PROGRESS,
572                        &dst_dir,
573                        std::path::Path::new(""),
574                        &HashSet::<OsString>::new(),
575                        Some(&filter),
576                        &delete_settings(false),
577                        false,
578                        None,
579                        vec![(
580                            std::ffi::OsString::from("cache"),
581                            Some(crate::walk::EntryKind::File),
582                        )],
583                    ),
584                )
585                .await
586                .context("stale-hint delete protection did not terminate")?
587                .map_err(|error| error.source)?;
588            assert_eq!(result.files_removed, 0);
589            assert_eq!(result.directories_removed, 0);
590            assert!(dst.join("cache").join("child").exists());
591            Ok(())
592        }
593
594        /// A destructive filter admits classification even when `d_type` reports a file.
595        #[tokio::test]
596        async fn filtered_hinted_file_waits_before_authoritative_decision() -> anyhow::Result<()> {
597            let tmp = tempfile::tempdir()?;
598            let dst = tmp.path().join("dst");
599            tokio::fs::create_dir(&dst).await?;
600            tokio::fs::write(dst.join("protected"), b"x").await?;
601            let admission = crate::testutils::AdmissionLimit::new().await;
602            admission.set_files_in_flight(1);
603            let dst_dir = open_dst(&dst).await?;
604            let stat_resource =
605                throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Stat);
606            admission.set_max_ops_in_flight(stat_resource, 1);
607            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
608            let mut filter = crate::filter::FilterSettings::new();
609            filter.add_exclude("protected")?;
610            let keep: HashSet<OsString> = HashSet::new();
611            let settings = delete_settings(false);
612            let prune = prune_entries(
613                &PROGRESS,
614                &dst_dir,
615                std::path::Path::new(""),
616                &keep,
617                Some(&filter),
618                &settings,
619                false,
620                None,
621                vec![(
622                    std::ffi::OsString::from("protected"),
623                    Some(crate::walk::EntryKind::File),
624                )],
625            );
626            tokio::pin!(prune);
627            let stopped_at_stat_gate = futures::poll!(prune.as_mut()).is_pending();
628            let mut second_permit = Box::pin(throttle::pending_meta_permit());
629            let classification_owned_admission =
630                futures::poll!(second_permit.as_mut()).is_pending();
631            drop(second_permit);
632            drop(held_stat);
633            let result = admission
634                .run_with_timeout(std::time::Duration::from_secs(20), prune.as_mut())
635                .await
636                .context("filtered hinted delete did not resume after stat release")?;
637            let summary = result.map_err(|error| error.source)?;
638            assert!(
639                stopped_at_stat_gate,
640                "delete protection did not reach the held destination Stat gate"
641            );
642            assert!(
643                classification_owned_admission,
644                "delete protection reached classification without owning admission"
645            );
646            assert_eq!(summary.files_removed, 0);
647            assert!(dst.join("protected").exists());
648            Ok(())
649        }
650
651        /// A `DT_UNKNOWN` prune entry must reserve metadata capacity before the fd-based filter
652        /// classification. If the filter protects it, `rm_child` is never reached and cannot repair
653        /// admission after the fact.
654        #[tokio::test]
655        async fn filtered_unknown_entry_waits_before_probe() -> anyhow::Result<()> {
656            let tmp = tempfile::tempdir()?;
657            let dst = tmp.path().join("dst");
658            tokio::fs::create_dir(&dst).await?;
659            tokio::fs::write(dst.join("protected"), b"x").await?;
660            let admission = crate::testutils::AdmissionLimit::new().await;
661            let dst_dir = open_dst(&dst).await?;
662            let mut filter = crate::filter::FilterSettings::new();
663            filter.add_exclude("protected")?;
664            let keep: HashSet<OsString> = HashSet::new();
665            let settings = delete_settings(false);
666            admission.set_files_in_flight(1);
667            let stat_resource =
668                throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Stat);
669            admission.set_max_ops_in_flight(stat_resource, 1);
670            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
671            let prune = prune_entries(
672                &PROGRESS,
673                &dst_dir,
674                std::path::Path::new(""),
675                &keep,
676                Some(&filter),
677                &settings,
678                false,
679                None,
680                vec![(std::ffi::OsString::from("protected"), None)],
681            );
682            tokio::pin!(prune);
683            let stopped_at_stat_gate = futures::poll!(prune.as_mut()).is_pending();
684            let mut second_permit = Box::pin(throttle::pending_meta_permit());
685            let probe_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
686            drop(second_permit);
687            drop(held_stat);
688            let result = admission
689                .run_with_timeout(std::time::Duration::from_secs(20), prune.as_mut())
690                .await;
691            assert!(
692                stopped_at_stat_gate,
693                "DT_UNKNOWN prune filter did not reach the held stat gate"
694            );
695            let summary = result
696                .context("prune did not resume after stat capacity was released")?
697                .map_err(|error| error.source)?;
698            assert!(
699                !probe_bypassed_admission,
700                "DT_UNKNOWN prune filter probe bypassed pending-metadata admission"
701            );
702            assert_eq!(summary.files_removed, 0);
703            assert_eq!(summary.directories_removed, 0);
704            assert!(dst.join("protected").exists());
705            Ok(())
706        }
707
708        /// Keep-going records a failed authoritative probe and continues with later siblings.
709        #[tokio::test]
710        async fn failed_authoritative_probe_keeps_going_in_entry_order() -> anyhow::Result<()> {
711            let tmp = tempfile::tempdir()?;
712            let dst = tmp.path().join("dst");
713            tokio::fs::create_dir(&dst).await?;
714            tokio::fs::write(dst.join("before"), b"b").await?;
715            tokio::fs::write(dst.join("kept"), b"k").await?;
716            tokio::fs::write(dst.join("after"), b"a").await?;
717            let admission = crate::testutils::AdmissionLimit::new().await;
718            let dst_dir = open_dst(&dst).await?;
719            let filter = crate::filter::FilterSettings::new();
720            let mut keep = HashSet::new();
721            keep.insert(std::ffi::OsString::from("kept"));
722            let result = admission
723                .run_with_timeout(
724                    std::time::Duration::from_secs(20),
725                    prune_entries(
726                        &PROGRESS,
727                        &dst_dir,
728                        std::path::Path::new(""),
729                        &keep,
730                        Some(&filter),
731                        &delete_settings(false),
732                        false,
733                        None,
734                        vec![
735                            (std::ffi::OsString::from("before"), None),
736                            (std::ffi::OsString::from("vanished"), None),
737                            (std::ffi::OsString::from("kept"), None),
738                            (std::ffi::OsString::from("after"), None),
739                        ],
740                    ),
741                )
742                .await
743                .context("keep-going delete-protection probe did not terminate")?;
744            let error = result.expect_err("a missing authoritative probe target must fail");
745            let rendered = format!("{:#}", error.source);
746            assert!(rendered.contains("failed reading metadata from"));
747            assert!(rendered.contains("vanished"));
748            assert_eq!(error.summary.bytes_removed, 2);
749            assert_eq!(error.summary.files_removed, 2);
750            assert_eq!(error.summary.symlinks_removed, 0);
751            assert_eq!(error.summary.directories_removed, 0);
752            assert_eq!(error.summary.files_skipped, 0);
753            assert_eq!(error.summary.symlinks_skipped, 0);
754            assert_eq!(error.summary.directories_skipped, 0);
755            assert!(!dst.join("before").exists());
756            assert!(!dst.join("vanished").exists());
757            assert!(dst.join("kept").exists());
758            assert!(!dst.join("after").exists());
759            Ok(())
760        }
761
762        /// Fail-early reports completed work and leaves siblings after a failed probe untouched.
763        #[tokio::test]
764        async fn failed_authoritative_probe_stops_early_in_entry_order() -> anyhow::Result<()> {
765            let tmp = tempfile::tempdir()?;
766            let dst = tmp.path().join("dst");
767            tokio::fs::create_dir(&dst).await?;
768            tokio::fs::write(dst.join("before"), b"b").await?;
769            tokio::fs::write(dst.join("kept"), b"k").await?;
770            tokio::fs::write(dst.join("after"), b"a").await?;
771            let admission = crate::testutils::AdmissionLimit::new().await;
772            let dst_dir = open_dst(&dst).await?;
773            let filter = crate::filter::FilterSettings::new();
774            let mut keep = HashSet::new();
775            keep.insert(std::ffi::OsString::from("kept"));
776            let result = admission
777                .run_with_timeout(
778                    std::time::Duration::from_secs(20),
779                    prune_entries(
780                        &PROGRESS,
781                        &dst_dir,
782                        std::path::Path::new(""),
783                        &keep,
784                        Some(&filter),
785                        &delete_settings(false),
786                        true,
787                        None,
788                        vec![
789                            (std::ffi::OsString::from("before"), None),
790                            (std::ffi::OsString::from("vanished"), None),
791                            (std::ffi::OsString::from("kept"), None),
792                            (std::ffi::OsString::from("after"), None),
793                        ],
794                    ),
795                )
796                .await
797                .context("fail-early delete-protection probe did not terminate")?;
798            let error = result.expect_err("a missing authoritative probe target must fail");
799            let rendered = format!("{:#}", error.source);
800            assert!(rendered.contains("failed reading metadata from"));
801            assert!(rendered.contains("vanished"));
802            assert_eq!(error.summary.bytes_removed, 1);
803            assert_eq!(error.summary.files_removed, 1);
804            assert_eq!(error.summary.symlinks_removed, 0);
805            assert_eq!(error.summary.directories_removed, 0);
806            assert_eq!(error.summary.files_skipped, 0);
807            assert_eq!(error.summary.symlinks_skipped, 0);
808            assert_eq!(error.summary.directories_skipped, 0);
809            assert!(!dst.join("before").exists());
810            assert!(!dst.join("vanished").exists());
811            assert!(dst.join("kept").exists());
812            assert!(dst.join("after").exists());
813            Ok(())
814        }
815    }
816
817    #[tokio::test]
818    #[traced_test]
819    async fn removes_entries_not_in_keep_set() -> anyhow::Result<()> {
820        let tmp = tempfile::tempdir()?;
821        let dst = tmp.path().join("dst");
822        tokio::fs::create_dir(&dst).await?;
823        tokio::fs::write(dst.join("keep.txt"), b"x").await?;
824        tokio::fs::write(dst.join("extra.txt"), b"x").await?;
825        tokio::fs::create_dir(dst.join("extra_dir")).await?;
826        tokio::fs::write(dst.join("extra_dir").join("nested.txt"), b"x").await?;
827
828        let mut keep = HashSet::new();
829        keep.insert(std::ffi::OsString::from("keep.txt"));
830
831        let dst_dir = open_dst(&dst).await?;
832        let summary = prune_extraneous(
833            &PROGRESS,
834            &dst_dir,
835            std::path::Path::new(""),
836            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
837            None,
838            false,
839            None,
840        )
841        .await
842        .map_err(|e| e.source)?;
843
844        assert_eq!(summary.files_removed, 2); // extra.txt + extra_dir/nested.txt
845        assert_eq!(summary.directories_removed, 1); // extra_dir
846        assert!(dst.join("keep.txt").exists());
847        assert!(!dst.join("extra.txt").exists());
848        assert!(!dst.join("extra_dir").exists());
849        Ok(())
850    }
851
852    #[tokio::test]
853    #[traced_test]
854    async fn protects_excluded_entries_unless_delete_excluded() -> anyhow::Result<()> {
855        let tmp = tempfile::tempdir()?;
856        let dst = tmp.path().join("dst");
857        tokio::fs::create_dir(&dst).await?;
858        tokio::fs::write(dst.join("data.bin"), b"x").await?; // extra, not excluded
859        tokio::fs::write(dst.join("note.log"), b"x").await?; // extra, excluded by *.log
860
861        let mut filter = crate::filter::FilterSettings::new();
862        filter.add_exclude("*.log")?;
863        let keep: HashSet<OsString> = HashSet::new(); // both are extraneous
864
865        // default: *.log is protected, data.bin is removed
866        let dst_dir = open_dst(&dst).await?;
867        let summary = prune_extraneous(
868            &PROGRESS,
869            &dst_dir,
870            std::path::Path::new(""),
871            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
872            Some(&filter),
873            false,
874            None,
875        )
876        .await
877        .map_err(|e| e.source)?;
878        assert_eq!(summary.files_removed, 1);
879        assert!(!dst.join("data.bin").exists());
880        assert!(
881            dst.join("note.log").exists(),
882            "*.log must be protected by default"
883        );
884
885        // with delete_excluded: note.log is also removed
886        let dst_dir = open_dst(&dst).await?;
887        let summary = prune_extraneous(
888            &PROGRESS,
889            &dst_dir,
890            std::path::Path::new(""),
891            &DeleteKeepSet::from_complete(delete_settings(true), (keep).clone()),
892            Some(&filter),
893            false,
894            None,
895        )
896        .await
897        .map_err(|e| e.source)?;
898        assert_eq!(summary.files_removed, 1);
899        assert!(!dst.join("note.log").exists());
900        Ok(())
901    }
902
903    #[tokio::test]
904    #[traced_test]
905    async fn protects_excluded_descendants_of_extraneous_dir() -> anyhow::Result<()> {
906        let tmp = tempfile::tempdir()?;
907        let dst = tmp.path().join("dst");
908        tokio::fs::create_dir(&dst).await?;
909        // an extraneous directory (no source counterpart) with an excluded and a normal file
910        tokio::fs::create_dir(dst.join("extra_dir")).await?;
911        tokio::fs::write(dst.join("extra_dir").join("keep.log"), b"x").await?; // excluded by *.log
912        tokio::fs::write(dst.join("extra_dir").join("gone.txt"), b"x").await?; // not excluded
913
914        let mut filter = crate::filter::FilterSettings::new();
915        filter.add_exclude("*.log")?;
916        let keep: HashSet<OsString> = HashSet::new(); // extra_dir is extraneous
917
918        // default --delete: the excluded descendant is protected, so the dir survives non-empty
919        let dst_dir = open_dst(&dst).await?;
920        let summary = prune_extraneous(
921            &PROGRESS,
922            &dst_dir,
923            std::path::Path::new(""),
924            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
925            Some(&filter),
926            false,
927            None,
928        )
929        .await
930        .map_err(|e| e.source)?;
931        assert_eq!(summary.files_removed, 1); // gone.txt
932        assert!(!dst.join("extra_dir").join("gone.txt").exists());
933        assert!(
934            dst.join("extra_dir").join("keep.log").exists(),
935            "excluded descendant of an extraneous dir must be protected"
936        );
937
938        // --delete-excluded: the whole extraneous directory is removed
939        let dst_dir = open_dst(&dst).await?;
940        let summary = prune_extraneous(
941            &PROGRESS,
942            &dst_dir,
943            std::path::Path::new(""),
944            &DeleteKeepSet::from_complete(delete_settings(true), (keep).clone()),
945            Some(&filter),
946            false,
947            None,
948        )
949        .await
950        .map_err(|e| e.source)?;
951        assert_eq!(summary.files_removed, 1); // keep.log
952        assert!(!dst.join("extra_dir").exists());
953        Ok(())
954    }
955
956    #[tokio::test]
957    #[traced_test]
958    async fn protects_path_excluded_descendants_of_extraneous_dir() -> anyhow::Result<()> {
959        let tmp = tempfile::tempdir()?;
960        let dst = tmp.path().join("dst");
961        tokio::fs::create_dir(&dst).await?;
962        // an extraneous directory whose descendants are targeted by a PATH-based exclude
963        tokio::fs::create_dir(dst.join("cache")).await?;
964        tokio::fs::write(dst.join("cache").join("foo.log"), b"x").await?; // matches cache/*.log -> protected
965        tokio::fs::write(dst.join("cache").join("data.txt"), b"x").await?; // not matched -> removed
966
967        let mut filter = crate::filter::FilterSettings::new();
968        filter.add_exclude("cache/*.log")?;
969        let keep: HashSet<OsString> = HashSet::new();
970
971        let dst_dir = open_dst(&dst).await?;
972        let summary = prune_extraneous(
973            &PROGRESS,
974            &dst_dir,
975            std::path::Path::new(""),
976            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
977            Some(&filter),
978            false,
979            None,
980        )
981        .await
982        .map_err(|e| e.source)?;
983
984        assert_eq!(summary.files_removed, 1); // data.txt
985        assert!(!dst.join("cache").join("data.txt").exists());
986        assert!(
987            dst.join("cache").join("foo.log").exists(),
988            "path-based exclude must protect the descendant of an extraneous dir"
989        );
990        Ok(())
991    }
992
993    /// A `DT_UNKNOWN` entry is authoritatively classified before delete protection.
994    #[tokio::test]
995    #[traced_test]
996    async fn protects_dir_only_excluded_directory_dt_unknown() -> anyhow::Result<()> {
997        let tmp = tempfile::tempdir()?;
998        let dst = tmp.path().join("dst");
999        tokio::fs::create_dir(&dst).await?;
1000        // extraneous destination directory `cache/` containing a file; it should be RETAINED by a
1001        // `cache/` dir-only exclude even though it has no source counterpart.
1002        tokio::fs::create_dir(dst.join("cache")).await?;
1003        tokio::fs::write(dst.join("cache").join("item.dat"), b"x").await?;
1004        // an unrelated extra file that IS extraneous and not excluded, so it should be removed.
1005        tokio::fs::write(dst.join("unrelated.txt"), b"y").await?;
1006
1007        let mut filter = crate::filter::FilterSettings::new();
1008        filter.add_exclude("cache/")?; // dir-only exclude: only protects directories, not files
1009
1010        let keep: HashSet<OsString> = HashSet::new(); // both `cache/` and `unrelated.txt` are extraneous
1011
1012        let dst_dir = open_dst(&dst).await?;
1013        let summary = prune_entries(
1014            &PROGRESS,
1015            &dst_dir,
1016            std::path::Path::new(""),
1017            &keep,
1018            Some(&filter),
1019            &delete_settings(false),
1020            false,
1021            None,
1022            vec![
1023                (std::ffi::OsString::from("cache"), None),
1024                (
1025                    std::ffi::OsString::from("unrelated.txt"),
1026                    Some(crate::walk::EntryKind::File),
1027                ),
1028            ],
1029        )
1030        .await
1031        .map_err(|e| e.source)?;
1032
1033        assert_eq!(summary.files_removed, 1); // unrelated.txt
1034        assert!(!dst.join("unrelated.txt").exists());
1035        assert!(
1036            dst.join("cache").exists(),
1037            "dir-only exclude `cache/` must protect the destination directory from --delete"
1038        );
1039        assert!(
1040            dst.join("cache").join("item.dat").exists(),
1041            "contents of the excluded directory must be preserved"
1042        );
1043        Ok(())
1044    }
1045
1046    /// Repeatedly swap `dst/extra` between a real directory (holding a real file) and a symlink to
1047    /// an OUT-OF-TREE sentinel directory, using rename so each individual state is atomic. Two
1048    /// staging names live alongside `extra` and are renamed over it in a tight loop until `stop` is
1049    /// set. Runs on a dedicated OS thread so it makes progress regardless of the tokio runtime's
1050    /// scheduling. Mirrors rm's `spawn_dir_symlink_swapper`.
1051    fn spawn_extra_swapper(
1052        dst: std::path::PathBuf,
1053        sentinel: std::path::PathBuf,
1054        stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1055    ) -> std::thread::JoinHandle<()> {
1056        std::thread::spawn(move || {
1057            let extra = dst.join("extra");
1058            let staged_dir = dst.join("__staged_extra_dir");
1059            let staged_link = dst.join("__staged_extra_link");
1060            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1061                // stage a real directory (with a real file) then swap it in over `extra`.
1062                let _ = std::fs::remove_dir_all(&staged_dir);
1063                if std::fs::create_dir(&staged_dir).is_ok() {
1064                    let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL");
1065                    // RENAME_EXCHANGE isn't portable here; remove-then-rename. The window where
1066                    // `extra` is briefly absent is fine — prune may error or no-op, an accepted
1067                    // failed-closed outcome. (prune must still never touch the sentinel.)
1068                    let _ = std::fs::remove_dir_all(&extra);
1069                    let _ = std::fs::remove_file(&extra);
1070                    let _ = std::fs::rename(&staged_dir, &extra);
1071                }
1072                // stage a symlink to the out-of-tree sentinel dir, then swap it in over `extra`.
1073                let _ = std::fs::remove_file(&staged_link);
1074                if std::os::unix::fs::symlink(&sentinel, &staged_link).is_ok() {
1075                    let _ = std::fs::remove_dir_all(&extra);
1076                    let _ = std::fs::remove_file(&extra);
1077                    let _ = std::fs::rename(&staged_link, &extra);
1078                }
1079            }
1080        })
1081    }
1082
1083    /// While `prune_extraneous` prunes an extraneous destination SUBDIRECTORY (`dst/extra`, with no
1084    /// source counterpart so the empty keep-set marks it for deletion), a background thread rapidly
1085    /// flips `dst/extra` between a real directory and a symlink to a SENTINEL directory tree that
1086    /// lives OUTSIDE the destination, holding files that must never be deleted.
1087    ///
1088    /// Prune is fd-relative: it enumerates and removes children through the destination's own
1089    /// pinned `Dir` fd (`rm_child` → `child()` classify + `open_dir` descent). If `extra` is a
1090    /// symlink at the moment of descent, `open_dir`'s `O_NOFOLLOW|O_DIRECTORY` fails closed
1091    /// (ELOOP/ENOTDIR) and prune never follows it into the sentinel. If `extra` is a symlink at the
1092    /// moment of classification it is treated as a leaf and `unlink_at` removes the LINK, never its
1093    /// target. Either way the out-of-tree sentinel files survive — the core safety assertion,
1094    /// checked on every iteration regardless of timing. Also confirms the run terminates (per-op
1095    /// timeout) rather than hanging or following the link.
1096    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1097    async fn prune_extra_dir_swap_never_deletes_out_of_tree_sentinel() -> anyhow::Result<()> {
1098        let tmp = tempfile::tempdir()?;
1099        let root = tmp.path();
1100        // the sentinel tree lives OUTSIDE the destination, reachable only via the swapped symlink.
1101        let sentinel = root.join("sentinel_tree");
1102        tokio::fs::create_dir(&sentinel).await?;
1103        tokio::fs::write(sentinel.join("secret1.txt"), b"SECRET-1").await?;
1104        tokio::fs::create_dir(sentinel.join("subdir")).await?;
1105        tokio::fs::write(sentinel.join("subdir").join("secret2.txt"), b"SECRET-2").await?;
1106
1107        let dst = root.join("dst");
1108        tokio::fs::create_dir(&dst).await?;
1109
1110        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1111        let swapper = spawn_extra_swapper(dst.clone(), sentinel.clone(), stop.clone());
1112
1113        // empty keep-set: `extra` (and any other entry) is extraneous and marked for pruning.
1114        let keep: HashSet<OsString> = HashSet::new();
1115        let mut pruned = 0usize;
1116        let mut errored = 0usize;
1117        for i in 0..400 {
1118            // give `dst` many sibling extraneous subdirectories with files so prune spends real
1119            // time enumerating/removing them concurrently with the swapper's flips, widening the
1120            // window in which `extra` is classified/descended mid-swap.
1121            for d in 0..16 {
1122                let sib = dst.join(format!("sib_{d}"));
1123                let _ = tokio::fs::create_dir(&sib).await;
1124                for f in 0..4 {
1125                    let _ = tokio::fs::write(sib.join(format!("f{f}.txt")), b"x").await;
1126                }
1127            }
1128            let extra = dst.join("extra");
1129            if i % 2 == 0 {
1130                // deterministically place a symlink-to-sentinel at `extra` (best-effort; the
1131                // swapper may immediately flip it — both states are safe).
1132                let _ = tokio::fs::remove_dir_all(&extra).await;
1133                let _ = tokio::fs::remove_file(&extra).await;
1134                let _ = tokio::fs::symlink(&sentinel, &extra).await;
1135            } else if tokio::fs::symlink_metadata(&extra).await.is_err() {
1136                let _ = tokio::fs::create_dir(&extra).await;
1137                let _ = tokio::fs::write(extra.join("real.txt"), b"REAL").await;
1138            }
1139            // open the destination O_NOFOLLOW (as the real call sites do) and prune it.
1140            let dst_dir = open_dst(&dst).await?;
1141            let result = tokio::time::timeout(
1142                std::time::Duration::from_secs(30),
1143                prune_extraneous(
1144                    &PROGRESS,
1145                    &dst_dir,
1146                    std::path::Path::new(""),
1147                    &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
1148                    None,
1149                    false,
1150                    None,
1151                ),
1152            )
1153            .await
1154            .expect("prune must not hang under concurrent dir swapping");
1155            match result {
1156                Ok(_) => pruned += 1,
1157                Err(_) => errored += 1, // a swap was caught mid-walk (failed closed) — accepted
1158            }
1159            // CORE SAFETY ASSERTION (holds on every iteration regardless of timing): the
1160            // out-of-tree sentinel tree and its files are NEVER deleted — neither by following a
1161            // symlinked `extra` (unlink removes the link, not the target) nor by descending it
1162            // (open_dir's O_NOFOLLOW fails closed).
1163            assert!(
1164                sentinel.exists(),
1165                "iteration {i}: sentinel directory was deleted — prune followed the symlink"
1166            );
1167            let s1 = tokio::fs::read(sentinel.join("secret1.txt")).await;
1168            assert!(
1169                matches!(&s1, Ok(b) if b == b"SECRET-1"),
1170                "iteration {i}: sentinel/secret1.txt was deleted or altered — prune followed the symlink"
1171            );
1172            let s2 = tokio::fs::read(sentinel.join("subdir").join("secret2.txt")).await;
1173            assert!(
1174                matches!(&s2, Ok(b) if b == b"SECRET-2"),
1175                "iteration {i}: sentinel/subdir/secret2.txt was deleted — prune recursed through the symlink"
1176            );
1177        }
1178
1179        stop.store(true, std::sync::atomic::Ordering::Relaxed);
1180        swapper.join().expect("extra swapper thread panicked");
1181        // sanity (not the safety assertion): the run did observable work across the iterations.
1182        tracing::info!("prune extra-dir swap: pruned={pruned}, errored={errored}");
1183        assert!(
1184            pruned + errored > 0,
1185            "expected at least one observable outcome across the iterations"
1186        );
1187        Ok(())
1188    }
1189
1190    #[tokio::test]
1191    #[traced_test]
1192    async fn opening_dst_symlink_to_directory_fails_closed() -> anyhow::Result<()> {
1193        // prune operates through a `Dir` the caller opens `O_NOFOLLOW`. In a real --delete run the
1194        // create-or-overwrite step replaces any non-directory destination (including a symlink)
1195        // before prune runs; in --dry-run that overwrite is skipped, so the destination path could
1196        // still be a symlink-to-directory. Opening it `O_NOFOLLOW|O_DIRECTORY` (dereference=false) —
1197        // exactly what the copy/link prune call sites do — must fail closed on that symlink rather
1198        // than follow it. Prune can never receive a `Dir` that followed a destination symlink, so it
1199        // cannot preview or perform deletions outside the destination tree.
1200        let tmp = tempfile::tempdir()?;
1201        let dst_parent = tmp.path().join("dst_parent");
1202        let outside = tmp.path().join("outside"); // outside the destination tree
1203        tokio::fs::create_dir(&dst_parent).await?;
1204        tokio::fs::create_dir(&outside).await?;
1205        tokio::fs::write(outside.join("precious.txt"), b"keep me").await?;
1206        // dst is a symlink-to-directory living under the parent we'd prune.
1207        let dst = dst_parent.join("link_dir");
1208        std::os::unix::fs::symlink(&outside, &dst)?;
1209
1210        // opening the symlinked dst O_NOFOLLOW must fail (ELOOP), so the call site skips prune.
1211        let result = Dir::open_root_dir(&dst, false, congestion::Side::Destination).await;
1212        assert!(
1213            result.is_err(),
1214            "opening a dst symlink-to-directory O_NOFOLLOW must fail closed, not follow it"
1215        );
1216        // the out-of-tree tree is untouched.
1217        assert!(outside.join("precious.txt").exists());
1218        Ok(())
1219    }
1220}