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