rcp-tools-common 0.41.0

Internal library for RCP file operation tools - shared utilities and core operations (not intended for direct use)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! rsync-style `--delete` (mirror) support: remove destination entries that
//! have no counterpart in the source directory.

use std::ffi::OsString;
use std::sync::Arc;

use anyhow::Context;

use crate::progress;
use crate::safedir::Dir;

/// Settings controlling rsync-style `--delete` (mirror) behavior.
///
/// Present (`Some`) only when `--delete` was requested. `None` means the
/// destination is never enumerated and no pruning work is done, so the default
/// copy path pays nothing for this feature.
#[derive(Debug, Clone)]
pub struct DeleteSettings {
    /// Also remove destination entries that match an exclude pattern
    /// (rsync `--delete-excluded`). When false, excluded entries are protected.
    pub delete_excluded: bool,
}

/// Complete exact child-name evidence, sealed with the settings that consume it.
///
/// Rlink captures settings when collection starts; copy binds its own settings at completion.
/// The storage can be ordered names from copy or a hashed set from rlink; pruning requires the
/// hashed form. Once sealed, the private fields keep those settings and names together.
#[derive(Debug)]
pub(crate) struct DeleteKeepSet<N> {
    settings: DeleteSettings,
    names: N,
}

impl<N> DeleteKeepSet<N> {
    /// Seal a completed, exact collection. Call only at a successful traversal boundary.
    fn from_complete(settings: DeleteSettings, names: N) -> Self {
        Self { settings, names }
    }
}

impl<'a> DeleteKeepSet<&'a [OsString]> {
    /// Borrow evidence that only a successful delete-collecting walk can produce. Ordinary
    /// collected names and successful non-collecting walks cannot authorize pruning.
    fn from_processed(
        settings: &DeleteSettings,
        processed: &'a crate::walk_driver::ProcessedChildren,
    ) -> Option<Self> {
        processed
            .delete_names()
            .map(|names| Self::from_complete(settings.clone(), names))
    }
    /// Hash borrowed names only once a destination exists to prune.
    pub(crate) fn hashed(&self) -> DeleteKeepSet<std::collections::HashSet<&'a std::ffi::OsStr>> {
        DeleteKeepSet::from_complete(
            self.settings.clone(),
            self.names.iter().map(OsString::as_os_str).collect(),
        )
    }
}

/// One completion decision owns both prune authorization and the discarded-evidence warning.
pub(crate) enum DeleteDecision<N> {
    NotRequested,
    Discarded,
    Ready(DeleteKeepSet<N>),
}

impl<N> DeleteDecision<N> {
    pub(crate) fn into_ready(self, dst_path: &std::path::Path) -> Option<DeleteKeepSet<N>> {
        match self {
            Self::NotRequested => None,
            Self::Discarded => {
                tracing::warn!(
                    "skipping --delete pruning of {:?} because entry processing failed or did not provide complete exact names",
                    dst_path
                );
                None
            }
            Self::Ready(keep) => Some(keep),
        }
    }
}

impl<'a> DeleteDecision<&'a [OsString]> {
    /// Only a successful exact collection can authorize pruning. An exact empty collection is
    /// valid evidence; failed traversal, ordinary names, and omitted collection are not.
    pub(crate) fn from_processed(
        settings: &DeleteSettings,
        processed: Option<&'a crate::walk_driver::ProcessedChildren>,
    ) -> Self {
        match processed.and_then(|processed| DeleteKeepSet::from_processed(settings, processed)) {
            Some(keep) => Self::Ready(keep),
            None => Self::Discarded,
        }
    }
}

/// Outcomes of rlink's source/update pass: errors always, and exact names when deletion is enabled.
///
/// This is the directory's keep-going error sink even without `--delete`. After all workers have
/// been joined, completion returns both the deletion decision and the errors needed by finalization.
pub(crate) struct LinkChildOutcomes {
    errors: crate::error_collector::ErrorCollector,
    inner: Option<(DeleteSettings, std::collections::HashSet<OsString>)>,
}

impl LinkChildOutcomes {
    pub(crate) fn new(settings: Option<&DeleteSettings>) -> Self {
        Self {
            inner: settings.map(|settings| (settings.clone(), std::collections::HashSet::new())),
            errors: crate::error_collector::ErrorCollector::default(),
        }
    }
    pub(crate) fn record_exact(&mut self, name: OsString) {
        if let Some((_, names)) = &mut self.inner {
            names.insert(name);
        }
    }
    /// Record traversal and worker errors even when deletion was not requested.
    pub(crate) fn record_error(&self, error: anyhow::Error) {
        self.errors.push(error);
    }
    /// Consume the directory's names and their own errors after every source/update worker has
    /// been joined. The returned errors remain available for keep-going finalization.
    pub(crate) fn finish(
        self,
    ) -> (
        DeleteDecision<std::collections::HashSet<OsString>>,
        crate::error_collector::ErrorCollector,
    ) {
        let decision = match self.inner {
            None => DeleteDecision::NotRequested,
            Some(_) if self.errors.has_errors() => DeleteDecision::Discarded,
            Some((settings, names)) => {
                DeleteDecision::Ready(DeleteKeepSet::from_complete(settings, names))
            }
        };
        (decision, self.errors)
    }
    #[cfg(test)]
    pub(crate) fn expect_ready(self) -> DeleteKeepSet<std::collections::HashSet<OsString>> {
        let (decision, errors) = self.finish();
        if let Some(error) = errors.into_error() {
            panic!("expected successful child outcomes: {error:#}");
        }
        match decision {
            DeleteDecision::Ready(keep) => keep,
            DeleteDecision::NotRequested | DeleteDecision::Discarded => {
                panic!("expected completed delete-name collection")
            }
        }
    }
    #[cfg(test)]
    pub(crate) fn as_set(&self) -> Option<&std::collections::HashSet<OsString>> {
        self.inner.as_ref().map(|(_, names)| names)
    }
}

