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