irontide-storage 1.0.1

Piece storage, verification, and disk I/O for BitTorrent
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
use parking_lot::Mutex;
use std::fs::{self, File};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use irontide_core::Lengths;
use serde::{Deserialize, Serialize};

use crate::Result;
use crate::error::Error;
use crate::file_map::FileMap;
use crate::storage::TorrentStorage;

/// Pre-allocation strategy for torrent files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum PreallocateMode {
    /// No pre-allocation — files created sparse via `set_len`.
    #[default]
    None,
    /// Reserve extents without write amplification (`FALLOC_FL_KEEP_SIZE` on Linux).
    /// Falls back to `None` on unsupported filesystems.
    Sparse,
    /// Full allocation — `fallocate(0)` on Linux, falls back to writing zeros.
    Full,
}

impl From<bool> for PreallocateMode {
    fn from(preallocate: bool) -> Self {
        if preallocate { Self::Full } else { Self::None }
    }
}

/// Disk-backed storage using one file handle per torrent file.
///
/// File handles are lazily opened on first access and locked per-file
/// so different pieces mapping to different files can be written concurrently.
/// Files are created as sparse (pre-allocated with `set_len`).
pub struct FilesystemStorage {
    base_dir: PathBuf,
    file_paths: Vec<PathBuf>,
    files: Vec<Mutex<Option<File>>>,
    file_map: FileMap,
    lengths: Lengths,
    /// When true, open files with `O_DIRECT` (Linux/FreeBSD) or `F_NOCACHE`
    /// (macOS) to bypass the kernel page cache.
    direct_io: bool,
}

impl FilesystemStorage {
    /// Create a new filesystem storage.
    ///
    /// Creates the directory structure and sparse files on disk.
    ///
    /// When `direct_io` is `true`, file handles are opened with
    /// `O_DIRECT` (Linux/FreeBSD) or `F_NOCACHE` (macOS) to bypass
    /// the kernel page cache.
    ///
    /// # Errors
    ///
    /// Returns an error if directory creation, file creation, or
    /// preallocation fails.
    #[allow(clippy::needless_pass_by_value, reason = "pub API stability")]
    pub fn new(
        base_dir: &Path,
        file_paths: Vec<PathBuf>,
        file_lengths: Vec<u64>,
        lengths: Lengths,
        file_priorities: Option<&[irontide_core::FilePriority]>,
        mode: PreallocateMode,
        direct_io: bool,
    ) -> Result<Self> {
        let file_map = FileMap::new(file_lengths.clone(), lengths.clone());

        // Pre-create directories and sparse files.
        for (i, path) in file_paths.iter().enumerate() {
            // Skip file creation for Skip-priority files
            if let Some(priorities) = file_priorities
                && priorities.get(i).copied() == Some(irontide_core::FilePriority::Skip)
            {
                continue;
            }

            let full = base_dir.join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent)?;
            }
            // Open existing or create. Avoid `File::create` because it
            // truncates — that destroys pre-existing payload bytes before
            // `TorrentActor::run` gets a chance to call
            // `verify_existing_pieces`, breaking the auto-restore /
            // seed-existing-files path documented in M161.
            let f = File::options()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&full)?;
            Self::preallocate_file(&f, file_lengths[i], mode)?;
        }

        let files = (0..file_paths.len()).map(|_| Mutex::new(None)).collect();

        Ok(Self {
            base_dir: base_dir.to_owned(),
            file_paths,
            files,
            file_map,
            lengths,
            direct_io,
        })
    }

    /// Pre-allocate a file according to the given mode.
    ///
    /// - `None`: sparse file via `set_len` only.
    /// - `Sparse`: reserve extents without write amplification
    ///   (`FALLOC_FL_KEEP_SIZE` on Linux, falls back to `None`).
    /// - `Full`: `fallocate(0)` on Linux, falls back to writing zeros.
    fn preallocate_file(f: &File, length: u64, mode: PreallocateMode) -> Result<()> {
        match mode {
            PreallocateMode::None => {
                f.set_len(length)?;
            }
            PreallocateMode::Sparse => {
                // Reserve extents without zeroing — great for SSDs.
                // M175: 64-bit Linux only; 32-bit Linux's `off_t == i32` would
                // silently truncate `length > 2 GiB`. Falls through to set_len.
                #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
                {
                    use std::os::unix::io::AsRawFd;
                    #[allow(
                        clippy::cast_possible_wrap,
                        reason = "off_t == i64 on 64-bit; length capped by realistic filesystem limits"
                    )]
                    let ret = unsafe {
                        libc::fallocate(
                            f.as_raw_fd(),
                            libc::FALLOC_FL_KEEP_SIZE,
                            0,
                            length as libc::off_t,
                        )
                    };
                    if ret == 0 {
                        // Also set the file length so reads past the end
                        // don't return short.
                        f.set_len(length)?;
                        return Ok(());
                    }
                    // EOPNOTSUPP / ENOTSUP — fall through to sparse.
                }
                f.set_len(length)?;
            }
            PreallocateMode::Full => {
                #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
                {
                    use std::os::unix::io::AsRawFd;
                    #[allow(
                        clippy::cast_possible_wrap,
                        reason = "off_t == i64 on 64-bit; length capped by realistic filesystem limits"
                    )]
                    let ret =
                        unsafe { libc::fallocate(f.as_raw_fd(), 0, 0, length as libc::off_t) };
                    if ret == 0 {
                        return Ok(());
                    }
                    // Fallback on error (e.g. filesystem doesn't support fallocate)
                }

                f.set_len(length)?;

                // Write zeros in chunks to actually allocate blocks.
                if length > 0 {
                    // M175 BUG FIX: previous code was `(remaining as usize).min(zeros.len())`,
                    // which on 32-bit Linux for files > 4 GiB truncates `remaining` first
                    // and could compute n < zeros.len() incorrectly, slowing or hanging
                    // the allocator loop. Bounding in `u64` first then narrowing fixes it.
                    #[allow(
                        clippy::cast_possible_truncation,
                        reason = "chunk_size = min(65536, length) ≤ 65536, fits usize on every supported target"
                    )]
                    let chunk_size = u64::min(65536, length) as usize;
                    let zeros = vec![0u8; chunk_size];
                    let mut writer = std::io::BufWriter::new(f);
                    let mut remaining = length;
                    while remaining > 0 {
                        #[allow(
                            clippy::cast_possible_truncation,
                            reason = "step ≤ chunk_size ≤ 65536, fits usize on every supported target"
                        )]
                        let n = u64::min(remaining, chunk_size as u64) as usize;
                        writer.write_all(&zeros[..n])?;
                        remaining -= n as u64;
                    }
                }
            }
        }
        Ok(())
    }

    /// Open (or return cached) file handle for the given file index.
    ///
    /// When `self.direct_io` is enabled, applies platform-specific flags
    /// to bypass the kernel page cache:
    /// - Linux/FreeBSD: `O_DIRECT` via `OpenOptionsExt::custom_flags`
    /// - macOS: `F_NOCACHE` via `fcntl` after open
    fn open_file(&self, index: usize) -> Result<parking_lot::MutexGuard<'_, Option<File>>> {
        let mut guard = self.files[index].lock();
        if guard.is_none() {
            let full = self.base_dir.join(&self.file_paths[index]);

            let mut opts = File::options();
            opts.read(true).write(true);

            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            if self.direct_io {
                use std::os::unix::fs::OpenOptionsExt;
                opts.custom_flags(libc::O_DIRECT);
            }

            let f = opts.open(&full)?;

            #[cfg(target_os = "macos")]
            if self.direct_io {
                use std::os::unix::io::AsRawFd;
                // SAFETY: `fcntl` with `F_NOCACHE` is a well-defined operation
                // on a valid file descriptor. The `1` argument enables the flag.
                unsafe {
                    libc::fcntl(f.as_raw_fd(), libc::F_NOCACHE, 1);
                }
            }

            *guard = Some(f);
        }
        Ok(guard)
    }
}