/// Remove entries in the already-open destination directory `dst_dir` whose names are not in
/// `keep` (the source entry names that passed the filter for this directory).
///
/// The destination is enumerated and pruned entirely through `dst_dir`'s pinned file descriptor:
/// entries come from `dst_dir.read_entries()` and each extraneous entry is removed via
/// `rm::rm_child` (fd-relative, `O_NOFOLLOW` descent). The destination path is never
/// re-resolved, so a privileged prune cannot be redirected by a concurrent symlink swap into
/// deleting a tree outside the destination — the classic mirror-delete symlink race fails closed.
/// The caller is responsible for opening `dst_dir` `O_NOFOLLOW`: in a real copy it is the held
/// destination directory; in `--dry-run` (where the create-or-overwrite step is skipped and the
/// path could still be a symlink-to-directory) the caller opens it `O_NOFOLLOW|O_DIRECTORY`, which
/// fails closed on a symlink or non-directory before prune is ever invoked.
///
/// `relative_dir` is this directory's path relative to the source root, used to match destination
/// entries against `filter` for exclude-protection. Excluded destination entries are protected
/// (kept) unless the keep-set's `delete_excluded` setting is set. Honors `dry_run` (reports without
/// removing, via `rm::rm_child`).
async fn prune_extraneous<K>(
    prog_track: &'static progress::Progress,
    dst_dir: &Arc<Dir>,
    relative_dir: &std::path::Path,
    keep: &DeleteKeepSet<std::collections::HashSet<K>>,
    filter: Option<&crate::filter::FilterSettings>,
    fail_early: bool,
    dry_run: Option<crate::config::DryRunMode>,
) -> Result<crate::rm::Summary, crate::rm::Error>
where
    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
{
    let DeleteKeepSet {
        settings: delete_settings,
        names: keep,
    } = keep;
    let summary = crate::rm::Summary::default();
    // enumerate the destination through its pinned fd (no path re-resolution). `d_type` remains a
    // scheduling hint only: exclude protection classifies under admission and transfers that exact
    // handle into rm, while unfiltered removal lets the shared driver classify at dispatch.
    let entries = dst_dir
        .read_entries()
        .await
        .with_context(|| "failed scanning destination directory for deletion".to_string())
        .map_err(|err| crate::rm::Error::new(err, summary))?;
    prune_entries(
        prog_track,
        dst_dir,
        relative_dir,
        keep,
        filter,
        delete_settings,
        fail_early,
        dry_run,
        entries,
    )
    .await
}

/// Select the held real or preview directory, reporting the shared no-directory skip policy.
pub(crate) fn select_scan_dir<'a>(
    dst_dir: Option<&'a Arc<Dir>>,
    preview_dir: Option<&'a Arc<Dir>>,
    dst_path: &std::path::Path,
) -> Option<&'a Arc<Dir>> {
    let scan_dir = dst_dir.or(preview_dir);
    if scan_dir.is_none() {
        tracing::debug!(
            "skipping --delete pruning of {:?}: no destination directory to scan",
            dst_path
        );
    }
    scan_dir
}

/// Prune through a held destination and fold successful or partial removal counts exactly once.
/// The caller retains its fail-early/finalization policy; the original error chain is returned.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn prune_and_fold<K>(
    prog_track: &'static progress::Progress,
    dst_dir: &Arc<Dir>,
    relative_dir: &std::path::Path,
    keep: &DeleteKeepSet<std::collections::HashSet<K>>,
    filter: Option<&crate::filter::FilterSettings>,
    fail_early: bool,
    dry_run: Option<crate::config::DryRunMode>,
    summary: &mut crate::rm::Summary,
) -> Result<(), anyhow::Error>
where
    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
{
    match prune_extraneous(
        prog_track,
        dst_dir,
        relative_dir,
        keep,
        filter,
        fail_early,
        dry_run,
    )
    .await
    {
        Ok(removed) => {
            *summary = *summary + removed;
            Ok(())
        }
        Err(error) => {
            *summary = *summary + error.summary;
            Err(error.source)
        }
    }
}

