Skip to main content

common/
rm.rs

1use anyhow::{Context, anyhow};
2use std::ffi::OsStr;
3use std::os::unix::fs::PermissionsExt;
4use std::sync::Arc;
5use tracing::instrument;
6
7use crate::filter::TimeFilter;
8use crate::progress;
9use crate::safedir::{self, Dir, Handle};
10use crate::walk::{AdmittedEntry, AdmittedLeaf, EntryAdmission, EntryKind, LeafPermit, PermitKind};
11use crate::walk_driver::{
12    DirAction, DirPostInput, DirPreResult, EntryCx, SkippedEntry, WalkVisitor,
13    process_admitted_entry, process_entry,
14};
15
16/// Error type for remove operations. See [`crate::error::OperationError`] for
17/// logging conventions and rationale.
18pub type Error = crate::error::OperationError<Summary>;
19
20#[derive(Debug, Clone)]
21pub struct Settings {
22    pub fail_early: bool,
23    /// filter settings for include/exclude patterns
24    pub filter: Option<crate::filter::FilterSettings>,
25    /// time-based filter (mtime/btime); applied to each entry individually (files,
26    /// symlinks, and directories). This is an entry filter, not a subtree gate:
27    /// directories are always traversed, and the filter only decides whether each
28    /// entry — including the directory itself, after its children are processed — is
29    /// eligible for removal. A directory whose own timestamps are too recent is left
30    /// intact even when its children have been removed; a non-empty leftover directory
31    /// is logged at info and not treated as an error.
32    pub time_filter: Option<TimeFilter>,
33    /// dry-run mode for previewing operations
34    pub dry_run: Option<crate::config::DryRunMode>,
35}
36
37/// Returns true when `err`'s chain contains an `io::Error` with `ErrorKind::Unsupported`.
38/// Used to downgrade time-filter eval failures on filesystems / entry types that don't
39/// report btime (e.g. many symlinks) from `error!` to `warn!` so they don't flood logs
40/// on otherwise-successful runs.
41fn is_unsupported_io_error(err: &anyhow::Error) -> bool {
42    err.chain().any(|cause| {
43        cause
44            .downcast_ref::<std::io::Error>()
45            .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::Unsupported)
46    })
47}
48
49/// Summary with the appropriate `*_skipped` counter set to 1 for the given entry kind.
50/// Special files count as `files_skipped` to match the historical mapping used
51/// when filters skip an entry.
52fn skipped_summary_for(kind: EntryKind) -> Summary {
53    match kind {
54        EntryKind::Dir => Summary {
55            directories_skipped: 1,
56            ..Default::default()
57        },
58        EntryKind::Symlink => Summary {
59            symlinks_skipped: 1,
60            ..Default::default()
61        },
62        EntryKind::File | EntryKind::Special => Summary {
63            files_skipped: 1,
64            ..Default::default()
65        },
66    }
67}
68
69#[derive(Copy, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
70pub struct Summary {
71    pub bytes_removed: u64,
72    pub files_removed: usize,
73    pub symlinks_removed: usize,
74    pub directories_removed: usize,
75    pub files_skipped: usize,
76    pub symlinks_skipped: usize,
77    pub directories_skipped: usize,
78}
79
80impl std::ops::Add for Summary {
81    type Output = Self;
82    fn add(self, other: Self) -> Self {
83        Self {
84            bytes_removed: self.bytes_removed + other.bytes_removed,
85            files_removed: self.files_removed + other.files_removed,
86            symlinks_removed: self.symlinks_removed + other.symlinks_removed,
87            directories_removed: self.directories_removed + other.directories_removed,
88            files_skipped: self.files_skipped + other.files_skipped,
89            symlinks_skipped: self.symlinks_skipped + other.symlinks_skipped,
90            directories_skipped: self.directories_skipped + other.directories_skipped,
91        }
92    }
93}
94
95impl std::fmt::Display for Summary {
96    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
97        write!(
98            f,
99            "bytes removed: {}\n\
100            files removed: {}\n\
101            symlinks removed: {}\n\
102            directories removed: {}\n\
103            files skipped: {}\n\
104            symlinks skipped: {}\n\
105            directories skipped: {}\n",
106            bytesize::ByteSize(self.bytes_removed),
107            self.files_removed,
108            self.symlinks_removed,
109            self.directories_removed,
110            self.files_skipped,
111            self.symlinks_skipped,
112            self.directories_skipped
113        )
114    }
115}
116
117/// A temporary directory-mode change that can be undone when filters retain the directory.
118///
119/// This is passive state, not an RAII cleanup guard. Once removal starts, errors and cancellation
120/// do not attempt to roll the directory back: its name or identity may already have changed, and
121/// the operation cannot restore the rest of the partially removed tree. The only restoration sites
122/// are branches where filtering deliberately leaves this directory in place.
123struct RelaxedDir {
124    handle: Handle,
125    original_mode: u32,
126}
127
128impl RelaxedDir {
129    /// Pins the exact inode before changing its mode.
130    fn prepare(handle: &Handle, original_mode: u32) -> std::io::Result<Self> {
131        Ok(Self {
132            handle: handle.try_clone()?,
133            original_mode,
134        })
135    }
136
137    /// Restores a filter-retained directory through normal chmod admission.
138    async fn restore(self) -> std::io::Result<()> {
139        safedir::chmod_via_proc_fd(
140            &self.handle,
141            congestion::Side::Destination,
142            self.original_mode,
143        )
144        .await
145    }
146}
147
148async fn restore_retained_dir(
149    relaxed: Option<RelaxedDir>,
150    path: &std::path::Path,
151) -> anyhow::Result<()> {
152    if let Some(relaxed) = relaxed {
153        relaxed
154            .restore()
155            .await
156            .with_context(|| format!("failed to restore filter-retained directory {path:?}"))?;
157    }
158    Ok(())
159}
160
161/// Public entry point for remove operations.
162///
163/// The walk is fd-based (see [`crate::safedir`]): the root operand is opened relative to its
164/// parent directory and every entry is classified and removed through file-descriptor-relative
165/// syscalls. A privileged `rrm` therefore cannot be redirected by a concurrent symlink swap
166/// into deleting a tree outside the intended target (the classic `rm -rf` symlink race) — the
167/// `O_NOFOLLOW|O_DIRECTORY` opens in [`Dir::open_dir`] catch a directory→symlink swap mid-walk
168/// and fail closed (ELOOP/ENOTDIR) rather than descending the link, and leaf removal uses
169/// `unlinkat` (never follows a symlink). The recursive walk skeleton — enumeration, the
170/// leaf-permit lifecycle, spawning, the single drop-before-recurse site, and the error fold —
171/// lives in the generic `walk_driver`; this module supplies the remove visitor.
172#[instrument(skip(prog_track, settings))]
173pub async fn rm(
174    prog_track: &'static progress::Progress,
175    path: &std::path::Path,
176    settings: &Settings,
177) -> Result<Summary, Error> {
178    // command-line callers may run many root operands concurrently. admit each one before opening
179    // its parent or performing the optional fd-based filter probe, then transfer that same permit
180    // into the shared driver. an authoritative directory releases it before descent.
181    let permit = crate::walk::ensure_leaf_permit(PermitKind::PendingMeta, None).await;
182    enum RmRootSetup {
183        Complete(Summary),
184        Ready {
185            operand: crate::walk::RootOperand,
186            parent: Arc<Dir>,
187            entry: AdmittedEntry,
188        },
189    }
190    let setup = safedir::with_optional_fd_admission(
191        permit.as_ref().map(LeafPermit::admission),
192        async move {
193            // decompose the operand into (parent dir, final component) so the root entry is opened and
194            // classified relative to a directory fd — the same fd-relative shape every nested entry takes.
195            // `.`/`..` operands (e.g. `rrm .`) are canonicalized so they still name a directory; `/` is
196            // rejected. rm reads and removes "the" tree; we gate it on the Source side (matching the
197            // existing rm code, which probes its stat/readdir on Source and only the destructive
198            // unlink/rmdir on Destination).
199            let operand = crate::walk::split_root_operand(path)
200                .await
201                .map_err(|err| Error::new(err, Default::default()))?;
202            let parent_path = operand.parent.as_path();
203            let name = operand.name.as_os_str();
204            let path = operand.display.as_path();
205            // the operand's TRUSTED parent prefix is resolved following symlinks normally (the prefix is
206            // trusted up to and including the operand's container — only entries strictly below the named
207            // root are O_NOFOLLOW-hardened). a symlinked parent (e.g. `rrm symlinkdir/foo`) is followed; the
208            // operand itself is still classified via `child(name)` with O_NOFOLLOW (a symlink root is
209            // removed as the link itself).
210            let parent = Dir::open_parent_dir(parent_path, congestion::Side::Source)
211                .await
212                .with_context(|| format!("cannot open parent directory {parent_path:?}"))
213                .map_err(|err| Error::new(err, Default::default()))?;
214            // cross from the trusted parent prefix into the hardened tree (O_NOFOLLOW below here).
215            let parent = Arc::new(parent.into_tree());
216            // classify the root once under admission. A filter decides from this handle, and an
217            // included entry transfers the same owner into the shared driver.
218            let entry = crate::walk::classify_admitted_entry(&parent, name, permit)
219                .await
220                .with_context(|| format!("failed reading metadata from {path:?}"))
221                .map_err(|err| Error::new(err, Default::default()))?;
222            if let Some(ref filter) = settings.filter {
223                let name_path = std::path::Path::new(name);
224                let result =
225                    filter.should_include_root_item(name_path, entry.kind() == EntryKind::Dir);
226                match result {
227                    crate::filter::FilterResult::Included => {}
228                    result => {
229                        let kind = entry.kind();
230                        if let Some(mode) = settings.dry_run {
231                            crate::dry_run::report_skip(path, &result, mode, kind.label_long());
232                        }
233                        kind.inc_skipped(prog_track);
234                        return Ok(RmRootSetup::Complete(skipped_summary_for(kind)));
235                    }
236                }
237            }
238            Ok(RmRootSetup::Ready {
239                operand,
240                parent,
241                entry,
242            })
243        },
244    )
245    .await?;
246    let (operand, parent, entry) = match setup {
247        RmRootSetup::Complete(summary) => return Ok(summary),
248        RmRootSetup::Ready {
249            operand,
250            parent,
251            entry,
252        } => (operand, parent, entry),
253    };
254    let name = operand.name.as_os_str();
255    let path = operand.display.as_path();
256    // the root context starts with an empty logical path and the operand as its display path
257    // the root is processed like a nested child via `process_admitted_entry`, transferring
258    // classification and admission acquired during setup
259    let visitor = Arc::new(RmVisitor {
260        protection: None,
261        prog_track,
262        settings: settings.clone(),
263    });
264    let root_cx = EntryCx::root(
265        Arc::clone(&parent),
266        name.to_owned(),
267        path.to_path_buf(),
268        prog_track,
269    );
270    process_admitted_entry(visitor, root_cx, (), entry).await // rm has no second tree → root context `()`
271}
272
273/// Remove a single child entry of an already-open directory, fd-relative.
274///
275/// This is the fd-based counterpart of path-based [`rm`]. It is used by two callers that
276/// already hold the relevant directory as an open [`Dir`] and want to remove one of its children
277/// through that pinned fd rather than re-resolving the entry by absolute path (the redirectable
278/// window):
279/// - `--delete` pruning removes each extraneous entry.
280/// - the remote-copy destination (`rcpd`) replaces a non-matching destination subtree (a
281///   directory/file/symlink in the way of the entry it must create) through the parent directory
282///   fd held in its directory tracker.
283///
284/// The entry is classified via `parent.child(name)` (`O_PATH|O_NOFOLLOW`, so a symlink is
285/// classified as a symlink, never followed) and then removed through the same fd-relative remove
286/// machinery (driven by `walk_driver::process_entry`): leaves via `unlinkat`, directories
287/// by recursing with `O_NOFOLLOW|O_DIRECTORY` descent and fd-pinned permission state. A privileged
288/// caller therefore cannot be redirected by a concurrent symlink swap of `name` into deleting a
289/// tree outside the directory it holds.
290///
291/// `rel_path` seeds both logical and display paths. Pruning supplies the entry's mirror-relative
292/// path to preserve the include/exclude namespace. Overwrite removal supplies the full destination
293/// display path and disables filtering. Neither form is opened by path. The caller owns the
294/// top-level decision on `name` (keep-set membership, exclude protection, or overwrite policy);
295/// this only removes the subtree.
296pub async fn rm_child(
297    prog_track: &'static progress::Progress,
298    parent: &Arc<Dir>,
299    name: &OsStr,
300    rel_path: &std::path::Path,
301    settings: &Settings,
302) -> Result<Summary, Error> {
303    rm_child_admitted(
304        prog_track,
305        parent,
306        name,
307        rel_path,
308        settings,
309        EntryAdmission::RootOrDelegated,
310        None,
311    )
312    .await
313}
314
315/// Remove an already-located child while transferring its explicit admission state.
316///
317/// Unfiltered `--delete` uses this to preserve its scheduling hint. Other callers use
318/// [`rm_child`], and the shared driver acquires before its own classification. A destructive filter
319/// that already classified the entry uses [`rm_child_admitted_entry`] instead.
320pub(crate) async fn rm_child_admitted(
321    prog_track: &'static progress::Progress,
322    parent: &Arc<Dir>,
323    name: &OsStr,
324    rel_path: &std::path::Path,
325    settings: &Settings,
326    admission: EntryAdmission,
327    protection: Option<Arc<crate::input_protection::InputProtection>>,
328) -> Result<Summary, Error> {
329    rm_child_with_source(
330        prog_track,
331        parent,
332        name,
333        rel_path,
334        settings,
335        RmChildSource::Unclassified(admission),
336        protection,
337    )
338    .await
339}
340
341/// Remove a child using the authoritative entry that informed a destructive filter decision.
342pub(crate) async fn rm_child_admitted_entry(
343    prog_track: &'static progress::Progress,
344    parent: &Arc<Dir>,
345    name: &OsStr,
346    rel_path: &std::path::Path,
347    settings: &Settings,
348    entry: AdmittedEntry,
349    protection: Option<Arc<crate::input_protection::InputProtection>>,
350) -> Result<Summary, Error> {
351    rm_child_with_source(
352        prog_track,
353        parent,
354        name,
355        rel_path,
356        settings,
357        RmChildSource::Admitted(entry),
358        protection,
359    )
360    .await
361}
362
363enum RmChildSource {
364    Unclassified(EntryAdmission),
365    Admitted(AdmittedEntry),
366}
367
368#[allow(clippy::too_many_arguments)]
369async fn rm_child_with_source(
370    prog_track: &'static progress::Progress,
371    parent: &Arc<Dir>,
372    name: &OsStr,
373    rel_path: &std::path::Path,
374    settings: &Settings,
375    source: RmChildSource,
376    protection: Option<Arc<crate::input_protection::InputProtection>>,
377) -> Result<Summary, Error> {
378    // pruning passes a mirror-relative seed; unfiltered overwrite passes a full display path
379    // both coordinates start from this one seed and are never used to open a removal target
380    let visitor = Arc::new(RmVisitor {
381        protection,
382        prog_track,
383        settings: settings.clone(),
384    });
385    let root_cx = EntryCx::seeded(
386        Arc::clone(parent),
387        name.to_owned(),
388        rel_path.to_path_buf(),
389        prog_track,
390    );
391    match source {
392        RmChildSource::Unclassified(admission) => {
393            process_entry(visitor, root_cx, (), admission).await
394        }
395        RmChildSource::Admitted(entry) => process_admitted_entry(visitor, root_cx, (), entry).await,
396    }
397}
398/// The remove walk's [`WalkVisitor`]. The driver owns enumeration, the leaf-permit lifecycle,
399/// spawning, the single drop-before-recurse site, and the error fold; this visitor supplies rm's
400/// per-entry bodies (leaf removal in [`WalkVisitor::visit_leaf`], permission relax + metadata
401/// snapshot in [`WalkVisitor::dir_pre`], and the post-order `rmdir` decision in
402/// [`WalkVisitor::dir_post`]). rm has no second tree, so [`Self::DirContext`] is `()`.
403struct RmVisitor {
404    protection: Option<Arc<crate::input_protection::InputProtection>>,
405    prog_track: &'static progress::Progress,
406    settings: Settings,
407}
408
409/// State threaded from [`WalkVisitor::dir_pre`] to [`WalkVisitor::dir_post`] (same task) — what the
410/// post-order `rmdir` decision needs.
411struct RmDirState {
412    /// Restores the relaxed mode only if filtering deliberately retains this directory. `None` in
413    /// dry-run and when the directory already had owner rwx, because neither case changes the mode.
414    relaxed: Option<RelaxedDir>,
415    /// The directory's PRISTINE full metadata, snapshotted in `dir_pre` BEFORE the relax or any
416    /// child removal, so the directory's own time filter sees timestamps unperturbed by clearing
417    /// its contents (removing children bumps mtime). `Some` iff a time filter is configured.
418    time_metadata: Option<anyhow::Result<std::fs::Metadata>>,
419    /// Whether the directory does NOT directly match an include pattern while includes are active —
420    /// the path-only half of the "traversed only" decision. Combined in `dir_post` with
421    /// "nothing was removed" (derived from the children's folded summary) to reproduce the old
422    /// `traversed_only` exactly.
423    matches_no_include: bool,
424}
425
426impl WalkVisitor for RmVisitor {
427    type Summary = Summary;
428    type DirContext = ();
429    type DirState = RmDirState;
430
431    fn root_dir_context(&self) {}
432
433    fn permit_kind(&self) -> PermitKind {
434        // use PendingMeta because copy/link overwrite leaf work can invoke rm while retaining
435        // OpenFile admission. A distinct semaphore keeps that one-way composition from becoming a
436        // hold-and-wait cycle while still bounding fd-backed entry handles
437        PermitKind::PendingMeta
438    }
439
440    fn fail_early(&self) -> bool {
441        self.settings.fail_early
442    }
443
444    fn filter(&self) -> Option<&crate::filter::FilterSettings> {
445        self.settings.filter.as_ref()
446    }
447
448    fn filter_requires_admitted_entry(&self) -> bool {
449        true
450    }
451
452    fn filter_allows_hint_only_skip(&self, _dir_ctx: &Self::DirContext) -> bool {
453        // real removal needs no action after an exclusion, but preview counters and actions describe
454        // the current entry type and therefore require the exact admitted filter decision.
455        self.settings.dry_run.is_none()
456    }
457
458    fn on_skip(
459        &self,
460        cx: &SkippedEntry<'_>,
461        kind: EntryKind,
462        skip_result: &crate::filter::FilterResult,
463    ) -> Summary {
464        // mirror the old spawn loop's inline filter-skip: the dry-run "skip ..." line plus the
465        // matching `*_skipped` counter. the driver already did the shared progress increment.
466        cx.report_skip(self.settings.dry_run, skip_result, kind);
467        skipped_summary_for(kind)
468    }
469
470    async fn visit_leaf(
471        &self,
472        cx: &EntryCx,
473        _parent_ctx: &(),
474        leaf: AdmittedLeaf,
475    ) -> Result<Summary, Error> {
476        let kind = leaf.kind();
477        let prog_track = self.prog_track;
478        let settings = &self.settings;
479        let parent = &cx.parent;
480        let name = cx.name.as_os_str();
481        let path = cx.real_path.as_path();
482        tracing::debug!("not a directory, just remove");
483        let is_symlink = kind == EntryKind::Symlink;
484        let file_size = if is_symlink {
485            0
486        } else {
487            crate::preserve::Metadata::size(leaf.handle().meta())
488        };
489        // apply time filter before removing (files/symlinks only)
490        if let Some(ref time_filter) = settings.time_filter {
491            let entry_type = if is_symlink { "symlink" } else { "file" };
492            let make_skipped_summary = || {
493                tracing::debug!("skipping {:?} due to time filter", &path);
494                if is_symlink {
495                    prog_track.symlinks_skipped.inc();
496                    Summary {
497                        symlinks_skipped: 1,
498                        ..Default::default()
499                    }
500                } else {
501                    prog_track.files_skipped.inc();
502                    Summary {
503                        files_skipped: 1,
504                        ..Default::default()
505                    }
506                }
507            };
508            // the time filter needs full std metadata (btime for --created-before), which the
509            // fd snapshot does not carry; read it inode-exact through the pinned handle so a
510            // concurrent swap of `name` cannot redirect the stat to a different inode.
511            let metadata =
512                match safedir::stat_meta_via_proc_fd(leaf.handle(), congestion::Side::Source).await
513                {
514                    Ok(md) => md,
515                    Err(err) => {
516                        let err = anyhow::Error::new(err).context(format!(
517                            "failed reading metadata for time filter on {path:?}"
518                        ));
519                        if settings.fail_early {
520                            return Err(Error::new(err, Default::default()));
521                        }
522                        // log and skip — never delete an entry whose age we cannot verify.
523                        if is_unsupported_io_error(&err) {
524                            tracing::warn!(
525                                "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
526                                entry_type,
527                                &path,
528                                &err
529                            );
530                        } else {
531                            tracing::error!(
532                                "time filter evaluation failed for {} {:?}, skipping: {:#}",
533                                entry_type,
534                                &path,
535                                &err
536                            );
537                        }
538                        return Ok(make_skipped_summary());
539                    }
540                };
541            match time_filter.matches(&metadata) {
542                Ok(result) => {
543                    if let Some(skip_reason) = result.as_skip_reason() {
544                        if let Some(mode) = settings.dry_run {
545                            crate::dry_run::report_time_skip(path, skip_reason, mode, entry_type);
546                        }
547                        return Ok(make_skipped_summary());
548                    }
549                }
550                Err(err) => {
551                    let err = err.context(format!("failed evaluating time filter on {:?}", &path));
552                    if settings.fail_early {
553                        return Err(Error::new(err, Default::default()));
554                    }
555                    // log and skip — never delete an entry whose age we cannot verify.
556                    // btime being unsupported (common for symlinks) is expected noise, so
557                    // downgrade to warn; anything else is unexpected and stays at error.
558                    if is_unsupported_io_error(&err) {
559                        tracing::warn!(
560                            "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
561                            entry_type,
562                            &path,
563                            &err
564                        );
565                    } else {
566                        tracing::error!(
567                            "time filter evaluation failed for {} {:?}, skipping: {:#}",
568                            entry_type,
569                            &path,
570                            &err
571                        );
572                    }
573                    return Ok(make_skipped_summary());
574                }
575            }
576        }
577        if let Some(protection) = &self.protection {
578            protection
579                .check_child(parent, name, path)
580                .await
581                .map_err(|error| Error::new(error.into(), Default::default()))?;
582        }
583        // handle dry-run mode for files/symlinks
584        if settings.dry_run.is_some() {
585            let entry_type = if is_symlink { "symlink" } else { "file" };
586            crate::dry_run::report_action("remove", path, None, entry_type);
587            return Ok(Summary {
588                bytes_removed: file_size,
589                files_removed: if is_symlink { 0 } else { 1 },
590                symlinks_removed: if is_symlink { 1 } else { 0 },
591                ..Default::default()
592            });
593        }
594        // the filter decision depends only on path plus directory-vs-nondirectory. Every kind this
595        // branch accepts has the same nondirectory decision, while unlinkat without AT_REMOVEDIR
596        // cannot remove a directory swapped into the name. Keep the classified handle for exact
597        // metadata/time/accounting, then perform the single fd-relative removal without opening a
598        // second PendingMeta descriptor. A same-class final-component replacement remains contained
599        // to the held parent, matching the documented best-effort residual.
600        //
601        // unlink_at never follows a symlink and is resolved relative to the parent dir fd, so it
602        // cannot be redirected outside the tree.
603        // gated on the Destination side to match the side the path-based rm used for remove_file.
604        if let Err(err) = parent
605            .unlink_at_on(name, congestion::Side::Destination)
606            .await
607            .with_context(|| format!("failed removing {:?}", &path))
608        {
609            return Err(Error::new(err, Default::default()));
610        }
611        if is_symlink {
612            prog_track.symlinks_removed.inc();
613            return Ok(Summary {
614                symlinks_removed: 1,
615                ..Default::default()
616            });
617        }
618        prog_track.files_removed.inc();
619        prog_track.bytes_removed.add(file_size);
620        Ok(Summary {
621            bytes_removed: file_size,
622            files_removed: 1,
623            ..Default::default()
624        })
625    }
626
627    async fn dir_pre(&self, cx: &EntryCx, _parent_ctx: &(), handle: &Handle) -> DirPreResult<Self> {
628        let settings = &self.settings;
629        let path = cx.real_path.as_path();
630        tracing::debug!("remove contents of the directory first");
631        if let Some(protection) = &self.protection {
632            protection
633                .check_child(&cx.parent, &cx.name, path)
634                .await
635                .and_then(|()| protection.check_directory(handle.meta(), path))
636                .map_err(|error| Error::new(error.into(), Default::default()))?;
637        }
638
639        // Snapshot the directory's full metadata NOW, before relaxing its mode or removing any
640        // child. The directory's own time filter (evaluated in `dir_post`, after its children are
641        // processed) must use these pristine timestamps: removing children bumps the directory's
642        // mtime, so a fresh stat at the end would wrongly see the directory as "just modified".
643        // This mirrors the old code's `src_metadata` captured at entry. We read full std metadata
644        // (not just the fd snapshot) because `--created-before` needs btime; it's read inode-exact
645        // through the pinned handle. Only fetched when a time filter is configured. The relax below
646        // changes only mode/ctime, never mtime/btime, so taking the snapshot before it is correct.
647        let time_metadata: Option<anyhow::Result<std::fs::Metadata>> =
648            if settings.time_filter.is_some() {
649                Some(
650                    safedir::stat_meta_via_proc_fd(handle, congestion::Side::Source)
651                        .await
652                        .map_err(|err| {
653                            anyhow::Error::new(err).context(format!(
654                                "failed reading metadata for time filter on {path:?}"
655                            ))
656                        }),
657                )
658            } else {
659                None
660            };
661        // the path-only half of the "traversed only" decision: a directory is "traversed only" when
662        // include filters are active and the directory itself doesn't directly match an include
663        // pattern (it was entered only to search for matching content). `dir_post` combines this
664        // with "nothing was removed". exclude-only filters never produce traversed-only directories
665        // because `directly_matches_include` returns true when no includes exist.
666        let matches_no_include = settings
667            .filter
668            .as_ref()
669            .is_some_and(|f| f.has_includes() && !f.directly_matches_include(&cx.rel_path, true));
670        // when the directory lacks owner write/execute we relax it so its contents can be cleared.
671        // the relax goes through the directory's own `O_PATH` handle (via /proc), which works even
672        // on a 0000-mode dir a non-root owner cannot open O_RDONLY — so it must happen BEFORE
673        // `open_dir`. the passive state carried in `RmDirState` restores the original mode only if
674        // filtering deliberately retains the directory. errors, cancellation, and intended removal
675        // simply drop it. dry-run skips the relax entirely.
676        let mut relaxed: Option<RelaxedDir> = None;
677        if settings.dry_run.is_none() {
678            let original_mode =
679                crate::preserve::Metadata::permissions(handle.meta()).mode() & 0o7777;
680            // relax unless the owner already has full r/w/x. read is needed to enumerate the dir
681            // (open_dir + getdents), and write+execute to unlink/rmdir its entries. 0o700 = u+rwx.
682            // this is a superset of the old `readonly()` (no-write) trigger, and also covers dirs
683            // missing owner read/execute that the old path-based read_dir would have failed on.
684            if original_mode & 0o700 != 0o700 {
685                tracing::debug!("directory is not writable/traversable - relax the permissions");
686                // pin the inode before relaxing so a filter-retention branch can later restore that
687                // exact directory even if its name has changed.
688                let prepared = RelaxedDir::prepare(handle, original_mode)
689                    .with_context(|| format!("failed to pin relaxed directory {path:?}"))
690                    .map_err(|err| Error::new(err, Default::default()))?;
691                // gated as a Destination Chmod: the relax is a permission mutation that enables the
692                // removal, so it shares the destructive side/bucket with the unlink/rmdir below.
693                safedir::chmod_via_proc_fd(handle, congestion::Side::Destination, 0o700)
694                    .await
695                    .with_context(|| {
696                        format!("failed to make {path:?} directory readable and writable")
697                    })
698                    .map_err(|err| Error::new(err, Default::default()))?;
699                relaxed = Some(prepared);
700            }
701        }
702        // open the directory's real fd via the parent fd with O_NOFOLLOW|O_DIRECTORY: a directory
703        // entry swapped to a symlink mid-walk fails closed here (ELOOP/ENOTDIR) — descent never
704        // follows it outside the tree. this is the core rm -rf race closure.
705        let (dir, _) = cx
706            .parent
707            .open_dir_with_meta(&cx.name)
708            .await
709            .with_context(|| format!("failed reading directory {path:?}"))
710            .map_err(|err| Error::new(err, Default::default()))?;
711        dir.verify_same_inode(handle)
712            .await
713            .with_context(|| {
714                format!("directory {path:?} changed identity before descent (possible TOCTOU swap)")
715            })
716            .map_err(|err| Error::new(err, Default::default()))?;
717        let dir = Arc::new(dir);
718        Ok(DirAction::Descend {
719            dir,
720            child_ctx: (),
721            state: RmDirState {
722                relaxed,
723                time_metadata,
724                matches_no_include,
725            },
726        })
727    }
728
729    async fn dir_post(
730        &self,
731        cx: &EntryCx,
732        state: RmDirState,
733        child_result: DirPostInput<Self>,
734    ) -> Result<Summary, Error> {
735        let prog_track = self.prog_track;
736        let settings = &self.settings;
737        let path = cx.real_path.as_path();
738        let RmDirState {
739            relaxed,
740            time_metadata,
741            matches_no_include,
742        } = state;
743        // a child failed (keep-going mode — fail-early aborts before `dir_post`). do not rmdir or
744        // attempt metadata rollback; return the partial summary with the error.
745        let mut rm_summary = match child_result {
746            Ok((summary, _)) => summary,
747            Err(err) => return Err(err),
748        };
749        tracing::debug!("finally remove the empty directory");
750        let anything_removed = rm_summary.files_removed > 0
751            || rm_summary.symlinks_removed > 0
752            || rm_summary.directories_removed > 0;
753        let anything_skipped = rm_summary.files_skipped > 0
754            || rm_summary.symlinks_skipped > 0
755            || rm_summary.directories_skipped > 0;
756        // directories that directly match an include pattern (e.g. --include target/) should be
757        // removed even if empty; only those merely traversed for matches are left intact.
758        let traversed_only = !anything_removed && matches_no_include;
759        // evaluate the directory's own time filter to decide whether to remove it.
760        // the time filter is an entry filter, not a subtree gate: children are already handled
761        // by their own recursive calls, so this decision only controls the final rmdir.
762        // the metadata SNAPSHOT taken in `dir_pre` — before relaxing the mode or removing any
763        // child — is used so those mutations (which bump the directory's mtime) don't change the
764        // answer. this mirrors the old code's `src_metadata` captured at entry.
765        let dir_passes_time_filter: bool = if let Some(ref time_filter) = settings.time_filter {
766            // unwrap is safe: time_metadata is Some whenever time_filter is Some (both gated on
767            // settings.time_filter.is_some()).
768            let matched = time_metadata.unwrap().and_then(|md| {
769                time_filter.matches(&md).map_err(|err| {
770                    err.context(format!("failed evaluating time filter on {path:?}"))
771                })
772            });
773            match matched {
774                Ok(result) => match result.as_skip_reason() {
775                    Some(reason) => {
776                        if let Some(mode) = settings.dry_run {
777                            crate::dry_run::report_time_skip(path, reason, mode, "dir");
778                        }
779                        false
780                    }
781                    None => true,
782                },
783                Err(err) => {
784                    if settings.fail_early {
785                        return Err(Error::new(err, rm_summary));
786                    }
787                    // log and skip — never remove a directory whose age we cannot verify.
788                    // btime being unsupported on the filesystem is expected noise; downgrade
789                    // to warn. anything else is unexpected and stays at error.
790                    if is_unsupported_io_error(&err) {
791                        tracing::warn!(
792                            "time filter evaluation unsupported for dir {:?}, leaving it intact: {:#}",
793                            &path,
794                            &err
795                        );
796                    } else {
797                        tracing::error!(
798                            "time filter evaluation failed for dir {:?}, leaving it intact: {:#}",
799                            &path,
800                            &err
801                        );
802                    }
803                    false
804                }
805            }
806        } else {
807            true
808        };
809        // handle dry-run mode for directories.
810        // `traversed_only` catches dirs only entered to search for include pattern matches.
811        // `anything_skipped` catches dirs that would still have content after partial removal.
812        // `!dir_passes_time_filter` catches dirs whose own timestamps disqualify removal.
813        // the real-mode path below only needs `traversed_only` and `!dir_passes_time_filter`
814        // because the subsequent `rmdir_at` call handles the non-empty case via ENOTEMPTY.
815        if settings.dry_run.is_some() {
816            if traversed_only || anything_skipped || !dir_passes_time_filter {
817                tracing::debug!(
818                    "dry-run: directory {:?} would not be removed (removed={}, skipped={}, time_ok={})",
819                    &path,
820                    anything_removed,
821                    anything_skipped,
822                    dir_passes_time_filter
823                );
824                if !dir_passes_time_filter {
825                    prog_track.directories_skipped.inc();
826                    rm_summary.directories_skipped += 1;
827                }
828            } else {
829                crate::dry_run::report_action("remove", path, None, "dir");
830                rm_summary.directories_removed += 1;
831            }
832            return Ok(rm_summary);
833        }
834        // skip directories that were only traversed to look for include matches.
835        // not needed for exclude-only filters or directly-matched directories.
836        // non-empty directories are handled by the ENOTEMPTY check below.
837        if traversed_only {
838            tracing::debug!(
839                "directory {:?} had nothing removed, leaving it intact",
840                &path
841            );
842            restore_retained_dir(relaxed, path)
843                .await
844                .map_err(|err| Error::new(err, rm_summary))?;
845            return Ok(rm_summary);
846        }
847        // skip directories whose own timestamps don't satisfy the time filter.
848        // children have already been processed; this only gates the dir's own removal.
849        if !dir_passes_time_filter {
850            tracing::debug!(
851                "directory {:?} skipped by time filter, leaving it intact",
852                &path
853            );
854            prog_track.directories_skipped.inc();
855            rm_summary.directories_skipped += 1;
856            restore_retained_dir(relaxed, path)
857                .await
858                .map_err(|err| Error::new(err, rm_summary))?;
859            return Ok(rm_summary);
860        }
861        // when filtering is active, directories may not be empty because we only removed matching
862        // files (includes) or skipped excluded files; use rmdir (not a recursive remove) so
863        // non-empty directories fail gracefully with ENOTEMPTY. fd-relative rmdir cannot escape
864        // the held parent and can remove only the empty directory occupying this name when the
865        // syscall runs. A separate identity observation could not bind this by-name mutation, so
866        // finalization performs the one removal syscall directly.
867        #[cfg(test)]
868        let _final_rmdir_gate_visit = {
869            // this gate tests mode-restoration ordering only; finalization intentionally retains
870            // no entry fd or identity handle for the by-name rmdir
871            crate::testutils::wait_on_blocking_path_gate(path, libc::AT_FDCWD)
872        };
873        let any_filter_active = settings.filter.is_some() || settings.time_filter.is_some();
874        match cx
875            .parent
876            .rmdir_at_on(&cx.name, congestion::Side::Destination)
877            .await
878        {
879            Ok(()) => {
880                prog_track.directories_removed.inc();
881                rm_summary.directories_removed += 1;
882            }
883            Err(err) if any_filter_active => {
884                // with filtering, it's expected that directories may not be empty because we only
885                // removed matching files; raw_os_error 39 is ENOTEMPTY on Linux. this is not an
886                // error — surface it at info so users can see which directories survived.
887                if err.kind() == std::io::ErrorKind::DirectoryNotEmpty
888                    || err.raw_os_error() == Some(39)
889                {
890                    tracing::info!(
891                        "directory {:?} not empty after filtering, leaving it intact",
892                        &path
893                    );
894                    restore_retained_dir(relaxed, path)
895                        .await
896                        .map_err(|restore_err| Error::new(restore_err, rm_summary))?;
897                } else {
898                    return Err(Error::new(
899                        anyhow!(err).context(format!("failed removing directory {:?}", &path)),
900                        rm_summary,
901                    ));
902                }
903            }
904            Err(err) => {
905                return Err(Error::new(
906                    anyhow!(err).context(format!("failed removing directory {:?}", &path)),
907                    rm_summary,
908                ));
909            }
910        }
911        Ok(rm_summary)
912    }
913}
914
915#[cfg(test)]
916mod tests {
917    use super::*;
918    use crate::config::DryRunMode;
919    use crate::testutils;
920    use crate::walk_driver::ProcessedChildren;
921    use tracing_test::traced_test;
922
923    static PROGRESS: std::sync::LazyLock<progress::Progress> =
924        std::sync::LazyLock::new(progress::Progress::new);
925
926    #[tokio::test]
927    #[traced_test]
928    async fn no_write_permission() -> Result<(), anyhow::Error> {
929        let tmp_dir = testutils::setup_test_dir().await?;
930        let test_path = tmp_dir.as_path();
931        let filepaths = vec![
932            test_path.join("foo").join("0.txt"),
933            test_path.join("foo").join("bar").join("2.txt"),
934            test_path.join("foo").join("baz").join("4.txt"),
935            test_path.join("foo").join("baz"),
936        ];
937        for fpath in &filepaths {
938            // change file permissions to not readable and not writable
939            tokio::fs::set_permissions(&fpath, std::fs::Permissions::from_mode(0o555)).await?;
940        }
941        let summary = rm(
942            &PROGRESS,
943            &test_path.join("foo"),
944            &Settings {
945                fail_early: false,
946                filter: None,
947                dry_run: None,
948                time_filter: None,
949            },
950        )
951        .await?;
952        assert!(!test_path.join("foo").exists());
953        assert_eq!(summary.files_removed, 5);
954        assert_eq!(summary.symlinks_removed, 2);
955        assert_eq!(summary.directories_removed, 3);
956        Ok(())
957    }
958
959    #[tokio::test]
960    #[traced_test]
961    async fn removal_error_leaves_temporary_directory_mode() -> Result<(), anyhow::Error> {
962        // once removal starts, rrm does not try to roll temporary directory metadata back on an
963        // error. the directory could disappear or change identity immediately after any attempted
964        // cleanup, so restoration is limited to branches that deliberately retain the directory.
965        //
966        // trigger the remove_dir error path by making the dst's parent non-writable: rm can
967        // chmod-relax dst and successfully unlink its contents (write on dst is granted by the
968        // relax), but the final remove_dir(dst) needs write permission on the parent, which it
969        // doesn't have → EACCES. the error leaves dst at the temporary 0o700 mode.
970        let tmp = tempfile::tempdir()?;
971        let parent = tmp.path().join("parent");
972        let dst = parent.join("dst");
973        tokio::fs::create_dir(&parent).await?;
974        tokio::fs::create_dir(&dst).await?;
975        tokio::fs::write(dst.join("inside.txt"), b"x").await?;
976        // dst is read-only → rm relaxes it.
977        tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o555)).await?;
978        // parent is read-only (still traversable via the execute bit) → remove_dir(dst) fails.
979        tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o555)).await?;
980
981        let result = rm(
982            &PROGRESS,
983            &dst,
984            &Settings {
985                fail_early: false,
986                filter: None,
987                dry_run: None,
988                time_filter: None,
989            },
990        )
991        .await;
992
993        // restore parent writability so we can stat dst and clean up regardless of the assertion.
994        tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755)).await?;
995
996        assert!(
997            result.is_err(),
998            "rm must fail when its dst can be emptied but the parent dir blocks remove_dir"
999        );
1000        let mode = tokio::fs::metadata(&dst).await?.permissions().mode() & 0o7777;
1001        assert_eq!(
1002            mode, 0o700,
1003            "a removal error unexpectedly restored the temporary directory mode (got {mode:o}o)"
1004        );
1005
1006        // cleanup
1007        tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o755)).await?;
1008        Ok(())
1009    }
1010
1011    #[tokio::test]
1012    #[traced_test]
1013    async fn parent_dir_no_write_permission() -> Result<(), anyhow::Error> {
1014        let tmp_dir = testutils::setup_test_dir().await?;
1015        let test_path = tmp_dir.as_path();
1016        // make parent directory read-only (no write permission)
1017        tokio::fs::set_permissions(
1018            &test_path.join("foo").join("bar"),
1019            std::fs::Permissions::from_mode(0o555),
1020        )
1021        .await?;
1022        let result = rm(
1023            &PROGRESS,
1024            &test_path.join("foo").join("bar").join("2.txt"),
1025            &Settings {
1026                fail_early: true,
1027                filter: None,
1028                dry_run: None,
1029                time_filter: None,
1030            },
1031        )
1032        .await;
1033        // should fail with permission denied error
1034        assert!(result.is_err());
1035        let err = result.unwrap_err();
1036        let err_string = format!("{:#}", err);
1037        // verify the error chain includes "Permission denied"
1038        assert!(
1039            err_string.contains("Permission denied") || err_string.contains("permission denied"),
1040            "Error should contain 'Permission denied' but got: {}",
1041            err_string
1042        );
1043        Ok(())
1044    }
1045
1046    mod filter_tests {
1047        use super::*;
1048        use crate::filter::FilterSettings;
1049        /// Test that path-based patterns (with /) work correctly with nested paths.
1050        #[tokio::test]
1051        #[traced_test]
1052        async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
1053            let tmp_dir = testutils::setup_test_dir().await?;
1054            let test_path = tmp_dir.as_path();
1055            // create filter that should only remove files in bar/ directory
1056            let mut filter = FilterSettings::new();
1057            filter.add_include("bar/*.txt").unwrap();
1058            let summary = rm(
1059                &PROGRESS,
1060                &test_path.join("foo"),
1061                &Settings {
1062                    fail_early: false,
1063                    filter: Some(filter),
1064                    dry_run: None,
1065                    time_filter: None,
1066                },
1067            )
1068            .await?;
1069            // should only remove files matching bar/*.txt pattern (bar/1.txt, bar/2.txt, bar/3.txt)
1070            assert_eq!(
1071                summary.files_removed, 3,
1072                "should remove 3 files matching bar/*.txt"
1073            );
1074            // each file is 1 byte ("1", "2", "3")
1075            assert_eq!(summary.bytes_removed, 3, "should report 3 bytes removed");
1076            // verify the right files were removed
1077            assert!(
1078                !test_path.join("foo/bar/1.txt").exists(),
1079                "bar/1.txt should be removed"
1080            );
1081            assert!(
1082                !test_path.join("foo/bar/2.txt").exists(),
1083                "bar/2.txt should be removed"
1084            );
1085            assert!(
1086                !test_path.join("foo/bar/3.txt").exists(),
1087                "bar/3.txt should be removed"
1088            );
1089            // verify files outside the pattern still exist
1090            assert!(
1091                test_path.join("foo/0.txt").exists(),
1092                "0.txt should still exist"
1093            );
1094            Ok(())
1095        }
1096        /// Test that filters are applied to top-level file arguments.
1097        #[tokio::test]
1098        #[traced_test]
1099        async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
1100            let tmp_dir = testutils::setup_test_dir().await?;
1101            let test_path = tmp_dir.as_path();
1102            // create filter that excludes .txt files
1103            let mut filter = FilterSettings::new();
1104            filter.add_exclude("*.txt").unwrap();
1105            let summary = rm(
1106                &PROGRESS,
1107                &test_path.join("foo/0.txt"), // single file source
1108                &Settings {
1109                    fail_early: false,
1110                    filter: Some(filter),
1111                    dry_run: None,
1112                    time_filter: None,
1113                },
1114            )
1115            .await?;
1116            // the file should NOT be removed because it matches the exclude pattern
1117            assert_eq!(
1118                summary.files_removed, 0,
1119                "file matching exclude pattern should not be removed"
1120            );
1121            assert!(
1122                test_path.join("foo/0.txt").exists(),
1123                "excluded file should still exist"
1124            );
1125            Ok(())
1126        }
1127        /// Test that filters apply to root directories with simple exclude patterns.
1128        #[tokio::test]
1129        #[traced_test]
1130        async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
1131            let test_path = testutils::create_temp_dir().await?;
1132            // create a directory that should be excluded
1133            tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
1134            tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
1135            // create filter that excludes *_dir/ directories
1136            let mut filter = FilterSettings::new();
1137            filter.add_exclude("*_dir/").unwrap();
1138            let result = rm(
1139                &PROGRESS,
1140                &test_path.join("excluded_dir"),
1141                &Settings {
1142                    fail_early: false,
1143                    filter: Some(filter),
1144                    dry_run: None,
1145                    time_filter: None,
1146                },
1147            )
1148            .await?;
1149            // directory should NOT be removed because it matches exclude pattern
1150            assert_eq!(
1151                result.directories_removed, 0,
1152                "root directory matching exclude should not be removed"
1153            );
1154            assert!(
1155                test_path.join("excluded_dir").exists(),
1156                "excluded root directory should still exist"
1157            );
1158            Ok(())
1159        }
1160        /// Test that filters apply to root symlinks with simple exclude patterns.
1161        #[tokio::test]
1162        #[traced_test]
1163        async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
1164            let test_path = testutils::create_temp_dir().await?;
1165            // create a target file and a symlink to it
1166            tokio::fs::write(test_path.join("target.txt"), "content").await?;
1167            tokio::fs::symlink(
1168                test_path.join("target.txt"),
1169                test_path.join("excluded_link"),
1170            )
1171            .await?;
1172            // create filter that excludes *_link
1173            let mut filter = FilterSettings::new();
1174            filter.add_exclude("*_link").unwrap();
1175            let result = rm(
1176                &PROGRESS,
1177                &test_path.join("excluded_link"),
1178                &Settings {
1179                    fail_early: false,
1180                    filter: Some(filter),
1181                    dry_run: None,
1182                    time_filter: None,
1183                },
1184            )
1185            .await?;
1186            // symlink should NOT be removed because it matches exclude pattern
1187            assert_eq!(
1188                result.symlinks_removed, 0,
1189                "root symlink matching exclude should not be removed"
1190            );
1191            assert!(
1192                test_path.join("excluded_link").exists(),
1193                "excluded root symlink should still exist"
1194            );
1195            Ok(())
1196        }
1197        /// Test combined include and exclude patterns (exclude takes precedence).
1198        #[tokio::test]
1199        #[traced_test]
1200        async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
1201            let tmp_dir = testutils::setup_test_dir().await?;
1202            let test_path = tmp_dir.as_path();
1203            // test structure from setup_test_dir:
1204            // foo/
1205            //   0.txt
1206            //   bar/ (1.txt, 2.txt, 3.txt)
1207            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
1208            // include all .txt files in bar/, but exclude 2.txt specifically
1209            let mut filter = FilterSettings::new();
1210            filter.add_include("bar/*.txt").unwrap();
1211            filter.add_exclude("bar/2.txt").unwrap();
1212            let summary = rm(
1213                &PROGRESS,
1214                &test_path.join("foo"),
1215                &Settings {
1216                    fail_early: false,
1217                    filter: Some(filter),
1218                    dry_run: None,
1219                    time_filter: None,
1220                },
1221            )
1222            .await?;
1223            // should remove: bar/1.txt, bar/3.txt = 2 files
1224            // should skip: bar/2.txt (excluded by pattern), 0.txt (excluded by default - no match) = 2 files
1225            assert_eq!(summary.files_removed, 2, "should remove 2 files");
1226            assert_eq!(
1227                summary.files_skipped, 2,
1228                "should skip 2 files (bar/2.txt excluded, 0.txt no match)"
1229            );
1230            // verify
1231            assert!(
1232                !test_path.join("foo/bar/1.txt").exists(),
1233                "bar/1.txt should be removed"
1234            );
1235            assert!(
1236                test_path.join("foo/bar/2.txt").exists(),
1237                "bar/2.txt should be excluded"
1238            );
1239            assert!(
1240                !test_path.join("foo/bar/3.txt").exists(),
1241                "bar/3.txt should be removed"
1242            );
1243            Ok(())
1244        }
1245        /// Test that skipped counts accurately reflect what was filtered.
1246        #[tokio::test]
1247        #[traced_test]
1248        async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
1249            let tmp_dir = testutils::setup_test_dir().await?;
1250            let test_path = tmp_dir.as_path();
1251            // test structure from setup_test_dir:
1252            // foo/
1253            //   0.txt
1254            //   bar/ (1.txt, 2.txt, 3.txt)
1255            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
1256            // exclude bar/ directory entirely
1257            let mut filter = FilterSettings::new();
1258            filter.add_exclude("bar/").unwrap();
1259            let summary = rm(
1260                &PROGRESS,
1261                &test_path.join("foo"),
1262                &Settings {
1263                    fail_early: false,
1264                    filter: Some(filter),
1265                    dry_run: None,
1266                    time_filter: None,
1267                },
1268            )
1269            .await?;
1270            // removed: 0.txt, baz/4.txt = 2 files
1271            // removed: baz/5.txt symlink, baz/6.txt symlink = 2 symlinks
1272            // removed: baz = 1 directory (foo cannot be removed because bar still exists)
1273            // skipped: bar directory (1 dir) - contents not counted since whole dir skipped
1274            assert_eq!(summary.files_removed, 2, "should remove 2 files");
1275            assert_eq!(summary.symlinks_removed, 2, "should remove 2 symlinks");
1276            assert_eq!(
1277                summary.directories_removed, 1,
1278                "should remove 1 directory (baz only, foo not empty)"
1279            );
1280            assert_eq!(
1281                summary.directories_skipped, 1,
1282                "should skip 1 directory (bar)"
1283            );
1284            // bar should still exist
1285            assert!(
1286                test_path.join("foo/bar").exists(),
1287                "bar directory should still exist"
1288            );
1289            // foo should still exist (not empty because bar is still there)
1290            assert!(
1291                test_path.join("foo").exists(),
1292                "foo directory should still exist (contains bar)"
1293            );
1294            Ok(())
1295        }
1296        /// Test that empty directories are not removed when they were only traversed to look
1297        /// for matches (regression test for bug where --include='foo' would remove empty dir baz).
1298        #[tokio::test]
1299        #[traced_test]
1300        async fn test_empty_dir_not_removed_when_only_traversed() -> Result<(), anyhow::Error> {
1301            let test_path = testutils::create_temp_dir().await?;
1302            // create structure:
1303            // test/
1304            //   foo (file)
1305            //   bar (file)
1306            //   baz/ (empty directory)
1307            tokio::fs::write(test_path.join("foo"), "content").await?;
1308            tokio::fs::write(test_path.join("bar"), "content").await?;
1309            tokio::fs::create_dir(test_path.join("baz")).await?;
1310            // include only 'foo' file
1311            let mut filter = FilterSettings::new();
1312            filter.add_include("foo").unwrap();
1313            let summary = rm(
1314                &PROGRESS,
1315                &test_path,
1316                &Settings {
1317                    fail_early: false,
1318                    filter: Some(filter),
1319                    dry_run: None,
1320                    time_filter: None,
1321                },
1322            )
1323            .await?;
1324            // only 'foo' should be removed
1325            assert_eq!(summary.files_removed, 1, "should remove only 'foo' file");
1326            assert_eq!(
1327                summary.directories_removed, 0,
1328                "should NOT remove empty 'baz' directory"
1329            );
1330            // verify foo was removed
1331            assert!(!test_path.join("foo").exists(), "foo should be removed");
1332            // verify bar still exists (not matching include pattern)
1333            assert!(test_path.join("bar").exists(), "bar should still exist");
1334            // verify empty baz directory still exists
1335            assert!(
1336                test_path.join("baz").exists(),
1337                "empty baz directory should NOT be removed"
1338            );
1339            Ok(())
1340        }
1341        /// Test that empty directories ARE removed with exclude-only filters.
1342        /// Unlike include filters (where empty dirs are only traversed for matches),
1343        /// exclude-only filters should not prevent removal of empty directories.
1344        #[tokio::test]
1345        #[traced_test]
1346        async fn test_exclude_only_removes_empty_directory() -> Result<(), anyhow::Error> {
1347            let test_path = testutils::create_temp_dir().await?;
1348            // create structure:
1349            // test/
1350            //   foo (file)
1351            //   bar.log (file)
1352            //   baz/ (empty directory)
1353            tokio::fs::write(test_path.join("foo"), "content").await?;
1354            tokio::fs::write(test_path.join("bar.log"), "content").await?;
1355            tokio::fs::create_dir(test_path.join("baz")).await?;
1356            // exclude only .log files
1357            let mut filter = FilterSettings::new();
1358            filter.add_exclude("*.log").unwrap();
1359            let summary = rm(
1360                &PROGRESS,
1361                &test_path,
1362                &Settings {
1363                    fail_early: false,
1364                    filter: Some(filter),
1365                    dry_run: None,
1366                    time_filter: None,
1367                },
1368            )
1369            .await?;
1370            // foo should be removed, bar.log should be skipped, baz/ should be removed
1371            assert_eq!(summary.files_removed, 1, "should remove 'foo'");
1372            assert_eq!(summary.files_skipped, 1, "should skip 'bar.log'");
1373            assert_eq!(
1374                summary.directories_removed, 1,
1375                "should remove empty 'baz' directory"
1376            );
1377            assert!(!test_path.join("foo").exists(), "foo should be removed");
1378            assert!(
1379                test_path.join("bar.log").exists(),
1380                "bar.log should still exist"
1381            );
1382            assert!(
1383                !test_path.join("baz").exists(),
1384                "empty baz directory should be removed"
1385            );
1386            Ok(())
1387        }
1388        /// Test that empty directories are not removed in dry-run mode when only traversed.
1389        #[tokio::test]
1390        #[traced_test]
1391        async fn test_dry_run_empty_dir_not_reported_as_removed() -> Result<(), anyhow::Error> {
1392            let test_path = testutils::create_temp_dir().await?;
1393            // create structure:
1394            // test/
1395            //   foo (file)
1396            //   bar (file)
1397            //   baz/ (empty directory)
1398            tokio::fs::write(test_path.join("foo"), "content").await?;
1399            tokio::fs::write(test_path.join("bar"), "content").await?;
1400            tokio::fs::create_dir(test_path.join("baz")).await?;
1401            // include only 'foo' file
1402            let mut filter = FilterSettings::new();
1403            filter.add_include("foo").unwrap();
1404            let summary = rm(
1405                &PROGRESS,
1406                &test_path,
1407                &Settings {
1408                    fail_early: false,
1409                    filter: Some(filter),
1410                    dry_run: Some(DryRunMode::Explain),
1411                    time_filter: None,
1412                },
1413            )
1414            .await?;
1415            // only 'foo' should be reported as would-be-removed
1416            assert_eq!(
1417                summary.files_removed, 1,
1418                "should report only 'foo' would be removed"
1419            );
1420            assert_eq!(
1421                summary.directories_removed, 0,
1422                "should NOT report empty 'baz' would be removed"
1423            );
1424            // verify nothing was actually removed (dry-run mode)
1425            assert!(test_path.join("foo").exists(), "foo should still exist");
1426            assert!(test_path.join("bar").exists(), "bar should still exist");
1427            assert!(test_path.join("baz").exists(), "baz should still exist");
1428            Ok(())
1429        }
1430        /// Test that an empty directory directly matching an include pattern IS removed.
1431        /// Unlike traversed-only directories, directly matched ones are explicit targets.
1432        #[tokio::test]
1433        #[traced_test]
1434        async fn test_include_directly_matched_empty_dir_is_removed() -> Result<(), anyhow::Error> {
1435            let test_path = testutils::create_temp_dir().await?;
1436            // create structure:
1437            // test/
1438            //   foo (file)
1439            //   baz/ (empty directory)
1440            tokio::fs::write(test_path.join("foo"), "content").await?;
1441            tokio::fs::create_dir(test_path.join("baz")).await?;
1442            // include pattern that directly matches the directory
1443            let mut filter = FilterSettings::new();
1444            filter.add_include("baz/").unwrap();
1445            let summary = rm(
1446                &PROGRESS,
1447                &test_path,
1448                &Settings {
1449                    fail_early: false,
1450                    filter: Some(filter),
1451                    dry_run: None,
1452                    time_filter: None,
1453                },
1454            )
1455            .await?;
1456            assert_eq!(
1457                summary.directories_removed, 1,
1458                "should remove directly matched empty 'baz' directory"
1459            );
1460            assert_eq!(summary.files_removed, 0, "should not remove 'foo'");
1461            assert!(test_path.join("foo").exists(), "foo should still exist");
1462            assert!(
1463                !test_path.join("baz").exists(),
1464                "directly matched empty baz directory should be removed"
1465            );
1466            Ok(())
1467        }
1468    }
1469    mod dry_run_tests {
1470        use super::*;
1471        use crate::filter::FilterSettings;
1472
1473        #[tokio::test(flavor = "current_thread")]
1474        async fn dry_run_rechecks_a_directory_hint_before_previewing_an_included_file()
1475        -> Result<(), anyhow::Error> {
1476            let root = testutils::create_temp_dir().await?;
1477            let target = root.join("target");
1478            tokio::fs::create_dir(&target).await?;
1479            tokio::fs::write(target.join("node"), "CURRENT").await?;
1480            let mut filter = FilterSettings::new();
1481            filter.add_exclude("node/")?;
1482            assert!(!matches!(
1483                filter.should_include(std::path::Path::new("node"), true),
1484                crate::filter::FilterResult::Included
1485            ));
1486            assert!(matches!(
1487                filter.should_include(std::path::Path::new("node"), false),
1488                crate::filter::FilterResult::Included
1489            ));
1490            let settings = Settings {
1491                fail_early: false,
1492                filter: Some(filter),
1493                dry_run: Some(DryRunMode::Brief),
1494                time_filter: None,
1495            };
1496            let admission = testutils::AdmissionLimit::new().await;
1497            admission.set_files_in_flight(1);
1498            let target_dir =
1499                Arc::new(Dir::open_root_dir(&target, false, congestion::Side::Source).await?);
1500            let visitor = Arc::new(RmVisitor {
1501                protection: None,
1502                prog_track: &PROGRESS,
1503                settings,
1504            });
1505            let root_cx = EntryCx::root(
1506                Arc::clone(&target_dir),
1507                std::ffi::OsString::from("target"),
1508                target.clone(),
1509                &PROGRESS,
1510            );
1511            let result = admission
1512                .run_with_timeout(
1513                    std::time::Duration::from_secs(20),
1514                    crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
1515                        visitor,
1516                        target_dir,
1517                        &root_cx,
1518                        &(),
1519                        vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
1520                    )),
1521                )
1522                .await
1523                .context("rm dry-run hint recheck did not finish at a cap of one")??;
1524            let returned = admission
1525                .run_with_timeout(
1526                    std::time::Duration::from_secs(20),
1527                    throttle::pending_meta_permit(),
1528                )
1529                .await
1530                .context("rm dry-run hint recheck did not return pending-meta capacity")?;
1531            drop(returned);
1532            let (summary, processed) = result;
1533            assert!(processed.names().is_none());
1534            assert_eq!(summary.files_removed, 1);
1535            assert_eq!(summary.directories_skipped, 0);
1536            assert_eq!(
1537                tokio::fs::read_to_string(target.join("node")).await?,
1538                "CURRENT"
1539            );
1540            Ok(())
1541        }
1542
1543        /// Test that dry-run mode doesn't modify permissions on read-only directories.
1544        #[tokio::test]
1545        #[traced_test]
1546        async fn test_dry_run_preserves_readonly_permissions() -> Result<(), anyhow::Error> {
1547            let tmp_dir = testutils::setup_test_dir().await?;
1548            let test_path = tmp_dir.as_path();
1549            let readonly_dir = test_path.join("foo/bar");
1550            // make the directory read-only
1551            tokio::fs::set_permissions(&readonly_dir, std::fs::Permissions::from_mode(0o555))
1552                .await?;
1553            // verify it's read-only
1554            let before_mode = tokio::fs::metadata(&readonly_dir)
1555                .await?
1556                .permissions()
1557                .mode()
1558                & 0o777;
1559            assert_eq!(
1560                before_mode, 0o555,
1561                "directory should be read-only before dry-run"
1562            );
1563            let summary = rm(
1564                &PROGRESS,
1565                &readonly_dir,
1566                &Settings {
1567                    fail_early: false,
1568                    filter: None,
1569                    dry_run: Some(DryRunMode::Brief),
1570                    time_filter: None,
1571                },
1572            )
1573            .await?;
1574            // verify the directory still exists (dry-run shouldn't remove it)
1575            assert!(
1576                readonly_dir.exists(),
1577                "directory should still exist after dry-run"
1578            );
1579            // verify permissions weren't changed
1580            let after_mode = tokio::fs::metadata(&readonly_dir)
1581                .await?
1582                .permissions()
1583                .mode()
1584                & 0o777;
1585            assert_eq!(
1586                after_mode, 0o555,
1587                "dry-run should not modify directory permissions"
1588            );
1589            // verify summary shows what would be removed
1590            assert!(
1591                summary.directories_removed > 0 || summary.files_removed > 0,
1592                "dry-run should report what would be removed"
1593            );
1594            Ok(())
1595        }
1596        /// Test that dry-run mode with filtering correctly handles directories that
1597        /// wouldn't be empty after filtering.
1598        #[tokio::test]
1599        #[traced_test]
1600        async fn test_dry_run_with_filter_non_empty_directory() -> Result<(), anyhow::Error> {
1601            let tmp_dir = testutils::setup_test_dir().await?;
1602            let test_path = tmp_dir.as_path();
1603            // test structure from setup_test_dir:
1604            // foo/
1605            //   0.txt
1606            //   bar/ (1.txt, 2.txt, 3.txt)
1607            //   baz/ (4.txt, 5.txt symlink, 6.txt symlink)
1608            // exclude bar/ - so foo would not be empty after removing (bar still there)
1609            let mut filter = crate::filter::FilterSettings::new();
1610            filter.add_exclude("bar/").unwrap();
1611            let summary = rm(
1612                &PROGRESS,
1613                &test_path.join("foo"),
1614                &Settings {
1615                    fail_early: false,
1616                    filter: Some(filter),
1617                    dry_run: Some(DryRunMode::Brief),
1618                    time_filter: None,
1619                },
1620            )
1621            .await?;
1622            // dry-run shouldn't actually remove anything
1623            assert!(
1624                test_path.join("foo").exists(),
1625                "foo should still exist after dry-run"
1626            );
1627            // verify summary reflects what WOULD happen:
1628            // - files: 0.txt, baz/4.txt would be removed = 2
1629            // - symlinks: baz/5.txt, baz/6.txt would be removed = 2
1630            // - directories: baz would be removed, but NOT foo (bar is skipped, so foo not empty)
1631            // - skipped: bar directory = 1
1632            assert_eq!(
1633                summary.files_removed, 2,
1634                "should report 2 files would be removed"
1635            );
1636            assert_eq!(
1637                summary.symlinks_removed, 2,
1638                "should report 2 symlinks would be removed"
1639            );
1640            assert_eq!(
1641                summary.directories_removed, 1,
1642                "should report only baz (not foo) would be removed"
1643            );
1644            assert_eq!(
1645                summary.directories_skipped, 1,
1646                "should report bar directory skipped"
1647            );
1648            Ok(())
1649        }
1650        /// Test that dry-run with exclude-only filter correctly reports empty directories
1651        /// as would-be-removed (unlike include filters where empty dirs are only traversed).
1652        #[tokio::test]
1653        #[traced_test]
1654        async fn test_dry_run_exclude_only_reports_empty_dir_removed() -> Result<(), anyhow::Error>
1655        {
1656            let test_path = testutils::create_temp_dir().await?;
1657            // create structure:
1658            // test/
1659            //   foo (file)
1660            //   bar.log (file)
1661            //   baz/ (empty directory)
1662            tokio::fs::write(test_path.join("foo"), "content").await?;
1663            tokio::fs::write(test_path.join("bar.log"), "content").await?;
1664            tokio::fs::create_dir(test_path.join("baz")).await?;
1665            // exclude only .log files
1666            let mut filter = FilterSettings::new();
1667            filter.add_exclude("*.log").unwrap();
1668            let summary = rm(
1669                &PROGRESS,
1670                &test_path,
1671                &Settings {
1672                    fail_early: false,
1673                    filter: Some(filter),
1674                    dry_run: Some(DryRunMode::Explain),
1675                    time_filter: None,
1676                },
1677            )
1678            .await?;
1679            // foo should be reported as would-be-removed, bar.log skipped, baz/ removed
1680            assert_eq!(
1681                summary.files_removed, 1,
1682                "should report 'foo' would be removed"
1683            );
1684            assert_eq!(
1685                summary.files_skipped, 1,
1686                "should report 'bar.log' would be skipped"
1687            );
1688            assert_eq!(
1689                summary.directories_removed, 1,
1690                "should report empty 'baz' directory would be removed"
1691            );
1692            // verify nothing was actually removed (dry-run mode)
1693            assert!(test_path.join("foo").exists(), "foo should still exist");
1694            assert!(
1695                test_path.join("bar.log").exists(),
1696                "bar.log should still exist"
1697            );
1698            assert!(test_path.join("baz").exists(), "baz should still exist");
1699            Ok(())
1700        }
1701        /// Test that dry-run correctly reports removal of an empty directory that directly
1702        /// matches an include pattern (not merely traversed).
1703        #[tokio::test]
1704        #[traced_test]
1705        async fn test_dry_run_include_directly_matched_empty_dir_reported()
1706        -> Result<(), anyhow::Error> {
1707            let test_path = testutils::create_temp_dir().await?;
1708            // create structure:
1709            // test/
1710            //   foo (file)
1711            //   baz/ (empty directory)
1712            tokio::fs::write(test_path.join("foo"), "content").await?;
1713            tokio::fs::create_dir(test_path.join("baz")).await?;
1714            // include pattern that directly matches the directory
1715            let mut filter = FilterSettings::new();
1716            filter.add_include("baz/").unwrap();
1717            let summary = rm(
1718                &PROGRESS,
1719                &test_path,
1720                &Settings {
1721                    fail_early: false,
1722                    filter: Some(filter),
1723                    dry_run: Some(DryRunMode::Explain),
1724                    time_filter: None,
1725                },
1726            )
1727            .await?;
1728            assert_eq!(
1729                summary.directories_removed, 1,
1730                "should report directly matched empty 'baz' would be removed"
1731            );
1732            assert_eq!(summary.files_removed, 0, "should not report 'foo'");
1733            // verify nothing was actually removed (dry-run mode)
1734            assert!(test_path.join("foo").exists(), "foo should still exist");
1735            assert!(test_path.join("baz").exists(), "baz should still exist");
1736            Ok(())
1737        }
1738    }
1739    mod time_filter_tests {
1740        use super::*;
1741        use crate::filter::TimeFilter;
1742
1743        fn set_mtime_age(path: &std::path::Path, age: std::time::Duration) -> anyhow::Result<()> {
1744            let past = filetime::FileTime::from_system_time(std::time::SystemTime::now() - age);
1745            filetime::set_file_mtime(path, past)?;
1746            Ok(())
1747        }
1748
1749        /// File with mtime older than threshold is removed.
1750        #[tokio::test]
1751        #[traced_test]
1752        async fn removes_files_older_than_modified_before() -> Result<(), anyhow::Error> {
1753            let test_path = testutils::create_temp_dir().await?;
1754            let file = test_path.join("old.txt");
1755            tokio::fs::write(&file, "x").await?;
1756            set_mtime_age(&file, std::time::Duration::from_secs(7200))?;
1757            // age test_path so the root dir passes its own time filter check
1758            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1759            let summary = rm(
1760                &PROGRESS,
1761                &test_path,
1762                &Settings {
1763                    fail_early: false,
1764                    filter: None,
1765                    time_filter: Some(TimeFilter {
1766                        modified_before: Some(std::time::Duration::from_secs(3600)),
1767                        created_before: None,
1768                    }),
1769                    dry_run: None,
1770                },
1771            )
1772            .await?;
1773            assert_eq!(summary.files_removed, 1, "old file should be removed");
1774            assert_eq!(summary.files_skipped, 0);
1775            assert!(!file.exists(), "old.txt should be removed");
1776            Ok(())
1777        }
1778
1779        /// File with mtime newer than threshold is skipped.
1780        #[tokio::test]
1781        #[traced_test]
1782        async fn keeps_files_newer_than_modified_before() -> Result<(), anyhow::Error> {
1783            let test_path = testutils::create_temp_dir().await?;
1784            let file = test_path.join("new.txt");
1785            tokio::fs::write(&file, "x").await?;
1786            set_mtime_age(&file, std::time::Duration::from_secs(60))?;
1787            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1788            let summary = rm(
1789                &PROGRESS,
1790                &test_path,
1791                &Settings {
1792                    fail_early: false,
1793                    filter: None,
1794                    time_filter: Some(TimeFilter {
1795                        modified_before: Some(std::time::Duration::from_secs(3600)),
1796                        created_before: None,
1797                    }),
1798                    dry_run: None,
1799                },
1800            )
1801            .await?;
1802            assert_eq!(summary.files_removed, 0, "new file should not be removed");
1803            assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1804            assert!(file.exists(), "new.txt should still exist");
1805            Ok(())
1806        }
1807
1808        /// A fresh subdirectory is descended into (children are handled individually),
1809        /// but the fresh_dir itself is not removed because its own mtime is too recent.
1810        #[tokio::test]
1811        #[traced_test]
1812        async fn fresh_subdirectory_is_descended_but_not_removed() -> Result<(), anyhow::Error> {
1813            let test_path = testutils::create_temp_dir().await?;
1814            let old_file = test_path.join("old.txt");
1815            let fresh_dir = test_path.join("fresh_dir");
1816            let fresh_child = fresh_dir.join("fresh_child.txt");
1817            let old_child = fresh_dir.join("old_child.txt");
1818            tokio::fs::write(&old_file, "x").await?;
1819            tokio::fs::create_dir(&fresh_dir).await?;
1820            tokio::fs::write(&fresh_child, "x").await?;
1821            tokio::fs::write(&old_child, "x").await?;
1822            set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
1823            set_mtime_age(&old_child, std::time::Duration::from_secs(7200))?;
1824            // fresh_child keeps its recent mtime; so does fresh_dir (we took the mtime
1825            // snapshot before remove_file mutates it)
1826            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1827            let summary = rm(
1828                &PROGRESS,
1829                &test_path,
1830                &Settings {
1831                    fail_early: false,
1832                    filter: None,
1833                    time_filter: Some(TimeFilter {
1834                        modified_before: Some(std::time::Duration::from_secs(3600)),
1835                        created_before: None,
1836                    }),
1837                    dry_run: None,
1838                },
1839            )
1840            .await?;
1841            // we descend into fresh_dir: old_child removed, fresh_child skipped
1842            assert_eq!(summary.files_removed, 2, "old.txt and old_child removed");
1843            assert_eq!(
1844                summary.files_skipped, 1,
1845                "fresh_child skipped inside fresh_dir"
1846            );
1847            assert_eq!(
1848                summary.directories_skipped, 1,
1849                "fresh_dir itself is skipped at removal time"
1850            );
1851            assert_eq!(
1852                summary.directories_removed, 0,
1853                "root survives because fresh_dir is still inside it"
1854            );
1855            assert!(!old_file.exists());
1856            assert!(!old_child.exists(), "old_child inside fresh_dir removed");
1857            assert!(
1858                fresh_dir.exists(),
1859                "fresh_dir kept despite its old child being removed"
1860            );
1861            assert!(fresh_child.exists(), "fresh_child inside fresh_dir kept");
1862            Ok(())
1863        }
1864
1865        /// An old directory that still holds a new (skipped) file survives as non-empty.
1866        /// The leftover-dir case is not treated as an error.
1867        #[tokio::test]
1868        #[traced_test]
1869        async fn old_dir_with_new_file_leaves_non_empty_dir_without_error()
1870        -> Result<(), anyhow::Error> {
1871            let test_path = testutils::create_temp_dir().await?;
1872            let old_dir = test_path.join("old_dir");
1873            tokio::fs::create_dir(&old_dir).await?;
1874            let new_file = old_dir.join("new.txt");
1875            tokio::fs::write(&new_file, "x").await?;
1876            set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
1877            set_mtime_age(&old_dir, std::time::Duration::from_secs(7200))?;
1878            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1879            tokio::fs::set_permissions(&old_dir, std::fs::Permissions::from_mode(0o555)).await?;
1880            let result = rm(
1881                &PROGRESS,
1882                &test_path,
1883                &Settings {
1884                    fail_early: false,
1885                    filter: None,
1886                    time_filter: Some(TimeFilter {
1887                        modified_before: Some(std::time::Duration::from_secs(3600)),
1888                        created_before: None,
1889                    }),
1890                    dry_run: None,
1891                },
1892            )
1893            .await;
1894            let summary = result.expect("ENOTEMPTY should not surface as an error");
1895            assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1896            assert_eq!(
1897                summary.directories_removed, 0,
1898                "old_dir cannot be removed while new.txt remains"
1899            );
1900            assert!(old_dir.exists(), "old_dir should still exist");
1901            assert!(new_file.exists(), "new.txt should still exist");
1902            assert_eq!(
1903                tokio::fs::metadata(&old_dir).await?.permissions().mode() & 0o7777,
1904                0o555,
1905                "ENOTEMPTY retention did not restore the original directory mode"
1906            );
1907            // the 'left intact' message is logged at info level
1908            assert!(
1909                logs_contain("not empty after filtering, leaving it intact"),
1910                "should log ENOTEMPTY case at info"
1911            );
1912            Ok(())
1913        }
1914
1915        /// An old, already-empty directory is removed by the time filter run.
1916        #[tokio::test]
1917        #[traced_test]
1918        async fn old_empty_directory_is_removed() -> Result<(), anyhow::Error> {
1919            let test_path = testutils::create_temp_dir().await?;
1920            let old_empty = test_path.join("old_empty");
1921            tokio::fs::create_dir(&old_empty).await?;
1922            set_mtime_age(&old_empty, std::time::Duration::from_secs(7200))?;
1923            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1924            let summary = rm(
1925                &PROGRESS,
1926                &test_path,
1927                &Settings {
1928                    fail_early: false,
1929                    filter: None,
1930                    time_filter: Some(TimeFilter {
1931                        modified_before: Some(std::time::Duration::from_secs(3600)),
1932                        created_before: None,
1933                    }),
1934                    dry_run: None,
1935                },
1936            )
1937            .await?;
1938            // both old_empty and test_path itself are removed
1939            assert_eq!(summary.directories_removed, 2);
1940            assert!(!old_empty.exists());
1941            assert!(!test_path.exists());
1942            Ok(())
1943        }
1944
1945        /// Time filter combines with glob exclude — both must pass for removal.
1946        #[tokio::test]
1947        #[traced_test]
1948        async fn time_filter_combines_with_glob_exclude() -> Result<(), anyhow::Error> {
1949            let test_path = testutils::create_temp_dir().await?;
1950            let old_keep = test_path.join("keep.log");
1951            let old_drop = test_path.join("drop.txt");
1952            let new_drop = test_path.join("recent.txt");
1953            tokio::fs::write(&old_keep, "x").await?;
1954            tokio::fs::write(&old_drop, "x").await?;
1955            tokio::fs::write(&new_drop, "x").await?;
1956            set_mtime_age(&old_keep, std::time::Duration::from_secs(7200))?;
1957            set_mtime_age(&old_drop, std::time::Duration::from_secs(7200))?;
1958            set_mtime_age(&new_drop, std::time::Duration::from_secs(60))?;
1959            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1960            let mut filter = crate::filter::FilterSettings::new();
1961            filter.add_exclude("*.log").unwrap();
1962            let summary = rm(
1963                &PROGRESS,
1964                &test_path,
1965                &Settings {
1966                    fail_early: false,
1967                    filter: Some(filter),
1968                    time_filter: Some(TimeFilter {
1969                        modified_before: Some(std::time::Duration::from_secs(3600)),
1970                        created_before: None,
1971                    }),
1972                    dry_run: None,
1973                },
1974            )
1975            .await?;
1976            // only old_drop passes both filters
1977            assert_eq!(summary.files_removed, 1, "only old_drop should be removed");
1978            assert_eq!(
1979                summary.files_skipped, 2,
1980                "old_keep and recent_drop should be skipped"
1981            );
1982            assert!(
1983                old_keep.exists(),
1984                "keep.log excluded by glob, should remain"
1985            );
1986            assert!(!old_drop.exists(), "drop.txt should be removed");
1987            assert!(new_drop.exists(), "recent.txt should remain (too new)");
1988            Ok(())
1989        }
1990
1991        /// Dry-run with time filter previews removal without modifying files.
1992        #[tokio::test]
1993        #[traced_test]
1994        async fn time_filter_with_dry_run() -> Result<(), anyhow::Error> {
1995            let test_path = testutils::create_temp_dir().await?;
1996            let old_file = test_path.join("old.txt");
1997            let new_file = test_path.join("new.txt");
1998            tokio::fs::write(&old_file, "x").await?;
1999            tokio::fs::write(&new_file, "x").await?;
2000            set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
2001            set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
2002            set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
2003            let summary = rm(
2004                &PROGRESS,
2005                &test_path,
2006                &Settings {
2007                    fail_early: false,
2008                    filter: None,
2009                    time_filter: Some(TimeFilter {
2010                        modified_before: Some(std::time::Duration::from_secs(3600)),
2011                        created_before: None,
2012                    }),
2013                    dry_run: Some(DryRunMode::Explain),
2014                },
2015            )
2016            .await?;
2017            assert_eq!(
2018                summary.files_removed, 1,
2019                "should report old file would be removed"
2020            );
2021            assert_eq!(
2022                summary.files_skipped, 1,
2023                "should report new file would be skipped"
2024            );
2025            assert!(old_file.exists(), "old.txt should still exist (dry-run)");
2026            assert!(new_file.exists(), "new.txt should still exist (dry-run)");
2027            Ok(())
2028        }
2029
2030        /// A fresh top-level directory is traversed (its old children are removed),
2031        /// but the root itself is not removed because its own mtime is too recent.
2032        #[tokio::test]
2033        #[traced_test]
2034        async fn fresh_top_level_directory_is_traversed_but_not_removed()
2035        -> Result<(), anyhow::Error> {
2036            let test_path = testutils::create_temp_dir().await?;
2037            let old_inside = test_path.join("old.txt");
2038            tokio::fs::write(&old_inside, "x").await?;
2039            set_mtime_age(&old_inside, std::time::Duration::from_secs(7200))?;
2040            // test_path itself is left fresh (recent mtime)
2041            tokio::fs::set_permissions(&test_path, std::fs::Permissions::from_mode(0o555)).await?;
2042            let summary = rm(
2043                &PROGRESS,
2044                &test_path,
2045                &Settings {
2046                    fail_early: false,
2047                    filter: None,
2048                    time_filter: Some(TimeFilter {
2049                        modified_before: Some(std::time::Duration::from_secs(3600)),
2050                        created_before: None,
2051                    }),
2052                    dry_run: None,
2053                },
2054            )
2055            .await?;
2056            assert_eq!(
2057                summary.files_removed, 1,
2058                "old child should be removed despite fresh parent"
2059            );
2060            assert_eq!(
2061                summary.directories_skipped, 1,
2062                "fresh root itself is skipped at removal time"
2063            );
2064            assert_eq!(
2065                summary.directories_removed, 0,
2066                "fresh root must not be removed"
2067            );
2068            assert!(test_path.exists(), "fresh root should still exist");
2069            assert!(!old_inside.exists(), "old child should be gone");
2070            assert_eq!(
2071                tokio::fs::metadata(&test_path).await?.permissions().mode() & 0o7777,
2072                0o555,
2073                "time-filter retention did not restore the original directory mode"
2074            );
2075            Ok(())
2076        }
2077
2078        /// Time filter on a single-file root argument increments skip when too new.
2079        #[tokio::test]
2080        #[traced_test]
2081        async fn time_filter_on_root_file_argument() -> Result<(), anyhow::Error> {
2082            let test_path = testutils::create_temp_dir().await?;
2083            let new_file = test_path.join("new.txt");
2084            tokio::fs::write(&new_file, "x").await?;
2085            set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
2086            let summary = rm(
2087                &PROGRESS,
2088                &new_file,
2089                &Settings {
2090                    fail_early: false,
2091                    filter: None,
2092                    time_filter: Some(TimeFilter {
2093                        modified_before: Some(std::time::Duration::from_secs(3600)),
2094                        created_before: None,
2095                    }),
2096                    dry_run: None,
2097                },
2098            )
2099            .await?;
2100            assert_eq!(summary.files_removed, 0);
2101            assert_eq!(
2102                summary.files_skipped, 1,
2103                "root file too new should be skipped"
2104            );
2105            assert!(new_file.exists(), "root file should still exist");
2106            Ok(())
2107        }
2108    }
2109
2110    /// Stress tests exercising max-files-in-flight saturation during rm.
2111    mod max_files_in_flight_tests {
2112        use super::*;
2113
2114        /// Public root setup must reserve metadata capacity before opening the operand parent or
2115        /// performing the fd-based root filter probe. Otherwise many CLI operands can bypass the
2116        /// shared driver's later admission point concurrently.
2117        #[tokio::test]
2118        async fn filtered_root_waits_for_admission_before_setup() -> Result<(), anyhow::Error> {
2119            let root = testutils::create_temp_dir().await?;
2120            let path = root.join("victim");
2121            tokio::fs::write(&path, b"x").await?;
2122            let mut filter = crate::filter::FilterSettings::new();
2123            filter.add_exclude("victim")?;
2124            let settings = Settings {
2125                fail_early: true,
2126                filter: Some(filter),
2127                dry_run: None,
2128                time_filter: None,
2129            };
2130            let admission = testutils::AdmissionLimit::new().await;
2131            admission.set_files_in_flight(1);
2132            let stat_resource =
2133                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
2134            admission.set_max_ops_in_flight(stat_resource, 1);
2135            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
2136            let operation = rm(&PROGRESS, &path, &settings);
2137            tokio::pin!(operation);
2138            let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
2139            let mut second_permit = Box::pin(throttle::pending_meta_permit());
2140            let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
2141            drop(second_permit);
2142            drop(held_stat);
2143            let result = admission
2144                .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
2145                .await;
2146            assert!(
2147                stopped_at_stat_gate,
2148                "rm root did not reach the held stat gate"
2149            );
2150            let summary =
2151                result.context("rm root did not resume after stat capacity was released")??;
2152            assert!(
2153                !setup_bypassed_admission,
2154                "rm performed root setup before pending-metadata admission"
2155            );
2156            assert_eq!(summary.files_skipped, 1);
2157            Ok(())
2158        }
2159
2160        /// Wide rm: many files with a very low files-in-flight limit.
2161        /// Verifies all files are removed correctly under permit saturation.
2162        #[tokio::test]
2163        #[traced_test]
2164        async fn wide_rm_under_files_in_flight_saturation() -> Result<(), anyhow::Error> {
2165            let test_path = testutils::create_temp_dir().await?;
2166            let file_count = 200;
2167            for i in 0..file_count {
2168                tokio::fs::write(
2169                    test_path.join(format!("{}.txt", i)),
2170                    format!("content-{}", i),
2171                )
2172                .await?;
2173            }
2174            // set a very low limit to force permit contention
2175            let admission = testutils::AdmissionLimit::new().await;
2176            admission.set_files_in_flight(4);
2177            let summary = admission
2178                .run_with_timeout(
2179                    std::time::Duration::from_secs(30),
2180                    rm(
2181                        &PROGRESS,
2182                        &test_path,
2183                        &Settings {
2184                            fail_early: true,
2185                            filter: None,
2186                            dry_run: None,
2187                            time_filter: None,
2188                        },
2189                    ),
2190                )
2191                .await
2192                .context("rm timed out — possible deadlock")??;
2193            assert_eq!(summary.files_removed, file_count);
2194            assert_eq!(summary.directories_removed, 1);
2195            assert!(!test_path.exists());
2196            Ok(())
2197        }
2198
2199        /// Deep + wide rm: a directory tree deeper than the files-in-flight limit, with files at every
2200        /// level. Verifies directories do not retain leaf admission across recursion.
2201        #[tokio::test]
2202        #[traced_test]
2203        async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
2204        -> Result<(), anyhow::Error> {
2205            let test_path = testutils::create_temp_dir().await?;
2206            let depth = 20;
2207            let files_per_level = 5;
2208            let limit = 1;
2209            // create a directory chain deeper than the permit limit, with files at each level
2210            let mut dir = test_path.clone();
2211            for level in 0..depth {
2212                tokio::fs::create_dir_all(&dir).await?;
2213                for f in 0..files_per_level {
2214                    tokio::fs::write(
2215                        dir.join(format!("f{}_{}.txt", level, f)),
2216                        format!("L{}F{}", level, f),
2217                    )
2218                    .await?;
2219                }
2220                dir = dir.join(format!("d{}", level));
2221            }
2222            let admission = testutils::AdmissionLimit::new().await;
2223            admission.set_files_in_flight(limit);
2224            let summary = admission
2225                .run_with_timeout(
2226                    std::time::Duration::from_secs(30),
2227                    rm(
2228                        &PROGRESS,
2229                        &test_path,
2230                        &Settings {
2231                            fail_early: true,
2232                            filter: None,
2233                            dry_run: None,
2234                            time_filter: None,
2235                        },
2236                    ),
2237                )
2238                .await
2239                .context("rm timed out — possible deadlock")?
2240                .context("rm failed")?;
2241            assert_eq!(summary.files_removed, depth * files_per_level);
2242            assert_eq!(summary.directories_removed, depth);
2243            assert!(!test_path.exists());
2244            Ok(())
2245        }
2246
2247        /// Regression for the hold-and-wait deadlock when a getdents leaf-hint entry is actually a
2248        /// directory (the DT_UNKNOWN edge, or a swap between `getdents` and the authoritative
2249        /// `child()`). The walk pre-acquires a `pending_meta` permit for every possible leaf; if such
2250        /// an entry turns out to be a directory, the spawned task must DROP that permit before
2251        /// recursing — otherwise it holds the permit AND its children block trying to acquire one,
2252        /// and with a saturated pool the whole walk hangs.
2253        ///
2254        /// This reproduces that exact shape deterministically by driving the `RmVisitor` through the
2255        /// driver's [`process_entry`] with the one-and-only permit pre-acquired by the caller
2256        /// (mirroring the spawn loop's hinted-leaf pre-acquire). With the bug, the directory branch
2257        /// would hold that permit while recursing into the directory, whose child file then blocks
2258        /// forever on `pending_meta` (pool size 1, already held by us) — the timeout fires. With the
2259        /// fix, the driver's single drop-before-recurse site releases the permit on the directory
2260        /// path before recursing, the child acquires it, and removal completes well within the
2261        /// timeout.
2262        #[tokio::test]
2263        #[traced_test]
2264        async fn hinted_leaf_that_is_dir_drops_permit_before_recursion() -> anyhow::Result<()> {
2265            let root = testutils::create_temp_dir().await?;
2266            // `d` is a directory (the authoritative type) holding one child file `c`.
2267            let dir_path = root.join("d");
2268            tokio::fs::create_dir(&dir_path).await?;
2269            tokio::fs::write(dir_path.join("c"), b"x").await?;
2270            // size the pending-meta pool to a single permit so a held-across-recursion permit
2271            // strands the child's pre-acquire — the saturation the fd-walk must tolerate.
2272            let admission = testutils::AdmissionLimit::new().await;
2273            admission.set_files_in_flight(1);
2274            // open the container of `d` and classify `d` itself: an authoritative directory.
2275            let parent = Dir::open_parent_dir(&root, congestion::Side::Source)
2276                .await
2277                .context("open parent dir")?;
2278            let parent = Arc::new(parent.into_tree());
2279            let name = std::ffi::OsStr::new("d");
2280            let handle = parent.child(name).await.context("classify d")?;
2281            assert_eq!(
2282                handle.kind(),
2283                EntryKind::Dir,
2284                "fixture `d` must be a directory"
2285            );
2286            drop(handle);
2287            let settings = Settings {
2288                fail_early: true,
2289                filter: None,
2290                dry_run: None,
2291                time_filter: None,
2292            };
2293            let visitor = Arc::new(RmVisitor {
2294                protection: None,
2295                prog_track: &PROGRESS,
2296                settings: settings.clone(),
2297            });
2298            let cx = EntryCx::root(
2299                Arc::clone(&parent),
2300                name.to_owned(),
2301                dir_path.clone(),
2302                &PROGRESS,
2303            );
2304            // pre-acquire the single permit exactly as the spawn loop does for a hinted leaf, and
2305            // hand it to `process_entry`. The fix drops it before recursing into the directory.
2306            let permit =
2307                crate::walk::preacquire_leaf_permit(PermitKind::PendingMeta, Some(EntryKind::File))
2308                    .await;
2309            assert!(permit.is_some(), "the pre-acquire must take the one permit");
2310            let result = admission
2311                .run_with_timeout(
2312                    std::time::Duration::from_secs(20),
2313                    process_entry(visitor, cx, (), permit),
2314                )
2315                .await;
2316            let summary = result
2317                .context(
2318                    "process_entry hung — leaf permit held across directory recursion (deadlock)",
2319                )?
2320                .map_err(|e| e.source)?;
2321            assert_eq!(summary.files_removed, 1, "child file should be removed");
2322            assert_eq!(
2323                summary.directories_removed, 1,
2324                "directory should be removed"
2325            );
2326            assert!(!dir_path.exists(), "directory `d` should be gone");
2327            Ok(())
2328        }
2329    }
2330
2331    /// TOCTOU race tests for the fd-based recursive removal.
2332    mod race_tests {
2333        use super::*;
2334
2335        static RACE_PROGRESS: std::sync::LazyLock<progress::Progress> =
2336            std::sync::LazyLock::new(progress::Progress::new);
2337
2338        #[tokio::test]
2339        async fn non_directory_action_cannot_remove_directory_replacement() -> anyhow::Result<()> {
2340            let tmp = tempfile::tempdir()?;
2341            let entry = tmp.path().join("entry");
2342            let original = tmp.path().join("original");
2343            tokio::fs::write(&entry, b"original").await?;
2344            let parent = Arc::new(
2345                Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2346                    .await?
2347                    .into_tree(),
2348            );
2349            let handle = parent.child(OsStr::new("entry")).await?;
2350            let leaf = AdmittedLeaf::try_new(handle, None)
2351                .map_err(|_| anyhow::anyhow!("file fixture classified as a directory"))?;
2352            tokio::fs::rename(&entry, &original).await?;
2353            tokio::fs::create_dir(&entry).await?;
2354            tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2355            let visitor = RmVisitor {
2356                protection: None,
2357                prog_track: &RACE_PROGRESS,
2358                settings: Settings {
2359                    fail_early: true,
2360                    filter: None,
2361                    time_filter: None,
2362                    dry_run: None,
2363                },
2364            };
2365            let cx = EntryCx::root(
2366                parent,
2367                OsStr::new("entry").to_owned(),
2368                entry.clone(),
2369                &RACE_PROGRESS,
2370            )
2371            .with_relative_path(std::path::PathBuf::from("entry"));
2372            let error = visitor
2373                .visit_leaf(&cx, &(), leaf)
2374                .await
2375                .expect_err("a nondirectory unlink must reject a replacement directory");
2376            assert!(format!("{:#}", error.source).contains("failed removing"));
2377            assert_eq!(tokio::fs::read(&original).await?, b"original");
2378            assert_eq!(
2379                tokio::fs::read(entry.join("replacement-child")).await?,
2380                b"replacement"
2381            );
2382            Ok(())
2383        }
2384
2385        #[tokio::test]
2386        async fn directory_replacement_is_not_descended_after_classification() -> anyhow::Result<()>
2387        {
2388            let tmp = tempfile::tempdir()?;
2389            let entry = tmp.path().join("entry");
2390            let original = tmp.path().join("original");
2391            tokio::fs::create_dir(&entry).await?;
2392            let parent = Arc::new(
2393                Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2394                    .await?
2395                    .into_tree(),
2396            );
2397            let handle = parent.child(OsStr::new("entry")).await?;
2398            tokio::fs::rename(&entry, &original).await?;
2399            tokio::fs::create_dir(&entry).await?;
2400            tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2401            let visitor = RmVisitor {
2402                protection: None,
2403                prog_track: &RACE_PROGRESS,
2404                settings: Settings {
2405                    fail_early: true,
2406                    filter: None,
2407                    time_filter: None,
2408                    dry_run: None,
2409                },
2410            };
2411            let cx = EntryCx::root(
2412                parent,
2413                OsStr::new("entry").to_owned(),
2414                entry.clone(),
2415                &RACE_PROGRESS,
2416            )
2417            .with_relative_path(std::path::PathBuf::from("entry"));
2418            let error = match visitor.dir_pre(&cx, &(), &handle).await {
2419                Ok(_) => anyhow::bail!("a replacement passed the directory identity check"),
2420                Err(error) => error,
2421            };
2422            assert!(format!("{:#}", error.source).contains("changed identity before descent"));
2423            assert_eq!(
2424                tokio::fs::read(entry.join("replacement-child")).await?,
2425                b"replacement"
2426            );
2427            Ok(())
2428        }
2429
2430        #[tokio::test]
2431        async fn final_rmdir_removes_an_empty_replacement_in_the_walked_slot() -> anyhow::Result<()>
2432        {
2433            let tmp = tempfile::tempdir()?;
2434            let entry = tmp.path().join("entry");
2435            let original = tmp.path().join("original");
2436            tokio::fs::create_dir(&entry).await?;
2437            let parent = Arc::new(
2438                Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2439                    .await?
2440                    .into_tree(),
2441            );
2442            let handle = parent.child(OsStr::new("entry")).await?;
2443            let visitor = RmVisitor {
2444                protection: None,
2445                prog_track: &RACE_PROGRESS,
2446                settings: Settings {
2447                    fail_early: true,
2448                    filter: None,
2449                    time_filter: None,
2450                    dry_run: None,
2451                },
2452            };
2453            let cx = EntryCx::root(
2454                parent,
2455                OsStr::new("entry").to_owned(),
2456                entry.clone(),
2457                &RACE_PROGRESS,
2458            )
2459            .with_relative_path(std::path::PathBuf::from("entry"));
2460            let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2461                DirAction::Descend { state, .. } => state,
2462                DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2463            };
2464            tokio::fs::rename(&entry, &original).await?;
2465            tokio::fs::create_dir(&entry).await?;
2466            let summary = visitor
2467                .dir_post(
2468                    &cx,
2469                    state,
2470                    Ok((Summary::default(), ProcessedChildren::default())),
2471                )
2472                .await?;
2473            assert_eq!(summary.directories_removed, 1);
2474            assert!(!entry.exists(), "the empty slot replacement survived rmdir");
2475            assert!(original.is_dir());
2476            Ok(())
2477        }
2478
2479        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2480        async fn intended_removal_keeps_temporary_mode_until_rmdir() -> anyhow::Result<()> {
2481            let tmp = tempfile::tempdir()?;
2482            let entry = tmp.path().join("entry");
2483            tokio::fs::create_dir(&entry).await?;
2484            tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2485            let parent = Arc::new(
2486                Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2487                    .await?
2488                    .into_tree(),
2489            );
2490            let handle = parent.child(OsStr::new("entry")).await?;
2491            let visitor = RmVisitor {
2492                protection: None,
2493                prog_track: &RACE_PROGRESS,
2494                settings: Settings {
2495                    fail_early: true,
2496                    filter: None,
2497                    time_filter: None,
2498                    dry_run: None,
2499                },
2500            };
2501            let cx = EntryCx::root(
2502                parent,
2503                OsStr::new("entry").to_owned(),
2504                entry.clone(),
2505                &RACE_PROGRESS,
2506            )
2507            .with_relative_path(std::path::PathBuf::from("entry"));
2508            let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2509                DirAction::Descend { state, .. } => state,
2510                DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2511            };
2512            assert_eq!(
2513                tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2514                0o700,
2515                "dir_pre must relax the directory before final removal"
2516            );
2517
2518            let mut gate = testutils::BlockingPathGate::install(entry.clone());
2519            let mut task = tokio::spawn(async move {
2520                visitor
2521                    .dir_post(
2522                        &cx,
2523                        state,
2524                        Ok((Summary::default(), ProcessedChildren::default())),
2525                    )
2526                    .await
2527            });
2528            let timeout = std::time::Duration::from_secs(20);
2529            let gate_start = tokio::time::timeout(timeout, gate.wait_started()).await;
2530            if !matches!(&gate_start, Ok(Ok(_))) {
2531                gate.release_all();
2532                task.abort();
2533                let _ = task.await;
2534                match gate_start {
2535                    Ok(Err(error)) => {
2536                        return Err(error.context("final rmdir did not reach its pre-syscall gate"));
2537                    }
2538                    Err(error) => {
2539                        return Err(anyhow::Error::new(error)
2540                            .context("final rmdir did not reach its pre-syscall gate"));
2541                    }
2542                    Ok(Ok(_)) => unreachable!(),
2543                }
2544            }
2545            let checked_mode = tokio::fs::metadata(&entry)
2546                .await
2547                .map(|metadata| metadata.permissions().mode() & 0o7777);
2548            gate.release_all();
2549            let owner_join = match tokio::time::timeout(timeout, &mut task).await {
2550                Ok(result) => result,
2551                Err(error) => {
2552                    task.abort();
2553                    let _ = task.await;
2554                    return Err(anyhow::Error::new(error)
2555                        .context("final rmdir did not quiesce after its gate released"));
2556                }
2557            };
2558            let result = owner_join.context("final rmdir task panicked")?;
2559            let summary = result.map_err(|error| error.source)?;
2560            assert_eq!(
2561                checked_mode?, 0o700,
2562                "the intended-removal path restored metadata before the rmdir boundary"
2563            );
2564            assert!(!entry.exists(), "the by-name rmdir left the directory name");
2565            assert_eq!(summary.directories_removed, 1);
2566            Ok(())
2567        }
2568
2569        #[tokio::test]
2570        async fn filtered_retention_restores_mode_through_chmod_admission() -> anyhow::Result<()> {
2571            let tmp = tempfile::tempdir()?;
2572            let entry = tmp.path().join("entry");
2573            tokio::fs::create_dir(&entry).await?;
2574            tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2575            let mut filter = crate::filter::FilterSettings::new();
2576            filter.add_include("other")?;
2577            let parent = Arc::new(
2578                Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2579                    .await?
2580                    .into_tree(),
2581            );
2582            let handle = parent.child(OsStr::new("entry")).await?;
2583            let visitor = RmVisitor {
2584                protection: None,
2585                prog_track: &RACE_PROGRESS,
2586                settings: Settings {
2587                    fail_early: true,
2588                    filter: Some(filter),
2589                    time_filter: None,
2590                    dry_run: None,
2591                },
2592            };
2593            let cx = EntryCx::root(
2594                parent,
2595                OsStr::new("entry").to_owned(),
2596                entry.clone(),
2597                &RACE_PROGRESS,
2598            )
2599            .with_relative_path(std::path::PathBuf::from("entry"));
2600            let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2601                DirAction::Descend { state, .. } => state,
2602                DirAction::Skip(_) => anyhow::bail!("include-filter ancestor was skipped"),
2603            };
2604            assert_eq!(
2605                tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2606                0o700,
2607                "dir_pre did not relax the protected directory"
2608            );
2609
2610            let admission = testutils::AdmissionLimit::new().await;
2611            let chmod_resource =
2612                throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
2613            admission.set_max_ops_in_flight(chmod_resource, 1);
2614            let held_chmod = throttle::ops_in_flight_permit(chmod_resource).await;
2615            let processed = ProcessedChildren::default();
2616            let restore = visitor.dir_post(&cx, state, Ok((Summary::default(), processed)));
2617            tokio::pin!(restore);
2618            assert!(
2619                futures::poll!(restore.as_mut()).is_pending(),
2620                "filtered retention bypassed Destination/Chmod admission"
2621            );
2622            assert_eq!(
2623                tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2624                0o700,
2625                "filtered retention restored the mode while chmod admission was held"
2626            );
2627            drop(held_chmod);
2628            let summary = admission
2629                .run_with_timeout(std::time::Duration::from_secs(20), restore.as_mut())
2630                .await
2631                .context("filtered mode restore did not resume after chmod admission")?
2632                .map_err(|error| error.source)?;
2633            assert!(entry.is_dir(), "filtered retention removed the directory");
2634            assert_eq!(summary.directories_removed, 0);
2635            assert_eq!(
2636                tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2637                0o555,
2638                "filtered retention did not restore the original directory mode"
2639            );
2640            Ok(())
2641        }
2642
2643        /// Repeatedly swap `tree/sub` between a real directory (holding a real file) and a symlink
2644        /// to an OUT-OF-TREE sentinel directory, using rename so each individual state is atomic.
2645        /// Two staging names live alongside `sub` and are renamed over it in a tight loop until
2646        /// `stop` is set. Runs on a dedicated OS thread so it makes progress regardless of the
2647        /// tokio runtime's scheduling. Mirrors copy's `intermediate_dir_swap_never_follows_symlink`
2648        /// swapper.
2649        fn spawn_dir_symlink_swapper(
2650            tree: std::path::PathBuf,
2651            sentinel: std::path::PathBuf,
2652        ) -> crate::testutils::SwapperGuard {
2653            crate::testutils::SwapperGuard::spawn(move |stop| {
2654                let sub = tree.join("sub");
2655                let staged_dir = tree.join("__staged_sub_dir");
2656                let staged_link = tree.join("__staged_sub_link");
2657                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
2658                    // stage a real directory (with a real file) then swap it in over `sub`.
2659                    let _ = std::fs::remove_dir_all(&staged_dir);
2660                    if std::fs::create_dir(&staged_dir).is_ok() {
2661                        let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL");
2662                        // RENAME_EXCHANGE isn't portable here; remove-then-rename. The window where
2663                        // `sub` is briefly absent is fine — rm may error, an accepted failed-closed
2664                        // outcome. (rm must still never touch the out-of-tree sentinel.)
2665                        let _ = std::fs::remove_dir_all(&sub);
2666                        let _ = std::fs::remove_file(&sub);
2667                        let _ = std::fs::rename(&staged_dir, &sub);
2668                    }
2669                    // stage a symlink to the out-of-tree sentinel dir, then swap it in over `sub`.
2670                    let _ = std::fs::remove_file(&staged_link);
2671                    if std::os::unix::fs::symlink(&sentinel, &staged_link).is_ok() {
2672                        let _ = std::fs::remove_dir_all(&sub);
2673                        let _ = std::fs::remove_file(&sub);
2674                        let _ = std::fs::rename(&staged_link, &sub);
2675                    }
2676                }
2677            })
2678        }
2679
2680        /// While `rm` removes a tree, a background thread rapidly flips an intermediate directory
2681        /// `tree/sub` between a real directory and a symlink to a SENTINEL directory tree that
2682        /// lives OUTSIDE the target, holding files that must never be deleted.
2683        ///
2684        /// [`RmVisitor::dir_pre`] descends a directory via [`Dir::open_dir`] (`O_NOFOLLOW|O_DIRECTORY`), so if
2685        /// `sub` is a symlink at the moment of descent the open fails closed (ELOOP/ENOTDIR) and
2686        /// the walk never follows it into the sentinel. If `sub` is a symlink at the moment of
2687        /// classification it is treated as a leaf and `unlink_at` removes the LINK, never its
2688        /// target. Either way the out-of-tree sentinel files survive — that is the safety
2689        /// assertion, checked on every iteration regardless of timing. Also confirms the run
2690        /// terminates (per-op timeout) rather than hanging or following the link.
2691        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2692        async fn intermediate_dir_swap_never_deletes_out_of_tree_sentinel() -> anyhow::Result<()> {
2693            let tmp = testutils::create_temp_dir().await?;
2694            let root = tmp.as_path();
2695            // the sentinel tree lives OUTSIDE the rm target, reachable only via the swapped symlink.
2696            let sentinel = root.join("sentinel_tree");
2697            tokio::fs::create_dir(&sentinel).await?;
2698            tokio::fs::write(sentinel.join("secret1.txt"), b"SECRET-1").await?;
2699            tokio::fs::create_dir(sentinel.join("subdir")).await?;
2700            tokio::fs::write(sentinel.join("subdir").join("secret2.txt"), b"SECRET-2").await?;
2701
2702            let tree = root.join("tree");
2703            let swapper = spawn_dir_symlink_swapper(tree.clone(), sentinel.clone());
2704
2705            let settings = Settings {
2706                fail_early: false,
2707                filter: None,
2708                dry_run: None,
2709                time_filter: None,
2710            };
2711            let mut removed = 0usize;
2712            let mut errored = 0usize;
2713            for i in 0..400 {
2714                // (re)create the target tree. To MAXIMIZE the chance rm encounters `tree/sub` while
2715                // the background thread has it in the symlink state, give `tree` many sibling
2716                // subdirectories with files: rm spends real time enumerating/removing them
2717                // concurrently with the swapper's flips, widening the window in which `sub` is
2718                // classified/descended mid-swap. On even iterations we additionally seed `sub` as a
2719                // symlink-to-sentinel up front, deterministically exercising the "intermediate is a
2720                // symlink at classification time → unlink the link, never recurse the target" path.
2721                let _ = tokio::fs::create_dir(&tree).await;
2722                for d in 0..16 {
2723                    let sib = tree.join(format!("sib_{d}"));
2724                    let _ = tokio::fs::create_dir(&sib).await;
2725                    for f in 0..4 {
2726                        let _ = tokio::fs::write(sib.join(format!("f{f}.txt")), b"x").await;
2727                    }
2728                }
2729                let sub = tree.join("sub");
2730                if i % 2 == 0 {
2731                    // deterministically place a symlink-to-sentinel at `sub` (best-effort; the
2732                    // swapper may immediately flip it — that's fine, both states are safe).
2733                    let _ = tokio::fs::remove_dir_all(&sub).await;
2734                    let _ = tokio::fs::remove_file(&sub).await;
2735                    let _ = tokio::fs::symlink(&sentinel, &sub).await;
2736                } else if tokio::fs::symlink_metadata(&sub).await.is_err() {
2737                    let _ = tokio::fs::create_dir(&sub).await;
2738                    let _ = tokio::fs::write(sub.join("real.txt"), b"REAL").await;
2739                }
2740                let result = tokio::time::timeout(
2741                    std::time::Duration::from_secs(30),
2742                    super::rm(&RACE_PROGRESS, &tree, &settings),
2743                )
2744                .await
2745                .expect("rm must not hang under concurrent dir swapping");
2746                let summary = match result {
2747                    Ok(summary) => summary,
2748                    Err(error) => {
2749                        errored += 1;
2750                        error.summary
2751                    }
2752                };
2753                removed +=
2754                    summary.files_removed + summary.symlinks_removed + summary.directories_removed;
2755                // CORE SAFETY ASSERTION (holds on every iteration regardless of timing): the
2756                // out-of-tree sentinel tree and its files are NEVER deleted by rm — neither by
2757                // following a symlinked `sub` (unlink removes the link, not the target) nor by
2758                // descending it (open_dir's O_NOFOLLOW fails closed).
2759                assert!(
2760                    sentinel.exists(),
2761                    "iteration {i}: sentinel directory was deleted — rm followed the symlink"
2762                );
2763                let s1 = tokio::fs::read(sentinel.join("secret1.txt")).await;
2764                assert!(
2765                    matches!(&s1, Ok(b) if b == b"SECRET-1"),
2766                    "iteration {i}: sentinel/secret1.txt was deleted or altered — rm followed the symlink"
2767                );
2768                let s2 = tokio::fs::read(sentinel.join("subdir").join("secret2.txt")).await;
2769                assert!(
2770                    matches!(&s2, Ok(b) if b == b"SECRET-2"),
2771                    "iteration {i}: sentinel/subdir/secret2.txt was deleted — rm recursed through the symlink"
2772                );
2773                // clean up any leftover tree before the next iteration (best-effort).
2774                let _ = tokio::fs::remove_dir_all(&tree).await;
2775            }
2776
2777            drop(swapper);
2778            // sanity (not the safety assertion): the run did observable work across the iterations.
2779            tracing::info!("intermediate dir swap: removed={removed}, errored={errored}");
2780            assert!(
2781                removed > 0,
2782                "expected actual removals across the concurrent iterations"
2783            );
2784            Ok(())
2785        }
2786    }
2787}