/// Write all data via `pwritev(2)`, retrying on short writes and EINTR.
///
/// Eliminates the seek syscall entirely — the file offset is passed as a parameter.
/// For ring-buffer straddle writes, two `IoSlice` entries handle the split in a
/// single atomic syscall.
///
/// Gated on `target_pointer_width = "64"` (M175): on 32-bit Linux without
/// `_FILE_OFFSET_BITS=64`, `libc::off_t` is `i32` and a `u64 → off_t` cast on
/// the offset would silently truncate at 2 GiB, corrupting any seed > 2 GiB.
/// 32-bit targets fall through to the `seek+write_all` path, which goes through
/// `std::fs::File::seek` (LFS-correct on Linux via the standard library).
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
fn pwritev_all(
    fd: std::os::unix::io::RawFd,
    bufs: &[std::io::IoSlice<'_>],
    offset: u64,
) -> std::io::Result<()> {
    let total: usize = bufs.iter().map(|b| b.len()).sum();
    if total == 0 {
        return Ok(());
    }

    let mut written = 0usize;
    loop {
        // Build adjusted iovec, skipping already-written bytes.
        let mut iov: smallvec::SmallVec<[std::io::IoSlice<'_>; 2]> = smallvec::SmallVec::new();
        let mut to_skip = written;
        for buf in bufs {
            let slice: &[u8] = buf;
            if to_skip >= slice.len() {
                to_skip -= slice.len();
                continue;
            }
            iov.push(std::io::IoSlice::new(&slice[to_skip..]));
            to_skip = 0;
        }

        // Cast safety on 64-bit Linux (M175):
        //  - `iov.len()` is bounded by SmallVec<[_; 2]>::push at this site;
        //    the call-site at write_chunk_vectored constructs at most 2 entries.
        //  - `offset + written as u64` overflows i64 only at >8 EiB offsets,
        //    well past any realistic file size; `libc::off_t == i64` on this cfg.
        //  - `ret as usize` after the `ret < 0` early-return is sign-safe.
        let ret = unsafe {
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_possible_wrap,
                reason = "iov.len() ≤ 2 (SmallVec<[_; 2]> at call site); off_t == i64 on 64-bit"
            )]
            libc::pwritev(
                fd,
                iov.as_ptr().cast::<libc::iovec>(),
                iov.len() as libc::c_int,
                (offset + written as u64) as libc::off_t,
            )
        };

        if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(err);
        }

        #[allow(
            clippy::cast_sign_loss,
            reason = "ret < 0 short-circuits above; ret here is non-negative"
        )]
        let advance = ret as usize;
        written += advance;
        if written >= total {
            return Ok(());
        }
    }
}