/// Apply prune decisions to an already-enumerated destination directory.
///
/// Production callers arrive through [`prune_extraneous`]. Separating enumeration lets tests
/// inject stale and `DT_UNKNOWN` hints deterministically without requiring an NFS/FUSE fixture.
#[allow(clippy::too_many_arguments)]
async fn prune_entries<K>(
    prog_track: &'static progress::Progress,
    dst_dir: &Arc<Dir>,
    relative_dir: &std::path::Path,
    keep: &std::collections::HashSet<K>,
    filter: Option<&crate::filter::FilterSettings>,
    delete_settings: &DeleteSettings,
    fail_early: bool,
    dry_run: Option<crate::config::DryRunMode>,
    entries: Vec<(OsString, Option<crate::walk::EntryKind>)>,
) -> Result<crate::rm::Summary, crate::rm::Error>
where
    K: std::borrow::Borrow<std::ffi::OsStr> + Eq + std::hash::Hash + Sync,
{
    let mut summary = crate::rm::Summary::default();
    let errors = crate::error_collector::ErrorCollector::default();
    for (name, hint) in entries {
        let result: Result<crate::rm::Summary, crate::rm::Error> = async {
            if keep.contains(name.as_os_str()) {
                return Ok(Default::default());
            }
            // the entry's path relative to the destination (mirror) root: anchors filter matching
            // and reconstructs the display path inside `rm_child`. Computed once and reused below.
            let rel = relative_dir.join(&name);
            let protect_excluded = !delete_settings.delete_excluded && filter.is_some();
            let mut admitted_entry = None;
            // an exclude-protection decision authorizes deletion, so `d_type` is never authoritative
            // here. Classify once under admission and transfer this exact handle into rm; otherwise a
            // stale File hint for a real directory could bypass a dir-only exclude such as `cache/`.
            let is_dir = if protect_excluded {
                let admission = crate::walk::ensure_entry_admission(
                    crate::walk::PermitKind::PendingMeta,
                    crate::walk::EntryAdmission::RootOrDelegated,
                )
                .await;
                let entry =
                    crate::walk::classify_admitted_entry(dst_dir, &name, admission.into_permit())
                        .await
                        .with_context(|| format!("failed reading metadata from {rel:?}"))
                        .map_err(|error| crate::rm::Error::new(error, Default::default()))?;
                let is_dir = entry.kind() == crate::walk::EntryKind::Dir;
                admitted_entry = Some(entry);
                is_dir
            } else {
                false
            };
            // exclude-protection: keep destination entries the filter would exclude,
            // unless --delete-excluded was requested.
            if !delete_settings.delete_excluded
                && let Some(filter) = filter
                && !matches!(
                    filter.should_include(&rel, is_dir),
                    crate::filter::FilterResult::Included
                )
            {
                tracing::debug!("protecting excluded destination entry {:?}", rel);
                return Ok(Default::default());
            }
            // Protect excluded descendants when removing an extraneous directory: rm::rm_child
            // applies the filter recursively (skipping excluded entries), so an extra dir containing
            // e.g. `*.log` files keeps them and survives non-empty — upholding the documented
            // "excluded files are protected by default" guarantee (and matching rsync). With
            // --delete-excluded we pass no filter so the whole subtree is removed. The filter is
            // anchored at the destination (mirror) root, so the entry's destination-root-relative
            // path `relative_dir.join(name)` matches path/anchored patterns like `cache/*.log`
            // correctly.
            let rm_settings = crate::rm::Settings {
                fail_early,
                filter: if delete_settings.delete_excluded {
                    None
                } else {
                    filter.cloned()
                },
                time_filter: None,
                dry_run,
            };
            match admitted_entry {
                Some(entry) => {
                    crate::rm::rm_child_admitted_entry(
                        prog_track,
                        dst_dir,
                        &name,
                        &rel,
                        &rm_settings,
                        entry,
                    )
                    .await
                }
                None => {
                    let admission = crate::walk::ensure_entry_admission(
                        crate::walk::PermitKind::PendingMeta,
                        crate::walk::EntryAdmission::from_hint(hint),
                    )
                    .await;
                    crate::rm::rm_child_admitted(
                        prog_track,
                        dst_dir,
                        &name,
                        &rel,
                        &rm_settings,
                        admission,
                    )
                    .await
                }
            }
        }
        .await;
        match result {
            Ok(rm_summary) => {
                summary = summary + rm_summary;
            }
            Err(err) => {
                summary = summary + err.summary;
                if fail_early {
                    return Err(crate::rm::Error::new(err.source, summary));
                }
                errors.push(err.source);
            }
        }
    }
    if let Some(err) = errors.into_error() {
        return Err(crate::rm::Error::new(err, summary));
    }
    Ok(summary)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use tracing_test::traced_test;

    static PROGRESS: std::sync::LazyLock<progress::Progress> =
        std::sync::LazyLock::new(progress::Progress::new);

    fn delete_settings(delete_excluded: bool) -> DeleteSettings {
        DeleteSettings { delete_excluded }
    }

    #[test]
    fn failed_collection_cannot_authorize_pruning() {
        let settings = delete_settings(true);
        let mut collecting = LinkChildOutcomes::new(Some(&settings));
        collecting.record_exact(OsString::from("completed-child"));
        collecting.record_error(anyhow::anyhow!("a later child failed"));
        let (decision, errors) = collecting.finish();
        assert!(matches!(decision, DeleteDecision::Discarded));
        assert!(
            errors.has_errors(),
            "finalization must retain the traversal error"
        );
    }

    #[test]
    fn completed_collection_keeps_its_settings_and_empty_is_valid() {
        for delete_excluded in [false, true] {
            let settings = delete_settings(delete_excluded);
            let (decision, errors) = LinkChildOutcomes::new(Some(&settings)).finish();
            let DeleteDecision::Ready(keep) = decision else {
                panic!("completed empty collection must authorize pruning")
            };
            assert!(!errors.has_errors());
            assert!(keep.names.is_empty());
            assert_eq!(keep.settings.delete_excluded, delete_excluded);
        }
        let mut collecting = LinkChildOutcomes::new(None);
        collecting.record_exact(OsString::from("ignored"));
        let (decision, errors) = collecting.finish();
        assert!(matches!(decision, DeleteDecision::NotRequested));
        assert!(!errors.has_errors());
    }

    #[test]
    fn collection_preserves_errors_without_delete() {
        let mut collecting = LinkChildOutcomes::new(None);
        collecting.record_exact(OsString::from("unretained"));
        collecting.record_error(
            anyhow::Error::from(std::io::Error::from_raw_os_error(libc::EACCES))
                .context("source enumeration failed"),
        );
        let (decision, errors) = collecting.finish();
        assert!(matches!(decision, DeleteDecision::NotRequested));
        let error = errors
            .into_error()
            .expect("non-delete failures must survive completion");
        assert_eq!(
            error
                .downcast_ref::<std::io::Error>()
                .unwrap()
                .raw_os_error(),
            Some(libc::EACCES)
        );
        assert!(format!("{error:#}").contains("source enumeration failed"));
    }

    #[tokio::test]
    async fn prune_completion_folds_success_and_partial_counts_once() -> anyhow::Result<()> {
        use std::os::unix::fs::PermissionsExt;
        for (block_parent_removal, fail_early) in [(false, false), (true, false), (true, true)] {
            if block_parent_removal && nix::unistd::geteuid().is_root() {
                eprintln!("skipping permission-denial case: root bypasses directory permissions");
                continue;
            }
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            for child in ["extra1", "extra2"] {
                tokio::fs::create_dir_all(dst.join(child)).await?;
                tokio::fs::write(dst.join(child).join("file"), b"abc").await?;
            }
            let dir = open_dst(&dst).await?;
            if block_parent_removal {
                tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o500)).await?;
            }
            let keep =
                DeleteKeepSet::from_complete(delete_settings(false), HashSet::<OsString>::new());
            let mut summary = crate::rm::Summary {
                files_removed: 7,
                bytes_removed: 11,
                directories_removed: 2,
                ..Default::default()
            };
            let result = prune_and_fold(
                &PROGRESS,
                &dir,
                std::path::Path::new(""),
                &keep,
                None,
                fail_early,
                None,
                &mut summary,
            )
            .await;
            tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
            let removed = if block_parent_removal && fail_early {
                1
            } else {
                2
            };
            assert_eq!(summary.files_removed, 7 + removed);
            assert_eq!(summary.bytes_removed, 11 + 3 * removed as u64);
            assert_eq!(
                ["extra1", "extra2"]
                    .iter()
                    .filter(|child| dst.join(child).join("file").exists())
                    .count(),
                2 - removed,
            );
            if block_parent_removal {
                let error = result.expect_err("parent permissions must prevent the final rmdir");
                assert_eq!(
                    error
                        .downcast_ref::<std::io::Error>()
                        .unwrap()
                        .raw_os_error(),
                    Some(libc::EACCES),
                );
                assert_eq!(summary.directories_removed, 2);
                assert!(dst.join("extra1").is_dir());
                assert!(dst.join("extra2").is_dir());
            } else {
                result?;
                assert_eq!(summary.directories_removed, 4);
                assert!(!dst.join("extra1").exists());
                assert!(!dst.join("extra2").exists());
            }
        }
        Ok(())
    }

    /// Open `dst` as the destination directory `Dir` prune operates through, mirroring the copy/link
    /// call sites (`O_NOFOLLOW|O_DIRECTORY`, Destination side).
    async fn open_dst(dst: &std::path::Path) -> anyhow::Result<Arc<Dir>> {
        Ok(Arc::new(
            Dir::open_root_dir(dst, false, congestion::Side::Destination).await?,
        ))
    }

    mod max_files_in_flight_tests {
        use super::*;

        /// Delete protection must classify the entry it will remove rather than trust `d_type`.
        #[tokio::test]
        async fn stale_file_hint_cannot_bypass_dir_only_exclude() -> anyhow::Result<()> {
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            tokio::fs::create_dir_all(dst.join("cache")).await?;
            tokio::fs::write(dst.join("cache").join("child"), b"protected").await?;
            let admission = crate::testutils::AdmissionLimit::new().await;
            admission.set_files_in_flight(1);
            let dst_dir = open_dst(&dst).await?;
            let mut filter = crate::filter::FilterSettings::new();
            filter.add_exclude("cache/")?;
            let result = admission
                .run_with_timeout(
                    std::time::Duration::from_secs(20),
                    prune_entries(
                        &PROGRESS,
                        &dst_dir,
                        std::path::Path::new(""),
                        &HashSet::<OsString>::new(),
                        Some(&filter),
                        &delete_settings(false),
                        false,
                        None,
                        vec![(
                            std::ffi::OsString::from("cache"),
                            Some(crate::walk::EntryKind::File),
                        )],
                    ),
                )
                .await
                .context("stale-hint delete protection did not terminate")?
                .map_err(|error| error.source)?;
            assert_eq!(result.files_removed, 0);
            assert_eq!(result.directories_removed, 0);
            assert!(dst.join("cache").join("child").exists());
            Ok(())
        }

        /// A destructive filter admits classification even when `d_type` reports a file.
        #[tokio::test]
        async fn filtered_hinted_file_waits_before_authoritative_decision() -> anyhow::Result<()> {
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            tokio::fs::create_dir(&dst).await?;
            tokio::fs::write(dst.join("protected"), b"x").await?;
            let admission = crate::testutils::AdmissionLimit::new().await;
            admission.set_files_in_flight(1);
            let dst_dir = open_dst(&dst).await?;
            let stat_resource =
                throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Stat);
            admission.set_max_ops_in_flight(stat_resource, 1);
            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
            let mut filter = crate::filter::FilterSettings::new();
            filter.add_exclude("protected")?;
            let keep: HashSet<OsString> = HashSet::new();
            let settings = delete_settings(false);
            let prune = prune_entries(
                &PROGRESS,
                &dst_dir,
                std::path::Path::new(""),
                &keep,
                Some(&filter),
                &settings,
                false,
                None,
                vec![(
                    std::ffi::OsString::from("protected"),
                    Some(crate::walk::EntryKind::File),
                )],
            );
            tokio::pin!(prune);
            let stopped_at_stat_gate = futures::poll!(prune.as_mut()).is_pending();
            let mut second_permit = Box::pin(throttle::pending_meta_permit());
            let classification_owned_admission =
                futures::poll!(second_permit.as_mut()).is_pending();
            drop(second_permit);
            drop(held_stat);
            let result = admission
                .run_with_timeout(std::time::Duration::from_secs(20), prune.as_mut())
                .await
                .context("filtered hinted delete did not resume after stat release")?;
            let summary = result.map_err(|error| error.source)?;
            assert!(
                stopped_at_stat_gate,
                "delete protection did not reach the held destination Stat gate"
            );
            assert!(
                classification_owned_admission,
                "delete protection reached classification without owning admission"
            );
            assert_eq!(summary.files_removed, 0);
            assert!(dst.join("protected").exists());
            Ok(())
        }

        /// A `DT_UNKNOWN` prune entry must reserve metadata capacity before the fd-based filter
        /// classification. If the filter protects it, `rm_child` is never reached and cannot repair
        /// admission after the fact.
        #[tokio::test]
        async fn filtered_unknown_entry_waits_before_probe() -> anyhow::Result<()> {
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            tokio::fs::create_dir(&dst).await?;
            tokio::fs::write(dst.join("protected"), b"x").await?;
            let admission = crate::testutils::AdmissionLimit::new().await;
            let dst_dir = open_dst(&dst).await?;
            let mut filter = crate::filter::FilterSettings::new();
            filter.add_exclude("protected")?;
            let keep: HashSet<OsString> = HashSet::new();
            let settings = delete_settings(false);
            admission.set_files_in_flight(1);
            let stat_resource =
                throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Stat);
            admission.set_max_ops_in_flight(stat_resource, 1);
            let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
            let prune = prune_entries(
                &PROGRESS,
                &dst_dir,
                std::path::Path::new(""),
                &keep,
                Some(&filter),
                &settings,
                false,
                None,
                vec![(std::ffi::OsString::from("protected"), None)],
            );
            tokio::pin!(prune);
            let stopped_at_stat_gate = futures::poll!(prune.as_mut()).is_pending();
            let mut second_permit = Box::pin(throttle::pending_meta_permit());
            let probe_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
            drop(second_permit);
            drop(held_stat);
            let result = admission
                .run_with_timeout(std::time::Duration::from_secs(20), prune.as_mut())
                .await;
            assert!(
                stopped_at_stat_gate,
                "DT_UNKNOWN prune filter did not reach the held stat gate"
            );
            let summary = result
                .context("prune did not resume after stat capacity was released")?
                .map_err(|error| error.source)?;
            assert!(
                !probe_bypassed_admission,
                "DT_UNKNOWN prune filter probe bypassed pending-metadata admission"
            );
            assert_eq!(summary.files_removed, 0);
            assert_eq!(summary.directories_removed, 0);
            assert!(dst.join("protected").exists());
            Ok(())
        }

        /// Keep-going records a failed authoritative probe and continues with later siblings.
        #[tokio::test]
        async fn failed_authoritative_probe_keeps_going_in_entry_order() -> anyhow::Result<()> {
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            tokio::fs::create_dir(&dst).await?;
            tokio::fs::write(dst.join("before"), b"b").await?;
            tokio::fs::write(dst.join("kept"), b"k").await?;
            tokio::fs::write(dst.join("after"), b"a").await?;
            let admission = crate::testutils::AdmissionLimit::new().await;
            let dst_dir = open_dst(&dst).await?;
            let filter = crate::filter::FilterSettings::new();
            let mut keep = HashSet::new();
            keep.insert(std::ffi::OsString::from("kept"));
            let result = admission
                .run_with_timeout(
                    std::time::Duration::from_secs(20),
                    prune_entries(
                        &PROGRESS,
                        &dst_dir,
                        std::path::Path::new(""),
                        &keep,
                        Some(&filter),
                        &delete_settings(false),
                        false,
                        None,
                        vec![
                            (std::ffi::OsString::from("before"), None),
                            (std::ffi::OsString::from("vanished"), None),
                            (std::ffi::OsString::from("kept"), None),
                            (std::ffi::OsString::from("after"), None),
                        ],
                    ),
                )
                .await
                .context("keep-going delete-protection probe did not terminate")?;
            let error = result.expect_err("a missing authoritative probe target must fail");
            let rendered = format!("{:#}", error.source);
            assert!(rendered.contains("failed reading metadata from"));
            assert!(rendered.contains("vanished"));
            assert_eq!(error.summary.bytes_removed, 2);
            assert_eq!(error.summary.files_removed, 2);
            assert_eq!(error.summary.symlinks_removed, 0);
            assert_eq!(error.summary.directories_removed, 0);
            assert_eq!(error.summary.files_skipped, 0);
            assert_eq!(error.summary.symlinks_skipped, 0);
            assert_eq!(error.summary.directories_skipped, 0);
            assert!(!dst.join("before").exists());
            assert!(!dst.join("vanished").exists());
            assert!(dst.join("kept").exists());
            assert!(!dst.join("after").exists());
            Ok(())
        }

        /// Fail-early reports completed work and leaves siblings after a failed probe untouched.
        #[tokio::test]
        async fn failed_authoritative_probe_stops_early_in_entry_order() -> anyhow::Result<()> {
            let tmp = tempfile::tempdir()?;
            let dst = tmp.path().join("dst");
            tokio::fs::create_dir(&dst).await?;
            tokio::fs::write(dst.join("before"), b"b").await?;
            tokio::fs::write(dst.join("kept"), b"k").await?;
            tokio::fs::write(dst.join("after"), b"a").await?;
            let admission = crate::testutils::AdmissionLimit::new().await;
            let dst_dir = open_dst(&dst).await?;
            let filter = crate::filter::FilterSettings::new();
            let mut keep = HashSet::new();
            keep.insert(std::ffi::OsString::from("kept"));
            let result = admission
                .run_with_timeout(
                    std::time::Duration::from_secs(20),
                    prune_entries(
                        &PROGRESS,
                        &dst_dir,
                        std::path::Path::new(""),
                        &keep,
                        Some(&filter),
                        &delete_settings(false),
                        true,
                        None,
                        vec![
                            (std::ffi::OsString::from("before"), None),
                            (std::ffi::OsString::from("vanished"), None),
                            (std::ffi::OsString::from("kept"), None),
                            (std::ffi::OsString::from("after"), None),
                        ],
                    ),
                )
                .await
                .context("fail-early delete-protection probe did not terminate")?;
            let error = result.expect_err("a missing authoritative probe target must fail");
            let rendered = format!("{:#}", error.source);
            assert!(rendered.contains("failed reading metadata from"));
            assert!(rendered.contains("vanished"));
            assert_eq!(error.summary.bytes_removed, 1);
            assert_eq!(error.summary.files_removed, 1);
            assert_eq!(error.summary.symlinks_removed, 0);
            assert_eq!(error.summary.directories_removed, 0);
            assert_eq!(error.summary.files_skipped, 0);
            assert_eq!(error.summary.symlinks_skipped, 0);
            assert_eq!(error.summary.directories_skipped, 0);
            assert!(!dst.join("before").exists());
            assert!(!dst.join("vanished").exists());
            assert!(dst.join("kept").exists());
            assert!(dst.join("after").exists());
            Ok(())
        }
    }

    #[tokio::test]
    #[traced_test]
    async fn removes_entries_not_in_keep_set() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let dst = tmp.path().join("dst");
        tokio::fs::create_dir(&dst).await?;
        tokio::fs::write(dst.join("keep.txt"), b"x").await?;
        tokio::fs::write(dst.join("extra.txt"), b"x").await?;
        tokio::fs::create_dir(dst.join("extra_dir")).await?;
        tokio::fs::write(dst.join("extra_dir").join("nested.txt"), b"x").await?;

        let mut keep = HashSet::new();
        keep.insert(std::ffi::OsString::from("keep.txt"));

        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
            None,
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;

        assert_eq!(summary.files_removed, 2); // extra.txt + extra_dir/nested.txt
        assert_eq!(summary.directories_removed, 1); // extra_dir
        assert!(dst.join("keep.txt").exists());
        assert!(!dst.join("extra.txt").exists());
        assert!(!dst.join("extra_dir").exists());
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn protects_excluded_entries_unless_delete_excluded() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let dst = tmp.path().join("dst");
        tokio::fs::create_dir(&dst).await?;
        tokio::fs::write(dst.join("data.bin"), b"x").await?; // extra, not excluded
        tokio::fs::write(dst.join("note.log"), b"x").await?; // extra, excluded by *.log

        let mut filter = crate::filter::FilterSettings::new();
        filter.add_exclude("*.log")?;
        let keep: HashSet<OsString> = HashSet::new(); // both are extraneous

        // default: *.log is protected, data.bin is removed
        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
            Some(&filter),
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;
        assert_eq!(summary.files_removed, 1);
        assert!(!dst.join("data.bin").exists());
        assert!(
            dst.join("note.log").exists(),
            "*.log must be protected by default"
        );

        // with delete_excluded: note.log is also removed
        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(true), (keep).clone()),
            Some(&filter),
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;
        assert_eq!(summary.files_removed, 1);
        assert!(!dst.join("note.log").exists());
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn protects_excluded_descendants_of_extraneous_dir() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let dst = tmp.path().join("dst");
        tokio::fs::create_dir(&dst).await?;
        // an extraneous directory (no source counterpart) with an excluded and a normal file
        tokio::fs::create_dir(dst.join("extra_dir")).await?;
        tokio::fs::write(dst.join("extra_dir").join("keep.log"), b"x").await?; // excluded by *.log
        tokio::fs::write(dst.join("extra_dir").join("gone.txt"), b"x").await?; // not excluded

        let mut filter = crate::filter::FilterSettings::new();
        filter.add_exclude("*.log")?;
        let keep: HashSet<OsString> = HashSet::new(); // extra_dir is extraneous

        // default --delete: the excluded descendant is protected, so the dir survives non-empty
        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
            Some(&filter),
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;
        assert_eq!(summary.files_removed, 1); // gone.txt
        assert!(!dst.join("extra_dir").join("gone.txt").exists());
        assert!(
            dst.join("extra_dir").join("keep.log").exists(),
            "excluded descendant of an extraneous dir must be protected"
        );

        // --delete-excluded: the whole extraneous directory is removed
        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(true), (keep).clone()),
            Some(&filter),
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;
        assert_eq!(summary.files_removed, 1); // keep.log
        assert!(!dst.join("extra_dir").exists());
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn protects_path_excluded_descendants_of_extraneous_dir() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let dst = tmp.path().join("dst");
        tokio::fs::create_dir(&dst).await?;
        // an extraneous directory whose descendants are targeted by a PATH-based exclude
        tokio::fs::create_dir(dst.join("cache")).await?;
        tokio::fs::write(dst.join("cache").join("foo.log"), b"x").await?; // matches cache/*.log -> protected
        tokio::fs::write(dst.join("cache").join("data.txt"), b"x").await?; // not matched -> removed

        let mut filter = crate::filter::FilterSettings::new();
        filter.add_exclude("cache/*.log")?;
        let keep: HashSet<OsString> = HashSet::new();

        let dst_dir = open_dst(&dst).await?;
        let summary = prune_extraneous(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
            Some(&filter),
            false,
            None,
        )
        .await
        .map_err(|e| e.source)?;

        assert_eq!(summary.files_removed, 1); // data.txt
        assert!(!dst.join("cache").join("data.txt").exists());
        assert!(
            dst.join("cache").join("foo.log").exists(),
            "path-based exclude must protect the descendant of an extraneous dir"
        );
        Ok(())
    }

    /// A `DT_UNKNOWN` entry is authoritatively classified before delete protection.
    #[tokio::test]
    #[traced_test]
    async fn protects_dir_only_excluded_directory_dt_unknown() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let dst = tmp.path().join("dst");
        tokio::fs::create_dir(&dst).await?;
        // extraneous destination directory `cache/` containing a file; it should be RETAINED by a
        // `cache/` dir-only exclude even though it has no source counterpart.
        tokio::fs::create_dir(dst.join("cache")).await?;
        tokio::fs::write(dst.join("cache").join("item.dat"), b"x").await?;
        // an unrelated extra file that IS extraneous and not excluded, so it should be removed.
        tokio::fs::write(dst.join("unrelated.txt"), b"y").await?;

        let mut filter = crate::filter::FilterSettings::new();
        filter.add_exclude("cache/")?; // dir-only exclude: only protects directories, not files

        let keep: HashSet<OsString> = HashSet::new(); // both `cache/` and `unrelated.txt` are extraneous

        let dst_dir = open_dst(&dst).await?;
        let summary = prune_entries(
            &PROGRESS,
            &dst_dir,
            std::path::Path::new(""),
            &keep,
            Some(&filter),
            &delete_settings(false),
            false,
            None,
            vec![
                (std::ffi::OsString::from("cache"), None),
                (
                    std::ffi::OsString::from("unrelated.txt"),
                    Some(crate::walk::EntryKind::File),
                ),
            ],
        )
        .await
        .map_err(|e| e.source)?;

        assert_eq!(summary.files_removed, 1); // unrelated.txt
        assert!(!dst.join("unrelated.txt").exists());
        assert!(
            dst.join("cache").exists(),
            "dir-only exclude `cache/` must protect the destination directory from --delete"
        );
        assert!(
            dst.join("cache").join("item.dat").exists(),
            "contents of the excluded directory must be preserved"
        );
        Ok(())
    }

    /// Repeatedly swap `dst/extra` between a real directory (holding a real file) and a symlink to
    /// an OUT-OF-TREE sentinel directory, using rename so each individual state is atomic. Two
    /// staging names live alongside `extra` and are renamed over it in a tight loop until `stop` is
    /// set. Runs on a dedicated OS thread so it makes progress regardless of the tokio runtime's
    /// scheduling. Mirrors rm's `spawn_dir_symlink_swapper`.
    fn spawn_extra_swapper(
        dst: std::path::PathBuf,
        sentinel: std::path::PathBuf,
        stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    ) -> std::thread::JoinHandle<()> {
        std::thread::spawn(move || {
            let extra = dst.join("extra");
            let staged_dir = dst.join("__staged_extra_dir");
            let staged_link = dst.join("__staged_extra_link");
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                // stage a real directory (with a real file) then swap it in over `extra`.
                let _ = std::fs::remove_dir_all(&staged_dir);
                if std::fs::create_dir(&staged_dir).is_ok() {
                    let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL");
                    // RENAME_EXCHANGE isn't portable here; remove-then-rename. The window where
                    // `extra` is briefly absent is fine — prune may error or no-op, an accepted
                    // failed-closed outcome. (prune must still never touch the sentinel.)
                    let _ = std::fs::remove_dir_all(&extra);
                    let _ = std::fs::remove_file(&extra);
                    let _ = std::fs::rename(&staged_dir, &extra);
                }
                // stage a symlink to the out-of-tree sentinel dir, then swap it in over `extra`.
                let _ = std::fs::remove_file(&staged_link);
                if std::os::unix::fs::symlink(&sentinel, &staged_link).is_ok() {
                    let _ = std::fs::remove_dir_all(&extra);
                    let _ = std::fs::remove_file(&extra);
                    let _ = std::fs::rename(&staged_link, &extra);
                }
            }
        })
    }

    /// While `prune_extraneous` prunes an extraneous destination SUBDIRECTORY (`dst/extra`, with no
    /// source counterpart so the empty keep-set marks it for deletion), a background thread rapidly
    /// flips `dst/extra` between a real directory and a symlink to a SENTINEL directory tree that
    /// lives OUTSIDE the destination, holding files that must never be deleted.
    ///
    /// Prune is fd-relative: it enumerates and removes children through the destination's own
    /// pinned `Dir` fd (`rm_child` → `child()` classify + `open_dir` descent). If `extra` is a
    /// symlink at the moment of descent, `open_dir`'s `O_NOFOLLOW|O_DIRECTORY` fails closed
    /// (ELOOP/ENOTDIR) and prune never follows it into the sentinel. If `extra` is a symlink at the
    /// moment of classification it is treated as a leaf and `unlink_at` removes the LINK, never its
    /// target. Either way the out-of-tree sentinel files survive — the core safety assertion,
    /// checked on every iteration regardless of timing. Also confirms the run terminates (per-op
    /// timeout) rather than hanging or following the link.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn prune_extra_dir_swap_never_deletes_out_of_tree_sentinel() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let root = tmp.path();
        // the sentinel tree lives OUTSIDE the destination, reachable only via the swapped symlink.
        let sentinel = root.join("sentinel_tree");
        tokio::fs::create_dir(&sentinel).await?;
        tokio::fs::write(sentinel.join("secret1.txt"), b"SECRET-1").await?;
        tokio::fs::create_dir(sentinel.join("subdir")).await?;
        tokio::fs::write(sentinel.join("subdir").join("secret2.txt"), b"SECRET-2").await?;

        let dst = root.join("dst");
        tokio::fs::create_dir(&dst).await?;

        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let swapper = spawn_extra_swapper(dst.clone(), sentinel.clone(), stop.clone());

        // empty keep-set: `extra` (and any other entry) is extraneous and marked for pruning.
        let keep: HashSet<OsString> = HashSet::new();
        let mut pruned = 0usize;
        let mut errored = 0usize;
        for i in 0..400 {
            // give `dst` many sibling extraneous subdirectories with files so prune spends real
            // time enumerating/removing them concurrently with the swapper's flips, widening the
            // window in which `extra` is classified/descended mid-swap.
            for d in 0..16 {
                let sib = dst.join(format!("sib_{d}"));
                let _ = tokio::fs::create_dir(&sib).await;
                for f in 0..4 {
                    let _ = tokio::fs::write(sib.join(format!("f{f}.txt")), b"x").await;
                }
            }
            let extra = dst.join("extra");
            if i % 2 == 0 {
                // deterministically place a symlink-to-sentinel at `extra` (best-effort; the
                // swapper may immediately flip it — both states are safe).
                let _ = tokio::fs::remove_dir_all(&extra).await;
                let _ = tokio::fs::remove_file(&extra).await;
                let _ = tokio::fs::symlink(&sentinel, &extra).await;
            } else if tokio::fs::symlink_metadata(&extra).await.is_err() {
                let _ = tokio::fs::create_dir(&extra).await;
                let _ = tokio::fs::write(extra.join("real.txt"), b"REAL").await;
            }
            // open the destination O_NOFOLLOW (as the real call sites do) and prune it.
            let dst_dir = open_dst(&dst).await?;
            let result = tokio::time::timeout(
                std::time::Duration::from_secs(30),
                prune_extraneous(
                    &PROGRESS,
                    &dst_dir,
                    std::path::Path::new(""),
                    &DeleteKeepSet::from_complete(delete_settings(false), (keep).clone()),
                    None,
                    false,
                    None,
                ),
            )
            .await
            .expect("prune must not hang under concurrent dir swapping");
            match result {
                Ok(_) => pruned += 1,
                Err(_) => errored += 1, // a swap was caught mid-walk (failed closed) — accepted
            }
            // CORE SAFETY ASSERTION (holds on every iteration regardless of timing): the
            // out-of-tree sentinel tree and its files are NEVER deleted — neither by following a
            // symlinked `extra` (unlink removes the link, not the target) nor by descending it
            // (open_dir's O_NOFOLLOW fails closed).
            assert!(
                sentinel.exists(),
                "iteration {i}: sentinel directory was deleted — prune followed the symlink"
            );
            let s1 = tokio::fs::read(sentinel.join("secret1.txt")).await;
            assert!(
                matches!(&s1, Ok(b) if b == b"SECRET-1"),
                "iteration {i}: sentinel/secret1.txt was deleted or altered — prune followed the symlink"
            );
            let s2 = tokio::fs::read(sentinel.join("subdir").join("secret2.txt")).await;
            assert!(
                matches!(&s2, Ok(b) if b == b"SECRET-2"),
                "iteration {i}: sentinel/subdir/secret2.txt was deleted — prune recursed through the symlink"
            );
        }

        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        swapper.join().expect("extra swapper thread panicked");
        // sanity (not the safety assertion): the run did observable work across the iterations.
        tracing::info!("prune extra-dir swap: pruned={pruned}, errored={errored}");
        assert!(
            pruned + errored > 0,
            "expected at least one observable outcome across the iterations"
        );
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn opening_dst_symlink_to_directory_fails_closed() -> anyhow::Result<()> {
        // prune operates through a `Dir` the caller opens `O_NOFOLLOW`. In a real --delete run the
        // create-or-overwrite step replaces any non-directory destination (including a symlink)
        // before prune runs; in --dry-run that overwrite is skipped, so the destination path could
        // still be a symlink-to-directory. Opening it `O_NOFOLLOW|O_DIRECTORY` (dereference=false) —
        // exactly what the copy/link prune call sites do — must fail closed on that symlink rather
        // than follow it. Prune can never receive a `Dir` that followed a destination symlink, so it
        // cannot preview or perform deletions outside the destination tree.
        let tmp = tempfile::tempdir()?;
        let dst_parent = tmp.path().join("dst_parent");
        let outside = tmp.path().join("outside"); // outside the destination tree
        tokio::fs::create_dir(&dst_parent).await?;
        tokio::fs::create_dir(&outside).await?;
        tokio::fs::write(outside.join("precious.txt"), b"keep me").await?;
        // dst is a symlink-to-directory living under the parent we'd prune.
        let dst = dst_parent.join("link_dir");
        std::os::unix::fs::symlink(&outside, &dst)?;

        // opening the symlinked dst O_NOFOLLOW must fail (ELOOP), so the call site skips prune.
        let result = Dir::open_root_dir(&dst, false, congestion::Side::Destination).await;
        assert!(
            result.is_err(),
            "opening a dst symlink-to-directory O_NOFOLLOW must fail closed, not follow it"
        );
        // the out-of-tree tree is untouched.
        assert!(outside.join("precious.txt").exists());
        Ok(())
    }
}