impl TorrentStorage for FilesystemStorage {
    fn write_chunk(&self, piece: u32, begin: u32, data: &[u8]) -> Result<()> {
        #[allow(
            clippy::cast_possible_truncation,
            reason = "data.len() ≤ piece_length ≤ 4 GiB (bounded by Lengths::piece_length: u32 by construction)"
        )]
        let segments = self
            .file_map
            .chunk_segments(piece, begin, data.len() as u32);
        let mut written = 0usize;

        for seg in &segments {
            let mut guard = self.open_file(seg.file_index)?;
            let f = guard.as_mut().unwrap();
            f.seek(SeekFrom::Start(seg.file_offset))?;
            f.write_all(&data[written..written + seg.len as usize])?;
            written += seg.len as usize;
        }

        Ok(())
    }

    fn write_chunk_vectored(&self, piece: u32, begin: u32, s0: &[u8], s1: &[u8]) -> Result<()> {
        let total_len = s0.len() + s1.len();
        #[allow(
            clippy::cast_possible_truncation,
            reason = "total_len ≤ piece_length ≤ 4 GiB (bounded by Lengths::piece_length: u32 by construction)"
        )]
        let segments = self.file_map.chunk_segments(piece, begin, total_len as u32);
        let mut pos = 0usize;

        for seg in &segments {
            let seg_len = seg.len as usize;
            let seg_end = pos + seg_len;

            // On 64-bit Linux, use pwritev(2) — no seek needed, single syscall for
            // ring-buffer straddle writes. M175: 32-bit Linux falls through to
            // the seek+write_all path because `libc::off_t == i32` would silently
            // truncate offsets > 2 GiB.
            #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
            {
                use std::io::IoSlice;
                use std::os::unix::io::AsRawFd;

                let guard = self.open_file(seg.file_index)?;
                let f = guard.as_ref().unwrap();
                let fd = f.as_raw_fd();

                if seg_end <= s0.len() {
                    let bufs = [IoSlice::new(&s0[pos..seg_end])];
                    pwritev_all(fd, &bufs, seg.file_offset)?;
                } else if pos >= s0.len() {
                    let s1_start = pos - s0.len();
                    let s1_end = seg_end - s0.len();
                    let bufs = [IoSlice::new(&s1[s1_start..s1_end])];
                    pwritev_all(fd, &bufs, seg.file_offset)?;
                } else {
                    // Straddle: two IoSlice entries, one pwritev call.
                    let from_s0 = &s0[pos..];
                    let s1_need = seg_len - from_s0.len();
                    let bufs = [IoSlice::new(from_s0), IoSlice::new(&s1[..s1_need])];
                    pwritev_all(fd, &bufs, seg.file_offset)?;
                }
            }

            // Fallback for non-Linux and 32-bit Linux: seek + write_all (LFS-correct
            // via std::fs::File on Linux without needing the FFI off_t dance).
            #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
            {
                let mut guard = self.open_file(seg.file_index)?;
                let f = guard.as_mut().unwrap();
                f.seek(SeekFrom::Start(seg.file_offset))?;

                if seg_end <= s0.len() {
                    f.write_all(&s0[pos..seg_end])?;
                } else if pos >= s0.len() {
                    let s1_start = pos - s0.len();
                    let s1_end = seg_end - s0.len();
                    f.write_all(&s1[s1_start..s1_end])?;
                } else {
                    let from_s0 = &s0[pos..];
                    let s1_need = seg_len - from_s0.len();
                    f.write_all(from_s0)?;
                    f.write_all(&s1[..s1_need])?;
                }
            }

            pos = seg_end;
        }

        Ok(())
    }

    fn read_chunk(&self, piece: u32, begin: u32, length: u32) -> Result<Vec<u8>> {
        let segments = self.file_map.chunk_segments(piece, begin, length);
        let mut buf = vec![0u8; length as usize];
        let mut offset = 0usize;

        for seg in &segments {
            let mut guard = self.open_file(seg.file_index)?;
            let f = guard.as_mut().unwrap();
            f.seek(SeekFrom::Start(seg.file_offset))?;
            f.read_exact(&mut buf[offset..offset + seg.len as usize])?;
            offset += seg.len as usize;
        }

        Ok(buf)
    }

    fn read_piece(&self, piece: u32) -> Result<Vec<u8>> {
        let piece_size = self.lengths.piece_size(piece);
        if piece_size == 0 {
            return Err(Error::PieceOutOfRange {
                index: piece,
                num_pieces: self.lengths.num_pieces(),
            });
        }
        self.read_chunk(piece, 0, piece_size)
    }

    fn verify_piece(&self, piece: u32, expected: &irontide_core::Id20) -> Result<bool> {
        let piece_size = self.lengths.piece_size(piece);
        if piece_size == 0 {
            return Err(Error::PieceOutOfRange {
                index: piece,
                num_pieces: self.lengths.num_pieces(),
            });
        }
        let segments = self.file_map.piece_segments(piece);
        let buf_size = (piece_size as usize).min(65536);
        let mut buf = vec![0u8; buf_size];
        let mut hasher = irontide_core::Sha1Hasher::new();

        for seg in &segments {
            let mut guard = self.open_file(seg.file_index)?;
            let f = guard.as_mut().unwrap();
            f.seek(SeekFrom::Start(seg.file_offset))?;
            let mut remaining = seg.len as usize;
            while remaining > 0 {
                let n = remaining.min(buf_size);
                f.read_exact(&mut buf[..n])?;
                hasher.update(&buf[..n]);
                remaining -= n;
            }
        }

        let actual = hasher.finish();
        Ok(actual == *expected)
    }

    fn filesystem_info(
        &self,
    ) -> Option<(
        &std::path::Path,
        &[std::path::PathBuf],
        &crate::file_map::FileMap,
    )> {
        Some((&self.base_dir, &self.file_paths, &self.file_map))
    }
}

/// Delete the on-disk files of a torrent and prune empty ancestor
/// directories (M170 — qBt `/torrents/delete?deleteFiles=true`).
///
/// `download_dir` is the torrent root (the directory the torrent was
/// added under). `file_paths` are the relative paths of the torrent's
/// files as recorded in the info dict — they are joined with
/// `download_dir` before each `remove_file` call.
///
/// After each successful file removal, empty parent directories are
/// pruned upward toward `download_dir`. The walk stops at the first
/// non-empty directory (indicated by `remove_dir` returning any error —
/// POSIX `rmdir` sets `ENOTEMPTY` in that case, and any other error is
/// treated as a reason to stop). The walk also stops before ever
/// touching `download_dir` itself. Non-empty directories are deliberately
/// preserved — that matches qBittorrent's "clean only what we own"
/// semantic.
///
/// # Lenient error taxonomy
///
/// This function matches real qBittorrent's behaviour: it never bails
/// out on I/O errors, only logs and continues.
///
/// - `ENOENT` (file already gone) → silent skip
/// - `EACCES` / `EPERM` (permissions) → `warn!` + continue
/// - `EBUSY` (file in use) → `warn!` + continue
/// - any other I/O error → `error!` + continue
///
/// On entry, callers MUST have already closed any open file handles —
/// this is the caller's responsibility. On Windows the rename would
/// otherwise fail with "file is being used by another process"; on
/// Unix an open fd leaves the inode behind after unlink.
///
/// This function is synchronous and intended to be invoked from a
/// `tokio::task::spawn_blocking` context by the session actor.
#[allow(clippy::needless_pass_by_value)] // ownership makes the closure simpler
pub fn delete_torrent_files_sync(download_dir: PathBuf, file_paths: Vec<PathBuf>) {
    use tracing::{error, warn};

    for rel in &file_paths {
        let full = download_dir.join(rel);
        match std::fs::remove_file(&full) {
            Ok(()) => {
                // Prune empty ancestor dirs up to download_dir (exclusive).
                prune_empty_parents(&download_dir, &full);
            }
            Err(e) => match e.kind() {
                std::io::ErrorKind::NotFound => {
                    // Silent — file already gone.
                }
                std::io::ErrorKind::PermissionDenied => {
                    warn!(
                        path = %full.display(),
                        error = %e,
                        "permission denied removing torrent file — continuing"
                    );
                }
                _ => {
                    // Raw OS error EBUSY (26) shows up here as Other on
                    // Linux; treat it (and any other I/O) with a warn —
                    // only truly unexpected errors escalate to error!().
                    let raw = e.raw_os_error();
                    if raw == Some(libc_ebusy()) {
                        warn!(
                            path = %full.display(),
                            error = %e,
                            "torrent file is busy — skipping"
                        );
                    } else {
                        error!(
                            path = %full.display(),
                            error = %e,
                            "failed to remove torrent file"
                        );
                    }
                }
            },
        }
    }
}

/// Walk upward from `file_path`'s parent directory, calling `remove_dir`
/// on each ancestor until either:
///   - the directory is non-empty (`remove_dir` fails — stop), or
///   - we have reached `download_dir` (never touch the root).
///
/// All errors are ignored — non-empty directories legitimately stop the
/// walk, and any other error is fine to leave in place.
fn prune_empty_parents(download_dir: &Path, file_path: &Path) {
    // Canonicalise `download_dir` guard-wise: we compare prefix-equality
    // against the file path, so both sides need to be treated as-is (we
    // were passed a plain join'd path earlier).
    let Some(mut cursor) = file_path.parent() else {
        return;
    };
    loop {
        // Never remove `download_dir` itself — this guards against the
        // degenerate case where `download_dir` is empty after deletion.
        if cursor == download_dir {
            break;
        }
        // Defensive: if somehow we walked above `download_dir` (e.g. via
        // `..` that escaped), stop immediately.
        if !cursor.starts_with(download_dir) {
            break;
        }
        // rmdir fails on non-empty -> break; on ENOENT (already gone) ->
        // keep going up. Any other error: stop.
        match std::fs::remove_dir(cursor) {
            Ok(()) => {
                // Parent may now be empty — climb.
                let Some(parent) = cursor.parent() else {
                    break;
                };
                cursor = parent;
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                let Some(parent) = cursor.parent() else {
                    break;
                };
                cursor = parent;
            }
            Err(_) => break,
        }
    }
}

/// EBUSY raw errno — portable lookup so we don't hard-code `26` inline.
#[inline]
fn libc_ebusy() -> i32 {
    #[cfg(unix)]
    {
        libc::EBUSY
    }
    #[cfg(not(unix))]
    {
        // Windows has no EBUSY — any "sharing violation" manifests as
        // Other. Return a sentinel that won't match real Windows errno.
        -1
    }
}

#[cfg(test)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap,
    reason = "test code — fixtures use small bounded sizes that fit narrower types"
)]
mod tests {
    use std::sync::Arc;
    use std::thread;

    use irontide_core::{Id20, Lengths};

    use super::*;
    use crate::filesystem::PreallocateMode;

    fn temp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir()
            .join(format!("torrent-test-{}", std::process::id()))
            .join(name);
        let _ = fs::remove_dir_all(&dir);
        dir
    }

    #[test]
    fn single_file_write_read() {
        let dir = temp_dir("single");
        let lengths = Lengths::new(100, 50, 25);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![42u8; 25];
        s.write_chunk(0, 0, &data).unwrap();
        let read = s.read_chunk(0, 0, 25).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn multi_file_write_read() {
        let dir = temp_dir("multi");
        let lengths = Lengths::new(200, 150, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("a.bin"), PathBuf::from("b.bin")],
            vec![100, 100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Write chunk spanning files: piece 0, begin 50, 100 bytes
        // Piece 0 starts at offset 0. begin=50 → abs offset 50.
        // File a: 50..100 (50 bytes), file b: 0..50 (50 bytes)
        let data: Vec<u8> = (0..100).collect();
        s.write_chunk(0, 50, &data).unwrap();
        let read = s.read_chunk(0, 50, 100).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn read_piece() {
        let dir = temp_dir("readpiece");
        let lengths = Lengths::new(100, 50, 25);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![7u8; 50];
        s.write_chunk(0, 0, &data).unwrap();
        let piece = s.read_piece(0).unwrap();
        assert_eq!(piece, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn verify_piece() {
        let dir = temp_dir("verify");
        let lengths = Lengths::new(100, 50, 25);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![9u8; 50];
        s.write_chunk(0, 0, &data).unwrap();

        let expected = irontide_core::sha1(&data);
        assert!(s.verify_piece(0, &expected).unwrap());
        assert!(!s.verify_piece(0, &Id20::ZERO).unwrap());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn creates_directories() {
        let dir = temp_dir("dirs");
        let lengths = Lengths::new(100, 100, 16384);
        let _s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("sub/dir/test.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        assert!(dir.join("sub/dir/test.bin").exists());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn creates_sparse_files() {
        let dir = temp_dir("sparse");
        let lengths = Lengths::new(1_000_000, 500_000, 16384);
        let _s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("big.bin")],
            vec![1_000_000],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let meta = fs::metadata(dir.join("big.bin")).unwrap();
        assert_eq!(meta.len(), 1_000_000);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn last_piece_shorter() {
        let dir = temp_dir("lastpiece");
        // 75 bytes total, 50 byte pieces → piece 0 = 50, piece 1 = 25
        let lengths = Lengths::new(75, 50, 25);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![75],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![3u8; 25];
        s.write_chunk(1, 0, &data).unwrap();
        let piece = s.read_piece(1).unwrap();
        assert_eq!(piece, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn concurrent_different_pieces() {
        let dir = temp_dir("concurrent");
        let lengths = Lengths::new(200, 100, 50);
        let s = Arc::new(
            FilesystemStorage::new(
                &dir,
                vec![PathBuf::from("a.bin"), PathBuf::from("b.bin")],
                vec![100, 100],
                lengths,
                None,
                PreallocateMode::None,
                false,
            )
            .unwrap(),
        );

        let s0 = Arc::clone(&s);
        let t0 = thread::spawn(move || {
            let data = vec![1u8; 100];
            s0.write_chunk(0, 0, &data).unwrap();
        });

        let s1 = Arc::clone(&s);
        let t1 = thread::spawn(move || {
            let data = vec![2u8; 100];
            s1.write_chunk(1, 0, &data).unwrap();
        });

        t0.join().unwrap();
        t1.join().unwrap();

        let p0 = s.read_piece(0).unwrap();
        let p1 = s.read_piece(1).unwrap();
        assert_eq!(p0, vec![1u8; 100]);
        assert_eq!(p1, vec![2u8; 100]);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn skip_priority_file_not_created() {
        use irontide_core::FilePriority;

        let dir = temp_dir("skip_alloc");
        let lengths = Lengths::new(200, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("wanted.bin"), PathBuf::from("skipped.bin")],
            vec![100, 100],
            lengths,
            Some(&[FilePriority::Normal, FilePriority::Skip]),
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // wanted.bin should exist
        assert!(dir.join("wanted.bin").exists());
        // skipped.bin should NOT exist
        assert!(!dir.join("skipped.bin").exists());

        // Writing to wanted.bin should still work
        let data = vec![42u8; 50];
        s.write_chunk(0, 0, &data).unwrap();
        let read = s.read_chunk(0, 0, 50).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn streaming_verify_matches_full_read() {
        let dir = temp_dir("streaming_verify");
        // 262144 bytes = 256 KiB, large enough to exercise 64 KiB chunked reads
        let total = 262_144_u64;
        let lengths = Lengths::new(total, total, 16384);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![total],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Fill with patterned data
        let data: Vec<u8> = (0..total as usize).map(|i| (i % 251) as u8).collect();
        s.write_chunk(0, 0, &data).unwrap();

        // Compute expected hash via full read path
        let full_piece = s.read_piece(0).unwrap();
        let expected = irontide_core::sha1(&full_piece);

        // Streaming verify should produce the same result
        assert!(s.verify_piece(0, &expected).unwrap());
        assert!(!s.verify_piece(0, &Id20::ZERO).unwrap());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn streaming_verify_small_piece() {
        let dir = temp_dir("streaming_small");
        // 100 bytes — smaller than 64 KiB buffer
        let lengths = Lengths::new(100, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("small.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![0xABu8; 100];
        s.write_chunk(0, 0, &data).unwrap();

        let expected = irontide_core::sha1(&data);
        assert!(s.verify_piece(0, &expected).unwrap());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn full_preallocation() {
        let dir = temp_dir("prealloc");
        let lengths = Lengths::new(100_000, 50_000, 16384);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100_000],
            lengths,
            None,
            PreallocateMode::Full,
            false,
        )
        .unwrap();

        // File should exist with correct size
        let meta = fs::metadata(dir.join("test.bin")).unwrap();
        assert_eq!(meta.len(), 100_000);

        // On Linux, blocks should be allocated (not sparse)
        #[cfg(target_os = "linux")]
        {
            use std::os::linux::fs::MetadataExt;
            // 512-byte blocks, should have at least total_size/512 blocks
            assert!(meta.st_blocks() * 512 >= 100_000);
        }

        // I/O still works
        let data = vec![42u8; 16384];
        s.write_chunk(0, 0, &data).unwrap();
        let read = s.read_chunk(0, 0, 16384).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    /// M175 regression: previously the full-preallocation loop computed
    /// `n = (remaining as usize).min(zeros.len())`, which on 32-bit Linux
    /// could truncate `remaining > usize::MAX` *before* the `min`, returning
    /// a step smaller than the chunk size and stalling the allocator on
    /// files > 4 GiB. New form uses `u64::min(remaining, chunk_size as u64)
    /// as usize` so the bound is established before the narrowing cast.
    /// The invariant: `n` is always in `(0, min(remaining, chunk_size)]`.
    #[test]
    fn full_preallocation_chunk_step_invariant() {
        fn step(remaining: u64, chunk_size: u64) -> u64 {
            // Mirror of the fixed loop body — keep in sync with filesystem.rs:
            // chunk_size = u64::min(65536, length); n = u64::min(remaining, chunk_size as u64) as usize
            // The cast back to u64 here only widens, so the invariant is preserved.
            u64::min(remaining, chunk_size)
        }

        let chunk = 65536u64;
        // Exact-fit boundaries.
        assert_eq!(step(chunk, chunk), chunk);
        assert_eq!(step(chunk - 1, chunk), chunk - 1);
        assert_eq!(step(1, chunk), 1);

        // > 4 GiB scenario — what 32-bit truncation would have broken.
        let four_gib_plus_64 = (1u64 << 32) + 64;
        assert_eq!(
            step(four_gib_plus_64, chunk),
            chunk,
            "must clamp to chunk_size, not the truncated remainder"
        );

        // > 8 EiB still terminates.
        assert_eq!(step(u64::MAX, chunk), chunk);

        // Tiny torrent (chunk_size capped at length).
        assert_eq!(step(7, 7), 7);
        assert_eq!(step(3, 7), 3);
    }

    // ── write_chunk_vectored tests ────────────────────────────────────

    #[test]
    fn write_chunk_vectored_single_file() {
        let dir = temp_dir("vec_single");
        let lengths = Lengths::new(200, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![200],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Simulate ring-buffer wrap: first 30 bytes in s0, last 20 in s1.
        let s0: Vec<u8> = (0..30).collect();
        let s1: Vec<u8> = (30..50).collect();
        s.write_chunk_vectored(0, 10, &s0, &s1).unwrap();

        let read = s.read_chunk(0, 10, 50).unwrap();
        let expected: Vec<u8> = (0..50).collect();
        assert_eq!(read, expected);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn write_chunk_vectored_file_boundary() {
        let dir = temp_dir("vec_boundary");
        // 200 bytes total, 150-byte pieces, two files of 100 bytes each.
        // Piece 0 starts at abs offset 0, spans files a (0..100) and b (0..50).
        let lengths = Lengths::new(200, 150, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("a.bin"), PathBuf::from("b.bin")],
            vec![100, 100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Write 100 bytes at piece 0, begin 50 → abs offset 50.
        // File a: 50..100 (50 bytes), file b: 0..50 (50 bytes).
        // Split: s0 = 60 bytes, s1 = 40 bytes.
        // s0 covers file-a's 50 bytes + 10 bytes into file-b.
        // s1 covers the remaining 40 bytes in file-b.
        let s0: Vec<u8> = (0..60).collect();
        let s1: Vec<u8> = (60..100).collect();
        s.write_chunk_vectored(0, 50, &s0, &s1).unwrap();

        let read = s.read_chunk(0, 50, 100).unwrap();
        let expected: Vec<u8> = (0..100).collect();
        assert_eq!(read, expected);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn write_chunk_vectored_empty_s1() {
        let dir = temp_dir("vec_empty_s1");
        let lengths = Lengths::new(100, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Common case: contiguous buffer, s1 is empty.
        let data = vec![0xABu8; 50];
        s.write_chunk_vectored(0, 0, &data, &[]).unwrap();

        let read = s.read_chunk(0, 0, 50).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    // ── pwritev tests ────────────────────────────────────────────────

    #[test]
    fn pwritev_single_file_contiguous() {
        // Single contiguous buffer write (s1 empty) via pwritev path.
        let dir = temp_dir("pwritev_contig");
        let lengths = Lengths::new(200, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![200],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data: Vec<u8> = (0..50).collect();
        s.write_chunk_vectored(0, 25, &data, &[]).unwrap();

        let read = s.read_chunk(0, 25, 50).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn pwritev_single_file_split() {
        // Two-segment ring-wrap write within a single file.
        let dir = temp_dir("pwritev_split");
        let lengths = Lengths::new(200, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![200],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Ring buffer wrap: 35 bytes in s0, 15 bytes in s1.
        let s0: Vec<u8> = (0..35).collect();
        let s1: Vec<u8> = (35..50).collect();
        s.write_chunk_vectored(0, 0, &s0, &s1).unwrap();

        let read = s.read_chunk(0, 0, 50).unwrap();
        let expected: Vec<u8> = (0..50).collect();
        assert_eq!(read, expected);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn pwritev_multi_file_boundary() {
        // Write spanning a file boundary with ring-buffer split.
        let dir = temp_dir("pwritev_multi");
        // Two files of 80 bytes each (160 total), 100-byte pieces.
        let lengths = Lengths::new(160, 100, 50);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("a.bin"), PathBuf::from("b.bin")],
            vec![80, 80],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        // Write 60 bytes at piece 0, begin 50 → abs offset 50.
        // File a: offset 50..80 (30 bytes), file b: offset 0..30 (30 bytes).
        // Ring split: s0 = 40 bytes, s1 = 20 bytes.
        let s0: Vec<u8> = (0..40).collect();
        let s1: Vec<u8> = (40..60).collect();
        s.write_chunk_vectored(0, 50, &s0, &s1).unwrap();

        let read = s.read_chunk(0, 50, 60).unwrap();
        let expected: Vec<u8> = (0..60).collect();
        assert_eq!(read, expected);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn sparse_fallocate_reserves_blocks() {
        use std::os::linux::fs::MetadataExt;

        let dir = temp_dir("sparse_falloc");
        let lengths = Lengths::new(100_000, 100_000, 16384);
        let _s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100_000],
            lengths,
            None,
            PreallocateMode::Sparse,
            false,
        )
        .unwrap();

        let meta = fs::metadata(dir.join("test.bin")).unwrap();
        assert_eq!(meta.len(), 100_000);
        // Sparse fallocate should reserve blocks (st_blocks > 0) on
        // filesystems that support FALLOC_FL_KEEP_SIZE (ext4, btrfs, bcachefs)
        // but tmpfs reports 0. The key invariant — that the call did not
        // error — is already enforced by the FilesystemStorage::new() unwrap
        // above, so we don't assert on st_blocks here.
        let _ = meta.st_blocks();

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn sparse_fallocate_degradation() {
        // Verify Sparse mode degrades gracefully: it should never panic or
        // return an error, even if the filesystem doesn't support
        // FALLOC_FL_KEEP_SIZE.
        let dir = temp_dir("sparse_degrade");
        let lengths = Lengths::new(1000, 1000, 500);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![1000],
            lengths,
            None,
            PreallocateMode::Sparse,
            false,
        )
        .unwrap();

        // File must exist with correct length regardless of fallocate support.
        let meta = fs::metadata(dir.join("test.bin")).unwrap();
        assert_eq!(meta.len(), 1000);

        // I/O must still work after sparse preallocation.
        let data = vec![0xCDu8; 500];
        s.write_chunk(0, 0, &data).unwrap();
        let read = s.read_chunk(0, 0, 500).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn prealloc_mode_from_bool_backward_compat() {
        assert_eq!(PreallocateMode::from(false), PreallocateMode::None);
        assert_eq!(PreallocateMode::from(true), PreallocateMode::Full);
    }

    // ── direct I/O tests ─────────────────────────────────────────────

    #[test]
    fn direct_io_field_stored() {
        let dir = temp_dir("dio_field");
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![100],
            Lengths::new(100, 100, 50),
            None,
            PreallocateMode::None,
            true,
        )
        .unwrap();

        assert!(s.direct_io, "direct_io field should be stored as true");

        let s2 = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test2.bin")],
            vec![100],
            Lengths::new(100, 100, 50),
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        assert!(!s2.direct_io, "direct_io field should be stored as false");

        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn direct_io_write_read_aligned() {
        // O_DIRECT requires filesystem support and aligned I/O.
        // tmpfs does not support O_DIRECT, so this test gracefully skips.
        let dir = tempfile::tempdir().expect("tempdir");
        let lengths = Lengths::new(16384, 16384, 16384);
        let result = FilesystemStorage::new(
            dir.path(),
            vec![PathBuf::from("test.bin")],
            vec![16384],
            lengths,
            None,
            PreallocateMode::None,
            true,
        );
        let storage = match result {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Skipping direct_io test: storage creation failed: {e}");
                return;
            }
        };
        // 16 KiB is always page-aligned, satisfying O_DIRECT requirements.
        let data = vec![0xAB_u8; 16384];
        match storage.write_chunk(0, 0, &data) {
            Ok(()) => {
                let read = storage.read_chunk(0, 0, 16384).expect("aligned read");
                assert_eq!(read, data);
            }
            Err(e) => {
                eprintln!("Skipping: O_DIRECT write failed (expected on tmpfs): {e}");
            }
        }
    }

    #[test]
    fn non_direct_io_write_read() {
        // Baseline: direct_io=false should always work on any filesystem.
        let dir = temp_dir("dio_off");
        let lengths = Lengths::new(16384, 16384, 16384);
        let s = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![16384],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let data = vec![0xCD_u8; 16384];
        s.write_chunk(0, 0, &data).unwrap();
        let read = s.read_chunk(0, 0, 16384).unwrap();
        assert_eq!(read, data);

        fs::remove_dir_all(&dir).unwrap();
    }

    // ── M170: delete_torrent_files_sync tests ────────────────────────

    #[test]
    fn delete_removes_single_file_and_prunes_empty_parent() {
        let dir = temp_dir("del_single");
        fs::create_dir_all(dir.join("Show").join("S01")).unwrap();
        let rel = PathBuf::from("Show/S01/ep01.mkv");
        let full = dir.join(&rel);
        fs::write(&full, b"data").unwrap();

        delete_torrent_files_sync(dir.clone(), vec![rel]);

        assert!(!full.exists(), "file should be gone");
        // Empty S01 must be pruned, empty Show must be pruned, but the
        // root dir itself must survive.
        assert!(!dir.join("Show/S01").exists(), "S01 should be pruned");
        assert!(!dir.join("Show").exists(), "Show should be pruned");
        assert!(dir.exists(), "root must NEVER be removed");
    }

    #[test]
    fn delete_preserves_non_empty_parent() {
        // If a sibling file lives alongside the deleted one, the parent
        // must not be removed.
        let dir = temp_dir("del_siblings");
        fs::create_dir_all(dir.join("Show/S01")).unwrap();
        let rel = PathBuf::from("Show/S01/ep01.mkv");
        fs::write(dir.join(&rel), b"data").unwrap();
        // Sibling that is NOT part of the torrent.
        fs::write(dir.join("Show/S01/ep02.mkv"), b"keep me").unwrap();

        delete_torrent_files_sync(dir.clone(), vec![rel.clone()]);

        assert!(!dir.join(&rel).exists(), "file should be gone");
        assert!(
            dir.join("Show/S01/ep02.mkv").exists(),
            "sibling should survive"
        );
        assert!(
            dir.join("Show/S01").exists(),
            "non-empty dir must NOT be pruned"
        );
    }

    #[test]
    fn delete_tolerates_missing_file() {
        // ENOENT path: the function must NOT panic and must NOT remove
        // the root directory if every file is missing.
        let dir = temp_dir("del_missing");
        fs::create_dir_all(&dir).unwrap();
        let rel = PathBuf::from("does-not-exist.bin");

        delete_torrent_files_sync(dir.clone(), vec![rel]);
        assert!(dir.exists(), "root must remain");
    }

    #[test]
    fn delete_never_removes_download_dir_itself() {
        // Entire contents removed — root must survive even when empty.
        let dir = temp_dir("del_root_safe");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("a.bin"), b"a").unwrap();
        fs::write(dir.join("b.bin"), b"b").unwrap();

        delete_torrent_files_sync(
            dir.clone(),
            vec![PathBuf::from("a.bin"), PathBuf::from("b.bin")],
        );

        assert!(!dir.join("a.bin").exists());
        assert!(!dir.join("b.bin").exists());
        assert!(
            dir.exists(),
            "download_dir root must NEVER be removed even if empty"
        );
    }

    #[test]
    fn delete_prunes_deeply_nested_chain() {
        let dir = temp_dir("del_deep");
        fs::create_dir_all(dir.join("a/b/c/d")).unwrap();
        let rel = PathBuf::from("a/b/c/d/file.bin");
        fs::write(dir.join(&rel), b"x").unwrap();

        delete_torrent_files_sync(dir.clone(), vec![rel]);

        assert!(!dir.join("a/b/c/d").exists());
        assert!(!dir.join("a/b/c").exists());
        assert!(!dir.join("a/b").exists());
        assert!(!dir.join("a").exists());
        assert!(dir.exists());
    }

    #[test]
    #[cfg(unix)]
    fn delete_tolerates_readonly_parent() {
        // Mark the parent directory read-only so remove_file hits EACCES.
        // The helper must NOT panic and MUST continue past the offending
        // file. We verify the walk completes — torrent_files_sync always
        // returns ().
        use std::os::unix::fs::PermissionsExt;

        let dir = temp_dir("del_readonly");
        let sub = dir.join("protected");
        fs::create_dir_all(&sub).unwrap();
        let file = sub.join("data.bin");
        fs::write(&file, b"x").unwrap();
        // u=r-x,g=r-x,o=r-x — no write bit on parent, so unlink will
        // return EACCES on Linux (on macOS it depends on chflags, so we
        // treat either outcome as "handled gracefully").
        let mut perms = fs::metadata(&sub).unwrap().permissions();
        perms.set_mode(0o555);
        fs::set_permissions(&sub, perms).unwrap();

        // Must not panic. Whether the file ends up deleted depends on
        // the running user's capabilities (root will still succeed) —
        // the important property is that this call returns.
        delete_torrent_files_sync(dir.clone(), vec![PathBuf::from("protected/data.bin")]);

        // Restore permissions so cleanup works (root may have already
        // succeeded and pruned `sub` via the empty-parent walk, so the
        // chmod is best-effort).
        if let Ok(meta) = fs::metadata(&sub) {
            let mut perms = meta.permissions();
            perms.set_mode(0o755);
            let _ = fs::set_permissions(&sub, perms);
        }
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn delete_partial_failure_still_processes_remaining_files() {
        // Three files; one does not exist on disk before the call. The
        // two real files MUST still be removed — the helper does not
        // short-circuit on the first missing file.
        let dir = temp_dir("del_partial");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("a.bin"), b"a").unwrap();
        fs::write(dir.join("c.bin"), b"c").unwrap();

        delete_torrent_files_sync(
            dir.clone(),
            vec![
                PathBuf::from("a.bin"),
                PathBuf::from("b.bin"), // does not exist — ENOENT
                PathBuf::from("c.bin"),
            ],
        );

        assert!(!dir.join("a.bin").exists(), "a should have been deleted");
        assert!(!dir.join("c.bin").exists(), "c should have been deleted");
        assert!(dir.exists(), "root must remain");
    }

    #[test]
    fn pre_existing_file_survives_storage_new() {
        // Regression: d674d92 fixed `File::create` → `File::options().truncate(false)`
        // in `FilesystemStorage::new`. Without that fix, pre-existing payload bytes
        // are destroyed before verify_existing_pieces runs, breaking seed-existing-files.
        let dir = temp_dir("trunc_regression");
        fs::create_dir_all(&dir).unwrap();

        let payload = b"ABCDEFGHIJKLMNOP";
        fs::write(dir.join("test.bin"), payload).unwrap();

        let lengths = Lengths::new(
            payload.len() as u64,
            payload.len() as u64,
            payload.len() as u32,
        );
        let _storage = FilesystemStorage::new(
            &dir,
            vec![PathBuf::from("test.bin")],
            vec![payload.len() as u64],
            lengths,
            None,
            PreallocateMode::None,
            false,
        )
        .unwrap();

        let on_disk = fs::read(dir.join("test.bin")).unwrap();
        assert_eq!(
            &on_disk, payload,
            "pre-existing content must survive storage init"
        );

        let _ = fs::remove_dir_all(&dir);
    }
}