rustfs-ecstore 1.0.1

Erasure coding storage backend for RustFS, providing efficient data storage and retrieval with redundancy.
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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::disk::disk_store::{get_drive_walkdir_peek_timeout, get_drive_walkdir_stall_timeout};
use crate::disk::error::DiskError;
use crate::disk::{self, DiskAPI, DiskStore, WalkDirOptions};
use futures::future::join_all;
use metrics::counter;
use rustfs_filemeta::{MetaCacheEntries, MetaCacheEntry, MetacacheReader, is_io_eof};
use std::{
    collections::{HashSet, VecDeque},
    future::Future,
    io::ErrorKind,
    pin::Pin,
    sync::{Arc, OnceLock, atomic::AtomicBool},
    task::{Context, Poll},
    time::Duration,
};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::Mutex as TokioMutex;
use tokio::task::JoinSet;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, warn};

const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_METACACHE: &str = "metacache";
const EVENT_METACACHE_LISTING: &str = "metacache_listing";

pub type AgreedFn = Box<dyn Fn(MetaCacheEntry) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + 'static>;
pub type PartialFn =
    Box<dyn Fn(MetaCacheEntries, &[Option<DiskError>]) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + 'static>;
pub(crate) type PartialResultFn = Box<
    dyn Fn(MetaCacheEntries, &[Option<DiskError>]) -> Pin<Box<dyn Future<Output = disk::error::Result<()>> + Send>>
        + Send
        + 'static,
>;
type FinishedFn = Box<dyn Fn(&[Option<DiskError>]) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + 'static>;

#[derive(Clone, Default)]
pub(crate) struct FallbackClaimTracker {
    claimed: Arc<TokioMutex<HashSet<String>>>,
}

impl FallbackClaimTracker {
    pub(crate) async fn claim_disk(&self, disk: &DiskStore) {
        self.claimed.lock().await.insert(disk.endpoint().to_string());
    }

    pub(crate) async fn claimed_keys(&self) -> HashSet<String> {
        self.claimed.lock().await.clone()
    }

    #[cfg(test)]
    pub(crate) async fn claim_test_fallback(&self) {
        let mut claimed = self.claimed.lock().await;
        let key = format!("test-fallback-{}", claimed.len());
        claimed.insert(key);
    }

    #[cfg(test)]
    pub(crate) async fn contains_key(&self, key: &str) -> bool {
        self.claimed.lock().await.contains(key)
    }
}

#[derive(Debug)]
enum PeekOutcome {
    Ready(Option<MetaCacheEntry>),
    Error(rustfs_filemeta::Error),
    TimedOut,
    Cancelled,
}

async fn peek_with_timeout<R: AsyncRead + Unpin>(
    cancel: &CancellationToken,
    reader: &mut MetacacheReader<R>,
    timeout_duration: Duration,
) -> PeekOutcome {
    tokio::select! {
        biased;
        _ = cancel.cancelled() => PeekOutcome::Cancelled,
        result = timeout(timeout_duration, reader.peek()) => match result {
            Ok(Ok(entry)) => PeekOutcome::Ready(entry),
            Ok(Err(err)) => PeekOutcome::Error(err),
            Err(_) => PeekOutcome::TimedOut,
        },
    }
}

fn is_missing_path_error(err: &DiskError) -> bool {
    matches!(err, DiskError::FileNotFound | DiskError::FileVersionNotFound | DiskError::VolumeNotFound)
}

fn is_tolerated_producer_completion_error(err: &DiskError) -> bool {
    matches!(err, DiskError::DiskOngoingReq)
        || err.is_metacache_output_stream_closed()
        || err.contains_io_error_kind(ErrorKind::BrokenPipe)
}

async fn take_fallback_candidate<T>(fallback_items: &Arc<TokioMutex<VecDeque<T>>>) -> Option<T> {
    fallback_items.lock().await.pop_front()
}

fn duration_millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn classify_listing_quorum_failure(errors: &[DiskError]) -> DiskError {
    if errors.contains(&DiskError::Timeout) {
        return DiskError::Timeout;
    }
    if let Some(first) = errors.first()
        && !matches!(first, DiskError::Io(_))
        && errors.iter().all(|err| err == first)
    {
        return first.clone();
    }
    DiskError::ErasureReadQuorum
}

/// Returns true when a metacache listing missed quorum purely because the
/// volume or path is absent on a quorum of drives, i.e. every recorded failure
/// is [`DiskError::VolumeNotFound`] or [`DiskError::FileNotFound`].
///
/// This is a benign, expected outcome: the caller is handed
/// `VolumeNotFound`/`FileNotFound` and decides how to react. The most common
/// trigger is a startup race where the system bucket has not yet been created
/// on every drive when an early reader (e.g. the IAM config loader) lists it.
/// It must be distinguished from a listing that failed for a real reason (I/O,
/// timeout, corruption) so the former is not surfaced at `error`. See
/// rustfs/rustfs#5076.
fn is_benign_not_found_listing_failure(errors: &[DiskError]) -> bool {
    !errors.is_empty()
        && errors
            .iter()
            .all(|err| matches!(err, DiskError::VolumeNotFound | DiskError::FileNotFound))
}

struct PublishedBytesWriter<W> {
    inner: W,
    published: bool,
}

impl<W> PublishedBytesWriter<W> {
    fn new(inner: W) -> Self {
        Self { inner, published: false }
    }

    fn has_published(&self) -> bool {
        self.published
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for PublishedBytesWriter<W> {
    fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
        match Pin::new(&mut self.inner).poll_write(cx, buf) {
            Poll::Ready(Ok(written)) => {
                if written != 0 && !self.published {
                    self.published = true;
                }
                Poll::Ready(Ok(written))
            }
            other => other,
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(cx)
    }
}

#[cfg(test)]
#[derive(Clone)]
pub(crate) enum TestReaderBehavior {
    Eof,
    Entries(Vec<MetaCacheEntry>),
    Stall,
    StallWithSignals {
        entered: Arc<tokio::sync::Notify>,
        stopped: Arc<tokio::sync::Notify>,
    },
    IgnoreCancel,
    ProducerError(DiskError),
    PrimaryErrorThenFallback(DiskError),
    PartialThenTimeout(Vec<MetaCacheEntry>),
    DelayedEntries {
        delay: Duration,
        entries: Vec<MetaCacheEntry>,
    },
}

#[cfg(test)]
struct NotifyOnDrop(Arc<tokio::sync::Notify>);

#[cfg(test)]
impl Drop for NotifyOnDrop {
    fn drop(&mut self) {
        self.0.notify_one();
    }
}

#[derive(Default)]
pub struct ListPathRawOptions {
    pub disks: Vec<Option<DiskStore>>,
    pub fallback_disks: Vec<Option<DiskStore>>,
    pub bucket: String,
    pub path: String,
    pub recursive: bool,
    pub incl_deleted: bool,
    pub skip_hidden_prefix_check: bool,
    pub filter_prefix: Option<String>,
    pub forward_to: Option<String>,
    pub min_disks: usize,
    /// Deliver every replica to the partial callback, including matching headers.
    pub preserve_replica_metadata: bool,
    pub report_not_found: bool,
    pub per_disk_limit: i32,
    pub skip_walkdir_total_timeout: bool,
    pub walkdir_timeout: Option<Duration>,
    pub walkdir_stall_timeout: Option<Duration>,
    /// Shared terminal state for bounded producer walks.
    pub producer_limit_reached: Option<Arc<AtomicBool>>,
    pub agreed: Option<AgreedFn>,
    pub partial: Option<PartialFn>,
    pub finished: Option<FinishedFn>,
    #[cfg(test)]
    pub(crate) test_reader_behaviors: Vec<TestReaderBehavior>,
    #[cfg(test)]
    pub(crate) test_fallback_reader_behaviors: Vec<TestReaderBehavior>,
    #[cfg(test)]
    pub(crate) peek_timeout: Option<Duration>,
    // pub agreed: Option<Arc<dyn Fn(MetaCacheEntry) + Send + Sync>>,
    // pub partial: Option<Arc<dyn Fn(MetaCacheEntries, &[Option<Error>]) + Send + Sync>>,
    // pub finished: Option<Arc<dyn Fn(&[Option<Error>]) + Send + Sync>>,
}

impl Clone for ListPathRawOptions {
    fn clone(&self) -> Self {
        Self {
            disks: self.disks.clone(),
            fallback_disks: self.fallback_disks.clone(),
            bucket: self.bucket.clone(),
            path: self.path.clone(),
            recursive: self.recursive,
            incl_deleted: self.incl_deleted,
            skip_hidden_prefix_check: self.skip_hidden_prefix_check,
            filter_prefix: self.filter_prefix.clone(),
            forward_to: self.forward_to.clone(),
            min_disks: self.min_disks,
            preserve_replica_metadata: self.preserve_replica_metadata,
            report_not_found: self.report_not_found,
            per_disk_limit: self.per_disk_limit,
            skip_walkdir_total_timeout: self.skip_walkdir_total_timeout,
            walkdir_timeout: self.walkdir_timeout,
            walkdir_stall_timeout: self.walkdir_stall_timeout,
            producer_limit_reached: self.producer_limit_reached.clone(),
            #[cfg(test)]
            test_reader_behaviors: self.test_reader_behaviors.clone(),
            #[cfg(test)]
            test_fallback_reader_behaviors: self.test_fallback_reader_behaviors.clone(),
            #[cfg(test)]
            peek_timeout: self.peek_timeout,
            ..Default::default()
        }
    }
}

fn walk_dir_options(opts: &ListPathRawOptions) -> WalkDirOptions {
    WalkDirOptions {
        bucket: opts.bucket.clone(),
        base_dir: opts.path.clone(),
        recursive: opts.recursive,
        incl_deleted: opts.incl_deleted,
        skip_hidden_prefix_check: opts.skip_hidden_prefix_check,
        report_notfound: opts.report_not_found,
        filter_prefix: opts.filter_prefix.clone(),
        forward_to: opts.forward_to.clone(),
        limit: opts.per_disk_limit,
        skip_total_timeout: opts.skip_walkdir_total_timeout,
        timeout_ms: opts.walkdir_timeout.map(duration_millis),
        stall_timeout_ms: opts.walkdir_stall_timeout.map(duration_millis),
        producer_limit_reached: opts.producer_limit_reached.clone(),
        ..Default::default()
    }
}

pub async fn list_path_raw(rx: CancellationToken, opts: ListPathRawOptions) -> disk::error::Result<()> {
    let rx = rx.child_token();
    let _cancel_guard = rx.clone().drop_guard();
    list_path_raw_inner(rx, opts, None, None).await
}

pub(crate) async fn list_path_raw_with_claim_tracker(
    rx: CancellationToken,
    opts: ListPathRawOptions,
    claim_tracker: FallbackClaimTracker,
) -> disk::error::Result<()> {
    let rx = rx.child_token();
    let _cancel_guard = rx.clone().drop_guard();
    list_path_raw_inner(rx, opts, Some(claim_tracker), None).await
}

pub(crate) async fn list_path_raw_with_partial_result(
    rx: CancellationToken,
    opts: ListPathRawOptions,
    claim_tracker: FallbackClaimTracker,
    partial_result: PartialResultFn,
) -> disk::error::Result<()> {
    let rx = rx.child_token();
    let _cancel_guard = rx.clone().drop_guard();
    list_path_raw_inner(rx, opts, Some(claim_tracker), Some(partial_result)).await
}

async fn list_path_raw_inner(
    rx: CancellationToken,
    opts: ListPathRawOptions,
    fallback_claim_tracker: Option<FallbackClaimTracker>,
    partial_result: Option<PartialResultFn>,
) -> disk::error::Result<()> {
    if opts.disks.is_empty() {
        return Err(DiskError::ErasureReadQuorum);
    }
    if opts.min_disks > opts.disks.len() {
        return Err(DiskError::ErasureReadQuorum);
    }

    let log_bucket = opts.bucket.clone();
    let log_path = opts.path.clone();

    let mut jobs = JoinSet::new();
    let mut readers = Vec::with_capacity(opts.disks.len());
    let fds = Arc::new(TokioMutex::new(opts.fallback_disks.iter().flatten().cloned().collect::<VecDeque<_>>()));
    #[cfg(test)]
    let test_fallbacks = Arc::new(TokioMutex::new(
        opts.test_fallback_reader_behaviors.iter().cloned().collect::<VecDeque<_>>(),
    ));
    let max_disk_failures = opts.disks.len().saturating_sub(opts.min_disks);
    let producer_errs: Arc<[OnceLock<DiskError>]> = (0..opts.disks.len()).map(|_| OnceLock::new()).collect::<Vec<_>>().into();

    let cancel_rx = CancellationToken::new();

    for (disk_idx, disk) in opts.disks.iter().enumerate() {
        let opdisk = disk.clone();
        let opts_clone = opts.clone();
        let fallback_claim_tracker = fallback_claim_tracker.clone();
        let fds_clone = fds.clone();
        #[cfg(test)]
        let test_fallbacks_clone = test_fallbacks.clone();
        let cancel_rx_clone = cancel_rx.clone();
        let producer_errs_clone = producer_errs.clone();
        let (rd, wr) = tokio::io::duplex(64);
        readers.push(MetacacheReader::new(rd));
        jobs.spawn(async move {
            let mut wr = PublishedBytesWriter::new(wr);
            #[cfg(test)]
            let test_primary_error = if let Some(behavior) = opts_clone.test_reader_behaviors.get(disk_idx).cloned() {
                match behavior {
                    TestReaderBehavior::Eof => return Ok(()),
                    TestReaderBehavior::Entries(entries) => {
                        let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                        out.write(&entries).await.expect("test entries should be written");
                        out.close().await.expect("test entries should close");
                        return Ok(());
                    }
                    TestReaderBehavior::Stall => {
                        let _held_writer = wr;
                        cancel_rx_clone.cancelled().await;
                        return Ok(());
                    }
                    TestReaderBehavior::StallWithSignals { entered, stopped } => {
                        let _drop_signal = NotifyOnDrop(stopped);
                        entered.notify_one();
                        let _held_writer = &mut wr;
                        std::future::pending::<Option<DiskError>>().await
                    }
                    TestReaderBehavior::IgnoreCancel => {
                        let _held_writer = wr;
                        std::future::pending::<()>().await;
                        return Ok(());
                    }
                    TestReaderBehavior::ProducerError(err) => {
                        record_producer_error(&producer_errs_clone, disk_idx, &err);
                        return Err(err);
                    }
                    TestReaderBehavior::PrimaryErrorThenFallback(err) => Some(err),
                    TestReaderBehavior::PartialThenTimeout(entries) => {
                        let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                        let err = DiskError::Timeout;
                        let _ = out.write(&entries).await;
                        drop(out);
                        Some(err)
                    }
                    TestReaderBehavior::DelayedEntries { delay, entries } => {
                        tokio::time::sleep(delay).await;
                        let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                        out.write(&entries).await.expect("delayed test entries should be written");
                        out.close().await.expect("delayed test entries should close");
                        return Ok(());
                    }
                }
            } else {
                None
            };

            let wakl_opts = walk_dir_options(&opts_clone);

            let mut need_fallback = false;
            let mut last_err = None;
            #[cfg(test)]
            if let Some(err) = test_primary_error {
                if wr.has_published() {
                    record_producer_error(&producer_errs_clone, disk_idx, &err);
                    return Err(err);
                }
                last_err = Some(err);
                need_fallback = true;
            }

            if !need_fallback && let Some(disk) = opdisk {
                let primary_walk_started = std::time::Instant::now();
                match disk.walk_dir(wakl_opts, &mut wr).await {
                    Ok(_res) => {
                        rustfs_io_metrics::record_stage_duration(
                            "metacache_walk_dir_primary",
                            primary_walk_started.elapsed().as_secs_f64() * 1000.0,
                        );
                    }
                    Err(err) => {
                        if err.is_metacache_output_stream_closed() {
                            rustfs_io_metrics::record_stage_duration(
                                "metacache_walk_dir_primary",
                                primary_walk_started.elapsed().as_secs_f64() * 1000.0,
                            );
                            return Ok(());
                        }
                        rustfs_io_metrics::record_stage_duration(
                            "metacache_walk_dir_primary_failed",
                            primary_walk_started.elapsed().as_secs_f64() * 1000.0,
                        );
                        if is_missing_path_error(&err) {
                            debug!(
                                event = EVENT_METACACHE_LISTING,
                                component = LOG_COMPONENT_ECSTORE,
                                subsystem = LOG_SUBSYSTEM_METACACHE,
                                bucket = %opts_clone.bucket,
                                path = %opts_clone.path,
                                disk_index = disk_idx,
                                state = "walk_dir_missing_path",
                                error = ?err,
                                "Metacache walk_dir missing path skipped"
                            );
                        } else {
                            warn!(
                                event = EVENT_METACACHE_LISTING,
                                component = LOG_COMPONENT_ECSTORE,
                                subsystem = LOG_SUBSYSTEM_METACACHE,
                                bucket = %opts_clone.bucket,
                                path = %opts_clone.path,
                                disk_index = disk_idx,
                                state = "walk_dir_failed",
                                error = ?err,
                                "Metacache walk_dir failed"
                            );
                        }
                        if wr.has_published() {
                            record_producer_error(&producer_errs_clone, disk_idx, &err);
                            return Err(err);
                        }
                        last_err = Some(err);
                        need_fallback = true;
                    }
                }
            } else if !need_fallback {
                last_err = Some(DiskError::DiskNotFound);
                need_fallback = true;
            }

            if cancel_rx_clone.is_cancelled() {
                // warn!("list_path_raw: cancel_rx_clone.is_cancelled()");
                return Ok(());
            }

            while need_fallback {
                #[cfg(test)]
                if let Some(behavior) = take_fallback_candidate(&test_fallbacks_clone).await {
                    if let Some(claim_tracker) = fallback_claim_tracker.as_ref() {
                        claim_tracker.claim_test_fallback().await;
                    }
                    match behavior {
                        TestReaderBehavior::Eof => {
                            need_fallback = false;
                            last_err = None;
                            continue;
                        }
                        TestReaderBehavior::Entries(entries) => {
                            let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                            out.write(&entries).await.expect("test fallback entries should be written");
                            out.close().await.expect("test fallback entries should close");
                            need_fallback = false;
                            last_err = None;
                            continue;
                        }
                        TestReaderBehavior::ProducerError(err) | TestReaderBehavior::PrimaryErrorThenFallback(err) => {
                            last_err = Some(err);
                            continue;
                        }
                        TestReaderBehavior::Stall
                        | TestReaderBehavior::StallWithSignals { .. }
                        | TestReaderBehavior::IgnoreCancel => {
                            last_err = Some(DiskError::Timeout);
                            continue;
                        }
                        TestReaderBehavior::PartialThenTimeout(entries) => {
                            let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                            let err = DiskError::Timeout;
                            let _ = out.write(&entries).await;
                            drop(out);
                            record_producer_error(&producer_errs_clone, disk_idx, &err);
                            return Err(err);
                        }
                        TestReaderBehavior::DelayedEntries { delay, entries } => {
                            tokio::time::sleep(delay).await;
                            let mut out = rustfs_filemeta::MetacacheWriter::new(&mut wr);
                            out.write(&entries)
                                .await
                                .expect("delayed test fallback entries should be written");
                            out.close().await.expect("delayed test fallback entries should close");
                            need_fallback = false;
                            last_err = None;
                            continue;
                        }
                    }
                }

                let mut disk_op = None;
                while let Some(disk) = take_fallback_candidate(&fds_clone).await {
                    if disk.is_online().await {
                        disk_op = Some(disk);
                        break;
                    }
                }

                let Some(disk) = disk_op else {
                    let err = last_err.unwrap_or(DiskError::DiskNotFound);
                    if is_missing_path_error(&err) {
                        debug!(
                            event = EVENT_METACACHE_LISTING,
                            component = LOG_COMPONENT_ECSTORE,
                            subsystem = LOG_SUBSYSTEM_METACACHE,
                            bucket = %opts_clone.bucket,
                            path = %opts_clone.path,
                            disk_index = disk_idx,
                            state = "fallback_disk_missing_for_path",
                            error = ?err,
                            "Metacache fallback disk unavailable for missing path"
                        );
                    } else {
                        warn!(
                            event = EVENT_METACACHE_LISTING,
                            component = LOG_COMPONENT_ECSTORE,
                            subsystem = LOG_SUBSYSTEM_METACACHE,
                            bucket = %opts_clone.bucket,
                            path = %opts_clone.path,
                            disk_index = disk_idx,
                            state = "fallback_disk_missing",
                            error = ?err,
                            "Metacache fallback disk missing"
                        );
                    }
                    record_producer_error(&producer_errs_clone, disk_idx, &err);
                    return Err(err);
                };
                if let Some(claim_tracker) = fallback_claim_tracker.as_ref() {
                    claim_tracker.claim_disk(&disk).await;
                }

                let fallback_walk_started = std::time::Instant::now();
                match disk.as_ref().walk_dir(walk_dir_options(&opts_clone), &mut wr).await {
                    Ok(_r) => {
                        rustfs_io_metrics::record_stage_duration(
                            "metacache_walk_dir_fallback",
                            fallback_walk_started.elapsed().as_secs_f64() * 1000.0,
                        );
                        need_fallback = false;
                        last_err = None;
                    }
                    Err(err) => {
                        if err.is_metacache_output_stream_closed() {
                            rustfs_io_metrics::record_stage_duration(
                                "metacache_walk_dir_fallback",
                                fallback_walk_started.elapsed().as_secs_f64() * 1000.0,
                            );
                            return Ok(());
                        }
                        rustfs_io_metrics::record_stage_duration(
                            "metacache_walk_dir_fallback_failed",
                            fallback_walk_started.elapsed().as_secs_f64() * 1000.0,
                        );
                        if is_missing_path_error(&err) {
                            debug!(
                                event = EVENT_METACACHE_LISTING,
                                component = LOG_COMPONENT_ECSTORE,
                                subsystem = LOG_SUBSYSTEM_METACACHE,
                                bucket = %opts_clone.bucket,
                                path = %opts_clone.path,
                                disk_index = disk_idx,
                                state = "fallback_walk_dir_missing_path",
                                error = ?err,
                                "Metacache fallback walk_dir missing path skipped"
                            );
                        } else {
                            error!(
                                event = EVENT_METACACHE_LISTING,
                                component = LOG_COMPONENT_ECSTORE,
                                subsystem = LOG_SUBSYSTEM_METACACHE,
                                bucket = %opts_clone.bucket,
                                path = %opts_clone.path,
                                disk_index = disk_idx,
                                state = "fallback_walk_dir_failed",
                                error = ?err,
                                "Metacache fallback walk_dir failed"
                            );
                        }
                        if wr.has_published() {
                            record_producer_error(&producer_errs_clone, disk_idx, &err);
                            return Err(err);
                        }
                        last_err = Some(err);
                    }
                }
            }

            if need_fallback {
                return Err(last_err.unwrap_or(DiskError::DiskNotFound));
            }

            // warn!("list_path_raw: while need_fallback done");
            Ok(())
        });
    }

    let revjob_rx = rx.clone();
    let mut revjobs = JoinSet::new();
    revjobs.spawn(async move {
        // Consumer-side peek timeout, and a caveat worth understanding
        // (rustfs/backlog#1217).
        //
        // This budget must not be stricter than the producer-side walk stall
        // budget. The two measure different things:
        //   * producer stall: bounds a single drive READ inside the walk (see
        //     `with_walk_stall_deadline` in `disk/local.rs`);
        //   * this consumer peek: bounds the interval between two ADJACENT
        //     entries arriving from a drive's reader (`peek_with_timeout`).
        //
        // A drive can spend one stall budget walking a dense non-listable region
        // before it can publish the next visible entry. Use an independent,
        // profile-aware consumer budget so the merge does not detach that reader
        // before the producer itself would have failed.
        let producer_stall_timeout = opts.walkdir_stall_timeout.unwrap_or_else(get_drive_walkdir_stall_timeout);
        let configured_peek_timeout = get_drive_walkdir_peek_timeout().max(producer_stall_timeout);
        #[cfg(not(test))]
        let peek_timeout = configured_peek_timeout;
        #[cfg(test)]
        let peek_timeout = opts.peek_timeout.unwrap_or(configured_peek_timeout);
        let mut errs: Vec<Option<DiskError>> = Vec::with_capacity(readers.len());
        for _ in 0..readers.len() {
            errs.push(None);
        }
        let mut pending_entries: Vec<Option<MetaCacheEntry>> = vec![None; readers.len()];
        let mut peek_outcomes: Vec<Option<PeekOutcome>> = std::iter::repeat_with(|| None).take(readers.len()).collect();

        loop {
            let mut current = MetaCacheEntry::default();

            // warn!(
            //     "list_path_raw: loop start, bucket: {}, path: {}, current: {:?}",
            //     opts.bucket, opts.path, &current.name
            // );

            if revjob_rx.is_cancelled() {
                return Ok(());
            }

            let mut top_entries: Vec<Option<MetaCacheEntry>> = vec![None; readers.len()];

            let mut at_eof = 0;
            let mut fnf = 0;
            let mut vnf = 0;
            let mut has_err = 0;
            let mut agree = 0;

            // Start every missing head read in the same round so one stalled
            // disk cannot multiply the wait budget by the erasure-set width.
            // Outcomes are still consumed below in stable disk-index order.
            let concurrent_peeks = readers.iter_mut().enumerate().filter_map(|(i, reader)| {
                if errs[i].is_some() || pending_entries[i].is_some() {
                    return None;
                }

                let cancel = &revjob_rx;
                Some(async move { (i, peek_with_timeout(cancel, reader, peek_timeout).await) })
            });
            for (i, outcome) in join_all(concurrent_peeks).await {
                peek_outcomes[i] = Some(outcome);
            }

            for (i, r) in readers.iter_mut().enumerate() {
                if errs[i].is_some() {
                    has_err += 1;
                    continue;
                }

                let entry = if let Some(entry) = pending_entries[i].take() {
                    entry
                } else {
                    let Some(outcome) = peek_outcomes[i].take() else {
                        return Err(DiskError::Unexpected);
                    };
                    match outcome {
                        PeekOutcome::Ready(res) => {
                            if let Some(entry) = res {
                                // info!("read entry disk: {}, name: {}", i, entry.name);
                                entry
                            } else {
                                if let Some(err) = producer_error(&producer_errs, i) {
                                    has_err += 1;
                                    errs[i] = Some(err);
                                    continue;
                                }
                                // eof
                                at_eof += 1;
                                // warn!("list_path_raw: peek eof, disk: {}", i);
                                continue;
                            }
                        }
                        PeekOutcome::Error(err) => {
                            if let Some(err) = producer_error(&producer_errs, i) {
                                has_err += 1;
                                errs[i] = Some(err);
                                continue;
                            }

                            if err == rustfs_filemeta::Error::Unexpected {
                                at_eof += 1;
                                // warn!("list_path_raw: peek err eof, disk: {}", i);
                                continue;
                            }

                            // warn!("list_path_raw: peek err00, err: {:?}", err);

                            if is_io_eof(&err) {
                                at_eof += 1;
                                // warn!("list_path_raw: peek eof, disk: {}", i);
                                continue;
                            }

                            if err == rustfs_filemeta::Error::FileNotFound {
                                at_eof += 1;
                                fnf += 1;
                                // warn!("list_path_raw: peek fnf, disk: {}", i);
                                continue;
                            } else if err == rustfs_filemeta::Error::VolumeNotFound {
                                at_eof += 1;
                                fnf += 1;
                                vnf += 1;
                                // warn!("list_path_raw: peek vnf, disk: {}", i);
                                continue;
                            } else {
                                has_err += 1;
                                errs[i] = Some(err.into());
                                // warn!("list_path_raw: peek err, disk: {}", i);
                                continue;
                            }
                        }
                        PeekOutcome::TimedOut => {
                            has_err += 1;
                            errs[i] = Some(DiskError::Timeout);
                            let endpoint = opts
                                .disks
                                .get(i)
                                .and_then(|disk| disk.as_ref().map(|disk| disk.endpoint().to_string()))
                                .unwrap_or_else(|| "missing".to_string());
                            counter!(
                                "rustfs_list_path_raw_stall_total",
                                "drive" => endpoint.clone()
                            )
                            .increment(1);
                            warn!(
                                event = EVENT_METACACHE_LISTING,
                                component = LOG_COMPONENT_ECSTORE,
                                subsystem = LOG_SUBSYSTEM_METACACHE,
                                drive = %endpoint,
                                bucket = %opts.bucket,
                                path = %opts.path,
                                timeout_ms = peek_timeout.as_millis(),
                                state = "peek_timed_out",
                                "Metacache reader peek timed out"
                            );
                            let (detached_rd, write_half) = tokio::io::duplex(1);
                            drop(write_half);
                            *r = MetacacheReader::new(detached_rd);
                            continue;
                        }
                        PeekOutcome::Cancelled => return Ok(()),
                    }
                };

                // warn!("list_path_raw: loop entry: {:?}, disk: {}", &entry.name, i);

                // If no current, add it.
                if current.name.is_empty() {
                    top_entries[i] = Some(entry.clone());
                    current = entry;
                    agree += 1;

                    continue;
                }
                // If exact match, we agree.
                if let (_, true) = current.matches(Some(&entry), true) {
                    top_entries[i] = Some(entry);
                    agree += 1;

                    continue;
                }
                // If only the name matches we didn't agree, but add it for resolution.
                if entry.name == current.name {
                    top_entries[i] = Some(entry);
                    continue;
                }
                // We got different entries
                if entry.name > current.name {
                    pending_entries[i] = Some(entry);
                    continue;
                }

                for (idx, item) in top_entries.iter_mut().enumerate().take(i) {
                    if let Some(entry) = item.take() {
                        pending_entries[idx] = Some(entry);
                    }
                }

                agree = 1;
                top_entries[i] = Some(entry.clone());
                current = entry;
            }

            if vnf > 0 && vnf >= (readers.len() - opts.min_disks) {
                // warn!("list_path_raw: vnf > 0 && vnf >= (readers.len() - opts.min_disks) break");
                return Err(DiskError::VolumeNotFound);
            }

            if fnf > 0 && fnf >= (readers.len() - opts.min_disks) {
                // warn!("list_path_raw: fnf > 0 && fnf >= (readers.len() - opts.min_disks) break");
                return Err(DiskError::FileNotFound);
            }

            if has_err > 0 && has_err > opts.disks.len() - opts.min_disks {
                if let Some(finished_fn) = opts.finished.as_ref() {
                    tokio::select! {
                        biased;
                        _ = revjob_rx.cancelled() => return Ok(()),
                        _ = finished_fn(&errs) => {}
                    }
                }
                let mut combined_err = Vec::new();
                errs.iter().zip(opts.disks.iter()).for_each(|(err, disk)| match (err, disk) {
                    (Some(err), Some(disk)) => {
                        combined_err.push(format!("drive {} returned: {}", disk.to_string(), err));
                    }
                    (Some(err), None) => {
                        combined_err.push(err.to_string());
                    }
                    _ => {}
                });

                let failures = errs.iter().flatten().cloned().collect::<Vec<_>>();
                // A listing that misses quorum purely because the volume/path is
                // absent on a quorum of drives is benign and expected — the caller
                // receives VolumeNotFound/FileNotFound and decides how to react.
                // The common trigger is a startup race where the system bucket is
                // not yet created on every drive when an early reader (e.g. the IAM
                // config loader) lists it, so surfacing it at `error` is misleading
                // noise (rustfs/rustfs#5076). Keep `error` for listings that failed
                // for a real reason (I/O, timeout, corruption).
                if is_benign_not_found_listing_failure(&failures) {
                    debug!(
                        event = EVENT_METACACHE_LISTING,
                        component = LOG_COMPONENT_ECSTORE,
                        subsystem = LOG_SUBSYSTEM_METACACHE,
                        bucket = %opts.bucket,
                        path = %opts.path,
                        state = "quorum_not_found",
                        error = %combined_err.join(", "),
                        "Metacache listing quorum not reached (volume/path absent)"
                    );
                } else {
                    error!(
                        event = EVENT_METACACHE_LISTING,
                        component = LOG_COMPONENT_ECSTORE,
                        subsystem = LOG_SUBSYSTEM_METACACHE,
                        bucket = %opts.bucket,
                        path = %opts.path,
                        state = "quorum_failed",
                        error = %combined_err.join(", "),
                        "Metacache listing quorum failed"
                    );
                }
                return Err(classify_listing_quorum_failure(&failures));
            }

            // Break if all at EOF or error.
            if at_eof + has_err == readers.len() {
                if has_err > 0
                    && let Some(finished_fn) = opts.finished.as_ref()
                {
                    tokio::select! {
                        biased;
                        _ = revjob_rx.cancelled() => return Ok(()),
                        _ = finished_fn(&errs) => {}
                    }
                }
                // Tolerated reader failures, including timeouts, must not turn a
                // quorum EOF into a failed listing. The quorum failure branch above
                // is the single place that escalates too many reader errors.
                // error!("list_path_raw: at_eof + has_err == readers.len() break {:?}", &errs);
                break;
            }

            if agree == readers.len() && !opts.preserve_replica_metadata {
                for r in readers.iter_mut() {
                    let _ = r.skip(1).await;
                }

                if let Some(agreed_fn) = opts.agreed.as_ref() {
                    // warn!("list_path_raw: agreed_fn start, current: {:?}", &current.name);
                    tokio::select! {
                        biased;
                        _ = revjob_rx.cancelled() => return Ok(()),
                        _ = agreed_fn(current) => {}
                    }
                    // warn!("list_path_raw: agreed_fn done");
                }

                continue;
            }

            // warn!("list_path_raw: skip start, current: {:?}", &current.name);

            for (i, r) in readers.iter_mut().enumerate() {
                if top_entries[i].is_some() {
                    let _ = r.skip(1).await;
                }
            }

            if let Some(partial_fn) = partial_result.as_ref() {
                tokio::select! {
                    biased;
                    _ = revjob_rx.cancelled() => return Ok(()),
                    result = partial_fn(MetaCacheEntries(top_entries), &errs) => result?,
                }
            } else if let Some(partial_fn) = opts.partial.as_ref() {
                tokio::select! {
                    biased;
                    _ = revjob_rx.cancelled() => return Ok(()),
                    _ = partial_fn(MetaCacheEntries(top_entries), &errs) => {}
                }
            }
        }
        Ok(())
    });

    let merge_started = std::time::Instant::now();
    let Some(revjob) = revjobs.join_next().await else {
        return Err(DiskError::Unexpected);
    };
    if let Err(err) = revjob.map_err(std::io::Error::other)? {
        rustfs_io_metrics::record_stage_duration("metacache_merge_failed", merge_started.elapsed().as_secs_f64() * 1000.0);
        if is_missing_path_error(&err) {
            debug!(
                event = EVENT_METACACHE_LISTING,
                component = LOG_COMPONENT_ECSTORE,
                subsystem = LOG_SUBSYSTEM_METACACHE,
                bucket = %log_bucket,
                path = %log_path,
                state = "merge_job_missing_path",
                error = ?err,
                "Metacache merge job missing path skipped"
            );
        } else {
            error!(
                event = EVENT_METACACHE_LISTING,
                component = LOG_COMPONENT_ECSTORE,
                subsystem = LOG_SUBSYSTEM_METACACHE,
                bucket = %log_bucket,
                path = %log_path,
                state = "merge_job_failed",
                error = ?err,
                "Metacache merge job failed"
            );
        }
        cancel_rx.cancel();
        jobs.abort_all();

        return Err(err);
    }
    if rx.is_cancelled() {
        cancel_rx.cancel();
        jobs.abort_all();
        return Ok(());
    }
    rustfs_io_metrics::record_stage_duration("metacache_merge", merge_started.elapsed().as_secs_f64() * 1000.0);

    // The merge consumer can finish successfully before every producer finishes
    // (for example after reaching EOF quorum while a tolerated drive is stalled,
    // or after the requested listing limit is satisfied). Cancel remaining walk
    // jobs before aborting them so list calls do not wait for slow remote streams.
    cancel_rx.cancel();
    jobs.abort_all();
    let mut job_errs = Vec::new();
    while let Some(result) = jobs.join_next().await {
        match result {
            Ok(Ok(())) => {}
            Ok(Err(err)) => {
                if is_tolerated_producer_completion_error(&err) {
                    debug!(
                        event = EVENT_METACACHE_LISTING,
                        component = LOG_COMPONENT_ECSTORE,
                        subsystem = LOG_SUBSYSTEM_METACACHE,
                        state = "producer_tolerated_after_merge",
                        error = ?err,
                        "Metacache producer stopped after merge completed"
                    );
                    continue;
                }
                if is_missing_path_error(&err) {
                    debug!(
                        event = EVENT_METACACHE_LISTING,
                        component = LOG_COMPONENT_ECSTORE,
                        subsystem = LOG_SUBSYSTEM_METACACHE,
                        state = "producer_missing_path",
                        error = ?err,
                        "Metacache producer missing path"
                    );
                } else {
                    error!(
                        event = EVENT_METACACHE_LISTING,
                        component = LOG_COMPONENT_ECSTORE,
                        subsystem = LOG_SUBSYSTEM_METACACHE,
                        state = "producer_failed",
                        error = ?err,
                        "Metacache producer failed"
                    );
                }
                job_errs.push(err);
            }
            Err(err) => {
                if err.is_cancelled() {
                    continue;
                }
                error!(
                    event = EVENT_METACACHE_LISTING,
                    component = LOG_COMPONENT_ECSTORE,
                    subsystem = LOG_SUBSYSTEM_METACACHE,
                    state = "producer_join_failed",
                    error = ?err,
                    "Metacache producer join failed"
                );
                job_errs.push(err.into());
            }
        }
    }

    if job_errs.len() > max_disk_failures {
        return Err(classify_listing_quorum_failure(&job_errs));
    }

    // warn!("list_path_raw: done");
    Ok(())
}

#[inline]
fn record_producer_error(producer_errs: &[OnceLock<DiskError>], idx: usize, err: &DiskError) {
    let _ = producer_errs[idx].set(err.clone());
}

#[inline]
fn producer_error(producer_errs: &[OnceLock<DiskError>], idx: usize) -> Option<DiskError> {
    producer_errs[idx].get().cloned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustfs_filemeta::MetacacheWriter;
    use rustfs_filemeta::{FileInfo, FileMeta, MetadataResolutionParams};
    use std::sync::Mutex;
    use time::OffsetDateTime;
    use uuid::Uuid;

    #[test]
    fn benign_not_found_listing_failure_detection() {
        // Pure not-found quorum misses are benign (the volume/path simply does
        // not exist on a quorum of drives) and must not be logged at ERROR.
        assert!(is_benign_not_found_listing_failure(&[DiskError::VolumeNotFound]));
        assert!(is_benign_not_found_listing_failure(
            &[DiskError::VolumeNotFound, DiskError::FileNotFound,]
        ));
        // No recorded failure is not a not-found case.
        assert!(!is_benign_not_found_listing_failure(&[]));
        // Any real error must keep the failure at ERROR severity.
        assert!(!is_benign_not_found_listing_failure(&[DiskError::VolumeNotFound, DiskError::Timeout,]));
        assert!(!is_benign_not_found_listing_failure(&[DiskError::DiskNotFound]));
    }

    #[test]
    fn walk_dir_options_preserve_zero_total_and_inherited_stall_timeouts() {
        let options = walk_dir_options(&ListPathRawOptions {
            skip_hidden_prefix_check: true,
            walkdir_timeout: Some(Duration::ZERO),
            walkdir_stall_timeout: None,
            ..Default::default()
        });

        assert!(options.skip_hidden_prefix_check);
        assert_eq!(options.timeout_ms, Some(0));
        assert_eq!(options.stall_timeout_ms, None);
        assert!(!options.skip_total_timeout);
    }

    #[tokio::test]
    async fn list_path_raw_empty_disks_returns_read_quorum() {
        let err = list_path_raw(CancellationToken::new(), ListPathRawOptions::default())
            .await
            .expect_err("empty drive list should fail");

        assert_eq!(err, DiskError::ErasureReadQuorum);
    }

    #[tokio::test]
    async fn list_path_raw_rejects_impossible_min_disks() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 3,
                ..Default::default()
            },
        )
        .await
        .expect_err("impossible listing quorum should fail before producing partial results");

        assert_eq!(err, DiskError::ErasureReadQuorum);
    }

    #[tokio::test]
    async fn list_path_raw_returns_typed_quorum_error_for_multiple_drive_failures() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::ProducerError(DiskError::other("/sensitive/disk-a")),
                    TestReaderBehavior::ProducerError(DiskError::other("http://internal-node/disk-b")),
                    TestReaderBehavior::Eof,
                ],
                ..Default::default()
            },
        )
        .await
        .expect_err("multiple producer failures beyond tolerance should fail listing quorum");

        assert_eq!(err, DiskError::ErasureReadQuorum);
        assert!(!err.to_string().contains("sensitive"));
        assert!(!err.to_string().contains("internal-node"));
    }

    #[test]
    fn listing_quorum_failure_never_returns_raw_io_details() {
        let err = classify_listing_quorum_failure(&[DiskError::other("/sensitive/disk-a")]);

        assert_eq!(err, DiskError::ErasureReadQuorum);
        assert!(!err.to_string().contains("sensitive"));

        let access_denied = classify_listing_quorum_failure(&[DiskError::FileAccessDenied, DiskError::FileAccessDenied]);
        assert_eq!(access_denied, DiskError::FileAccessDenied);

        let mixed_timeout =
            classify_listing_quorum_failure(&[DiskError::Timeout, DiskError::FileAccessDenied, DiskError::ErasureReadQuorum]);
        assert_eq!(mixed_timeout, DiskError::Timeout);
    }

    #[test]
    fn mixed_missing_and_body_io_errors_remain_an_actionable_quorum_failure() {
        let failures = [
            DiskError::FileNotFound,
            DiskError::Io(std::io::Error::other("remote body stream aborted")),
        ];

        assert!(!is_benign_not_found_listing_failure(&failures));
        assert_eq!(classify_listing_quorum_failure(&failures), DiskError::ErasureReadQuorum);
    }

    #[test]
    fn missing_path_error_classification_excludes_actionable_failures() {
        assert!(is_missing_path_error(&DiskError::FileNotFound));
        assert!(is_missing_path_error(&DiskError::FileVersionNotFound));
        assert!(is_missing_path_error(&DiskError::VolumeNotFound));
        assert!(!is_missing_path_error(&DiskError::Timeout));
        assert!(!is_missing_path_error(&DiskError::DiskNotFound));
        assert!(!is_missing_path_error(&DiskError::FileAccessDenied));
    }

    #[test]
    fn tolerated_producer_completion_error_classification_excludes_actionable_failures() {
        assert!(is_tolerated_producer_completion_error(&DiskError::DiskOngoingReq));
        assert!(is_tolerated_producer_completion_error(&DiskError::metacache_output_stream_closed()));
        assert!(is_tolerated_producer_completion_error(&DiskError::Io(std::io::Error::new(
            ErrorKind::BrokenPipe,
            "reader closed after merge",
        ))));
        assert!(!is_tolerated_producer_completion_error(&DiskError::Timeout));
        assert!(!is_tolerated_producer_completion_error(&DiskError::DiskNotFound));
        assert!(!is_tolerated_producer_completion_error(&DiskError::FileAccessDenied));
    }

    #[tokio::test]
    async fn fallback_candidates_are_claimed_once_across_producers() {
        let mut queue = VecDeque::new();
        queue.push_back(1usize);
        let candidates = Arc::new(TokioMutex::new(queue));

        let first = take_fallback_candidate(&candidates).await;
        let second = take_fallback_candidate(&candidates).await;

        assert_eq!(first, Some(1));
        assert_eq!(second, None);
    }

    fn fallback_test_entry() -> MetaCacheEntry {
        MetaCacheEntry {
            name: "bucket/object".to_string(),
            metadata: vec![1, 2, 3],
            cached: None,
            reusable: false,
        }
    }

    #[tokio::test]
    async fn list_path_raw_does_not_reuse_one_fallback_for_multiple_failed_producers() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound),
                    TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound),
                ],
                test_fallback_reader_behaviors: vec![TestReaderBehavior::Entries(vec![fallback_test_entry()])],
                ..Default::default()
            },
        )
        .await
        .expect_err("one fallback must not be counted as two failed primary producers");

        assert_eq!(err, DiskError::DiskNotFound);
    }

    #[tokio::test]
    async fn list_path_raw_uses_distinct_fallbacks_to_restore_quorum() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_clone = seen.clone();

        list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound),
                    TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound),
                ],
                test_fallback_reader_behaviors: vec![
                    TestReaderBehavior::Entries(vec![fallback_test_entry()]),
                    TestReaderBehavior::Entries(vec![fallback_test_entry()]),
                ],
                partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
                    let seen = seen_clone.clone();
                    Box::pin(async move {
                        let matches = entries
                            .0
                            .iter()
                            .flatten()
                            .filter(|entry| entry.name == "bucket/object")
                            .count();
                        seen.lock().expect("seen mutex poisoned").push(matches);
                    })
                })),
                ..Default::default()
            },
        )
        .await
        .expect("distinct fallback producers should restore listing quorum");

        assert_eq!(seen.lock().expect("seen mutex poisoned").as_slice(), &[2]);
    }

    #[tokio::test]
    async fn list_path_raw_records_claimed_fallback_candidates() {
        let claim_tracker = FallbackClaimTracker::default();

        list_path_raw_with_claim_tracker(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound)],
                test_fallback_reader_behaviors: vec![TestReaderBehavior::Entries(vec![fallback_test_entry()])],
                ..Default::default()
            },
            claim_tracker.clone(),
        )
        .await
        .expect("fallback producer should restore the single logical reader");

        assert!(claim_tracker.contains_key("test-fallback-0").await);
    }

    #[tokio::test]
    async fn list_path_raw_returns_timeout_when_reader_stalls_before_completion() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 2,
                test_reader_behaviors: vec![TestReaderBehavior::Stall, TestReaderBehavior::Eof],
                peek_timeout: Some(Duration::from_millis(20)),
                ..Default::default()
            },
        )
        .await
        .expect_err("stalled reader should fail when read quorum cannot be met");

        assert_eq!(err, DiskError::Timeout);
    }

    #[tokio::test(start_paused = true)]
    async fn list_path_raw_bounds_multiple_stalled_readers_by_one_peek_deadline() {
        let peek_timeout = Duration::from_millis(20);
        let started = tokio::time::Instant::now();
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None, None],
                min_disks: 1,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Stall,
                    TestReaderBehavior::Stall,
                    TestReaderBehavior::Stall,
                    TestReaderBehavior::Stall,
                ],
                peek_timeout: Some(peek_timeout),
                ..Default::default()
            },
        )
        .await
        .expect_err("all stalled readers should fail the listing");

        assert_eq!(err, DiskError::Timeout);
        assert_eq!(
            started.elapsed(),
            peek_timeout,
            "reader deadlines must overlap instead of accumulating once per disk"
        );
    }

    #[tokio::test]
    async fn list_path_raw_waits_past_producer_stall_for_slow_progressing_reader() {
        let entry = MetaCacheEntry {
            name: "bucket/visible-object".to_string(),
            metadata: vec![1, 2, 3],
            cached: None,
            reusable: false,
        };
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_clone = seen.clone();

        timeout(
            Duration::from_secs(1),
            list_path_raw(
                CancellationToken::new(),
                ListPathRawOptions {
                    disks: vec![None, None],
                    min_disks: 2,
                    walkdir_stall_timeout: Some(Duration::from_millis(20)),
                    test_reader_behaviors: vec![
                        TestReaderBehavior::DelayedEntries {
                            delay: Duration::from_millis(60),
                            entries: vec![entry.clone()],
                        },
                        TestReaderBehavior::Entries(vec![entry]),
                    ],
                    partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
                        let seen = seen_clone.clone();
                        Box::pin(async move {
                            let mut names = entries.0.iter().flatten().map(|entry| entry.name.as_str());
                            if let (Some(first), Some(second), None) = (names.next(), names.next(), names.next())
                                && first == second
                            {
                                seen.lock().expect("seen mutex poisoned").push(first.to_owned());
                            }
                        })
                    })),
                    ..Default::default()
                },
            ),
        )
        .await
        .expect("slow-progressing reader should complete inside the consumer peek budget")
        .expect("slow-progressing reader should not be detached by the producer stall budget");

        assert_eq!(
            seen.lock().expect("seen mutex poisoned").as_slice(),
            &["bucket/visible-object".to_string()]
        );
    }

    #[tokio::test]
    async fn list_path_raw_prefers_timeout_for_mixed_errors_beyond_quorum_budget() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::ProducerError(DiskError::FileAccessDenied),
                    TestReaderBehavior::ProducerError(DiskError::Timeout),
                    TestReaderBehavior::Eof,
                ],
                ..Default::default()
            },
        )
        .await
        .expect_err("mixed failures beyond the tolerated budget should fail listing");

        assert_eq!(err, DiskError::Timeout);
    }

    #[tokio::test]
    async fn list_path_raw_tolerates_stalled_reader_after_quorum_eof() {
        list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![TestReaderBehavior::Eof, TestReaderBehavior::Eof, TestReaderBehavior::Stall],
                peek_timeout: Some(Duration::from_millis(20)),
                ..Default::default()
            },
        )
        .await
        .expect("stalled reader within the tolerated failure budget should not fail quorum EOF");
    }

    #[tokio::test]
    async fn list_path_raw_completes_after_partial_quorum_when_reader_stalls() {
        let entry = MetaCacheEntry {
            name: "bucket/object".to_string(),
            metadata: vec![1, 2, 3],
            cached: None,
            reusable: false,
        };
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_clone = seen.clone();

        list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Entries(vec![entry.clone()]),
                    TestReaderBehavior::Entries(vec![entry]),
                    TestReaderBehavior::Stall,
                ],
                peek_timeout: Some(Duration::from_millis(20)),
                partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
                    let seen = seen_clone.clone();
                    Box::pin(async move {
                        let mut names = entries.0.iter().flatten().map(|entry| entry.name.clone());
                        if let Some(name) = names.next()
                            && names.any(|next| next == name)
                        {
                            seen.lock().expect("seen mutex poisoned").push(name);
                        }
                    })
                })),
                ..Default::default()
            },
        )
        .await
        .expect("stalled reader within failure budget should not fail a quorum listing");

        assert_eq!(seen.lock().expect("seen mutex poisoned").as_slice(), &["bucket/object".to_string()]);
    }

    #[tokio::test]
    async fn list_path_raw_aborts_unresponsive_producer_after_quorum_eof() {
        let result = timeout(
            Duration::from_millis(200),
            list_path_raw(
                CancellationToken::new(),
                ListPathRawOptions {
                    disks: vec![None, None, None],
                    min_disks: 2,
                    test_reader_behaviors: vec![
                        TestReaderBehavior::Eof,
                        TestReaderBehavior::Eof,
                        TestReaderBehavior::IgnoreCancel,
                    ],
                    peek_timeout: Some(Duration::from_millis(20)),
                    ..Default::default()
                },
            ),
        )
        .await;

        let listing = result.expect("list_path_raw should abort unresponsive producer instead of hanging");
        listing.expect("unresponsive producer within failure budget should not fail quorum EOF");
    }

    #[tokio::test]
    async fn list_path_raw_treats_external_cancel_as_successful_shutdown() {
        let cancel = CancellationToken::new();
        cancel.cancel();

        list_path_raw(
            cancel,
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::IgnoreCancel],
                ..Default::default()
            },
        )
        .await
        .expect("external cancellation should stop listing without a synthetic canceled error");
    }

    #[tokio::test]
    async fn list_path_raw_cancels_a_blocked_peek_without_waiting_for_the_stall_timeout() {
        let cancel = CancellationToken::new();
        let entered = Arc::new(tokio::sync::Notify::new());
        let stopped = Arc::new(tokio::sync::Notify::new());
        let list = tokio::spawn(list_path_raw(
            cancel.clone(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::StallWithSignals {
                    entered: entered.clone(),
                    stopped: stopped.clone(),
                }],
                peek_timeout: Some(Duration::from_secs(60)),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), entered.notified())
            .await
            .expect("producer should block before cancellation");
        cancel.cancel();

        let result = timeout(Duration::from_secs(1), list)
            .await
            .expect("cancellation should interrupt the blocked metacache peek")
            .expect("listing task should not panic");
        assert!(result.is_ok(), "cancellation should stop the listing cleanly, got {result:?}");
        timeout(Duration::from_secs(1), stopped.notified())
            .await
            .expect("cancellation should drop the blocked producer");
    }

    #[tokio::test]
    async fn aborting_list_path_raw_drops_blocked_producers() {
        let entered = Arc::new(tokio::sync::Notify::new());
        let stopped = Arc::new(tokio::sync::Notify::new());
        let list = tokio::spawn(list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::StallWithSignals {
                    entered: entered.clone(),
                    stopped: stopped.clone(),
                }],
                peek_timeout: Some(Duration::from_secs(60)),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), entered.notified())
            .await
            .expect("producer should block before aborting the listing");
        list.abort();
        assert!(list.await.expect_err("listing task should be cancelled").is_cancelled());
        timeout(Duration::from_secs(1), stopped.notified())
            .await
            .expect("aborting the listing should drop the blocked producer");
    }

    #[tokio::test]
    async fn list_path_raw_propagates_partial_callback_failure() {
        let first = MetaCacheEntry {
            name: "bucket/object-a".to_string(),
            metadata: vec![1],
            ..Default::default()
        };
        let second = MetaCacheEntry {
            name: "bucket/object-b".to_string(),
            metadata: vec![2],
            ..Default::default()
        };

        let err = list_path_raw_with_partial_result(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Entries(vec![first]),
                    TestReaderBehavior::Entries(vec![second]),
                ],
                ..Default::default()
            },
            FallbackClaimTracker::default(),
            Box::new(move |_, _| Box::pin(async { Err(DiskError::ErasureReadQuorum) })),
        )
        .await
        .expect_err("a resolution failure after reader advancement must fail the listing");

        assert_eq!(err, DiskError::ErasureReadQuorum);
    }

    #[tokio::test]
    async fn list_path_raw_cancels_a_blocked_partial_callback() {
        let cancel = CancellationToken::new();
        let callback_started = Arc::new(tokio::sync::Notify::new());
        let callback_started_clone = callback_started.clone();
        let entry = MetaCacheEntry {
            name: "bucket/object-a".to_string(),
            metadata: vec![1],
            ..Default::default()
        };
        let later_entry = MetaCacheEntry {
            name: "bucket/object-b".to_string(),
            metadata: vec![1],
            ..Default::default()
        };
        let list = tokio::spawn(list_path_raw(
            cancel.clone(),
            ListPathRawOptions {
                disks: vec![None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Entries(vec![entry]),
                    TestReaderBehavior::Entries(vec![later_entry]),
                ],
                partial: Some(Box::new(move |_, _| {
                    let callback_started = callback_started_clone.clone();
                    Box::pin(async move {
                        callback_started.notify_one();
                        std::future::pending::<()>().await;
                    })
                })),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), callback_started.notified())
            .await
            .expect("partial callback should block before cancellation");
        cancel.cancel();

        let result = timeout(Duration::from_secs(1), list)
            .await
            .expect("cancellation should interrupt the blocked partial callback")
            .expect("listing task should not panic");
        assert!(result.is_ok(), "cancellation should stop the listing cleanly, got {result:?}");
    }

    #[tokio::test]
    async fn list_path_raw_cancels_a_blocked_agreed_callback() {
        let cancel = CancellationToken::new();
        let callback_started = Arc::new(tokio::sync::Notify::new());
        let callback_started_clone = callback_started.clone();
        let entry = MetaCacheEntry {
            name: "bucket/object".to_string(),
            metadata: vec![1],
            ..Default::default()
        };
        let list = tokio::spawn(list_path_raw(
            cancel.clone(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::Entries(vec![entry])],
                agreed: Some(Box::new(move |_| {
                    let callback_started = callback_started_clone.clone();
                    Box::pin(async move {
                        callback_started.notify_one();
                        std::future::pending::<()>().await;
                    })
                })),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), callback_started.notified())
            .await
            .expect("agreed callback should block before cancellation");
        cancel.cancel();

        let result = timeout(Duration::from_secs(1), list)
            .await
            .expect("cancellation should interrupt the blocked agreed callback")
            .expect("listing task should not panic");
        assert!(result.is_ok(), "cancellation should stop the listing cleanly, got {result:?}");
    }

    #[tokio::test]
    async fn list_path_raw_cancels_a_blocked_finished_callback_after_quorum_failure() {
        let cancel = CancellationToken::new();
        let callback_started = Arc::new(tokio::sync::Notify::new());
        let callback_started_clone = callback_started.clone();
        let list = tokio::spawn(list_path_raw(
            cancel.clone(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::ProducerError(DiskError::FileAccessDenied)],
                finished: Some(Box::new(move |_| {
                    let callback_started = callback_started_clone.clone();
                    Box::pin(async move {
                        callback_started.notify_one();
                        std::future::pending::<()>().await;
                    })
                })),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), callback_started.notified())
            .await
            .expect("finished callback should block before cancellation");
        cancel.cancel();

        let result = timeout(Duration::from_secs(1), list)
            .await
            .expect("cancellation should interrupt the blocked finished callback")
            .expect("listing task should not panic");
        assert!(result.is_ok(), "cancellation should stop the listing cleanly, got {result:?}");
    }

    #[tokio::test]
    async fn list_path_raw_cancels_a_blocked_finished_callback_after_tolerated_error() {
        let cancel = CancellationToken::new();
        let callback_started = Arc::new(tokio::sync::Notify::new());
        let callback_started_clone = callback_started.clone();
        let list = tokio::spawn(list_path_raw(
            cancel.clone(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::ProducerError(DiskError::FileAccessDenied),
                ],
                finished: Some(Box::new(move |_| {
                    let callback_started = callback_started_clone.clone();
                    Box::pin(async move {
                        callback_started.notify_one();
                        std::future::pending::<()>().await;
                    })
                })),
                ..Default::default()
            },
        ));

        timeout(Duration::from_secs(1), callback_started.notified())
            .await
            .expect("finished callback should block before cancellation");
        cancel.cancel();

        let result = timeout(Duration::from_secs(1), list)
            .await
            .expect("cancellation should interrupt the blocked finished callback")
            .expect("listing task should not panic");
        assert!(result.is_ok(), "cancellation should stop the listing cleanly, got {result:?}");
    }

    #[tokio::test]
    async fn list_path_raw_ignores_closed_output_stream_after_quorum_eof() {
        list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::ProducerError(DiskError::metacache_output_stream_closed()),
                ],
                ..Default::default()
            },
        )
        .await
        .expect("closed metacache output after quorum EOF should not fail listing");
    }

    #[tokio::test]
    async fn list_path_raw_tolerates_concurrent_scan_after_quorum_eof() {
        let result = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::Eof,
                    TestReaderBehavior::ProducerError(DiskError::DiskOngoingReq),
                ],
                ..Default::default()
            },
        )
        .await;

        assert!(result.is_ok(), "concurrent scan after quorum EOF should not fail listing");
    }

    #[tokio::test]
    async fn list_path_raw_returns_timeout_when_producer_fails_after_partial_entry() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_clone = seen.clone();
        let claim_tracker = FallbackClaimTracker::default();

        let err = list_path_raw_with_claim_tracker(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::PartialThenTimeout(vec![MetaCacheEntry {
                    name: "bucket/object".to_string(),
                    metadata: vec![1, 2, 3],
                    cached: None,
                    reusable: false,
                }])],
                test_fallback_reader_behaviors: vec![TestReaderBehavior::Entries(vec![fallback_test_entry()])],
                agreed: Some(Box::new(move |entry: MetaCacheEntry| {
                    let seen = seen_clone.clone();
                    Box::pin(async move {
                        seen.lock().expect("seen mutex poisoned").push(entry.name);
                    })
                })),
                ..Default::default()
            },
            claim_tracker.clone(),
        )
        .await
        .expect_err("producer timeout after partial output must fail the listing");

        assert_eq!(err, DiskError::Timeout);
        assert_eq!(seen.lock().expect("seen mutex poisoned").as_slice(), &["bucket/object".to_string()]);
        assert!(
            claim_tracker.claimed_keys().await.is_empty(),
            "fallback must not append a second metacache stream after partial output"
        );
    }

    #[tokio::test]
    async fn list_path_raw_does_not_try_second_fallback_after_partial_fallback_output() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_clone = seen.clone();
        let claim_tracker = FallbackClaimTracker::default();

        let err = list_path_raw_with_claim_tracker(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::PrimaryErrorThenFallback(DiskError::DiskNotFound)],
                test_fallback_reader_behaviors: vec![
                    TestReaderBehavior::PartialThenTimeout(vec![MetaCacheEntry {
                        name: "bucket/partial-fallback".to_string(),
                        metadata: vec![1, 2, 3],
                        cached: None,
                        reusable: false,
                    }]),
                    TestReaderBehavior::Entries(vec![fallback_test_entry()]),
                ],
                agreed: Some(Box::new(move |entry: MetaCacheEntry| {
                    let seen = seen_clone.clone();
                    Box::pin(async move {
                        seen.lock().expect("seen mutex poisoned").push(entry.name);
                    })
                })),
                ..Default::default()
            },
            claim_tracker.clone(),
        )
        .await
        .expect_err("a fallback timeout after partial output must fail the listing");

        assert_eq!(err, DiskError::Timeout);
        assert_eq!(
            seen.lock().expect("seen mutex poisoned").as_slice(),
            &["bucket/partial-fallback".to_string()]
        );
        assert_eq!(claim_tracker.claimed_keys().await.len(), 1, "a second fallback must not be claimed");
    }

    #[tokio::test]
    async fn list_path_raw_continues_after_single_disk_delete_marker_gap() {
        fn object_entry(name: &str, version_id: &str) -> MetaCacheEntry {
            let mut meta = FileMeta::default();
            let mut fi = FileInfo::new(name, 1, 1);
            fi.version_id = Some(Uuid::parse_str(version_id).expect("test version id should parse"));
            fi.mod_time = Some(OffsetDateTime::now_utc());
            meta.add_version(fi).expect("object metadata should be valid");
            MetaCacheEntry {
                name: name.to_string(),
                metadata: meta.marshal_msg().expect("object metadata should encode"),
                cached: Some(meta),
                reusable: false,
            }
        }

        fn delete_marker_entry(name: &str, version_id: &str) -> MetaCacheEntry {
            let mut meta = FileMeta::default();
            meta.add_version(FileInfo {
                deleted: true,
                version_id: Some(Uuid::parse_str(version_id).expect("test version id should parse")),
                mod_time: Some(OffsetDateTime::now_utc()),
                ..Default::default()
            })
            .expect("delete marker metadata should be valid");
            MetaCacheEntry {
                name: name.to_string(),
                metadata: meta.marshal_msg().expect("delete marker metadata should encode"),
                cached: Some(meta),
                reusable: false,
            }
        }

        let visible_before = object_entry("object-000003", "11111111-1111-1111-1111-111111111111");
        let hidden_delete = delete_marker_entry("object-000004", "22222222-2222-2222-2222-222222222222");
        let visible_after = object_entry("object-000005", "33333333-3333-3333-3333-333333333333");
        let seen = Arc::new(Mutex::new(Vec::new()));
        let agreed_seen = seen.clone();
        let partial_seen = seen.clone();

        list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None, None, None, None],
                min_disks: 2,
                test_reader_behaviors: vec![
                    TestReaderBehavior::Entries(vec![visible_before.clone(), hidden_delete, visible_after.clone()]),
                    TestReaderBehavior::Entries(vec![visible_before.clone(), visible_after.clone()]),
                    TestReaderBehavior::Entries(vec![visible_before.clone(), visible_after.clone()]),
                    TestReaderBehavior::Entries(vec![visible_before, visible_after]),
                ],
                agreed: Some(Box::new(move |entry| {
                    let seen = agreed_seen.clone();
                    Box::pin(async move {
                        seen.lock().expect("seen mutex poisoned").push(entry.name);
                    })
                })),
                partial: Some(Box::new(move |entries, _| {
                    let seen = partial_seen.clone();
                    Box::pin(async move {
                        if let Some(entry) = entries.resolve(MetadataResolutionParams {
                            obj_quorum: 2,
                            requested_versions: 1,
                            bucket: "bucket".to_string(),
                            ..Default::default()
                        }) {
                            seen.lock().expect("seen mutex poisoned").push(entry.name);
                        }
                    })
                })),
                ..Default::default()
            },
        )
        .await
        .expect("single-disk delete marker gap should not end listing");

        assert_eq!(
            seen.lock().expect("seen mutex poisoned").as_slice(),
            &["object-000003".to_string(), "object-000005".to_string()]
        );
    }

    #[tokio::test]
    async fn peek_with_timeout_times_out_on_silent_reader() {
        let (_writer, reader) = tokio::io::duplex(64);
        let mut reader = MetacacheReader::new(reader);
        let cancel = CancellationToken::new();

        let outcome = peek_with_timeout(&cancel, &mut reader, Duration::from_millis(20)).await;
        assert!(matches!(outcome, PeekOutcome::TimedOut));
    }

    #[tokio::test]
    async fn peek_with_timeout_stops_immediately_when_cancelled() {
        struct PendingReader(Arc<tokio::sync::Notify>);

        impl AsyncRead for PendingReader {
            fn poll_read(
                self: std::pin::Pin<&mut Self>,
                _cx: &mut std::task::Context<'_>,
                _buf: &mut tokio::io::ReadBuf<'_>,
            ) -> std::task::Poll<std::io::Result<()>> {
                self.get_mut().0.notify_one();
                std::task::Poll::Pending
            }
        }

        let entered = Arc::new(tokio::sync::Notify::new());
        let mut reader = MetacacheReader::new(PendingReader(entered.clone()));
        let cancel = CancellationToken::new();
        let wait_cancel = cancel.clone();

        let wait = tokio::spawn(async move { peek_with_timeout(&wait_cancel, &mut reader, Duration::from_secs(60)).await });
        timeout(Duration::from_secs(1), entered.notified())
            .await
            .expect("peek should block before cancellation");
        cancel.cancel();

        let outcome = timeout(Duration::from_secs(1), wait)
            .await
            .expect("cancellation should interrupt the pending peek")
            .expect("peek task should not panic");
        assert!(matches!(outcome, PeekOutcome::Cancelled));
    }

    #[tokio::test]
    async fn peek_with_timeout_reads_entry_before_deadline() {
        let (reader, writer) = tokio::io::duplex(256);
        let mut metacache_reader = MetacacheReader::new(reader);
        let cancel = CancellationToken::new();

        tokio::spawn(async move {
            let mut writer = MetacacheWriter::new(writer);
            let entry = MetaCacheEntry {
                name: "bucket/object".to_string(),
                metadata: vec![1, 2, 3],
                cached: None,
                reusable: false,
            };
            writer.write(&[entry]).await.expect("entry should be written");
            writer.close().await.expect("writer should close");
        });

        let outcome = peek_with_timeout(&cancel, &mut metacache_reader, Duration::from_secs(1)).await;
        match outcome {
            PeekOutcome::Ready(Some(entry)) => assert_eq!(entry.name, "bucket/object"),
            other => panic!("expected ready entry, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_path_raw_propagates_producer_access_denied() {
        let err = list_path_raw(
            CancellationToken::new(),
            ListPathRawOptions {
                disks: vec![None],
                min_disks: 1,
                test_reader_behaviors: vec![TestReaderBehavior::ProducerError(DiskError::FileAccessDenied)],
                ..Default::default()
            },
        )
        .await
        .expect_err("producer access failure must not be treated as an empty listing");

        assert_eq!(err, DiskError::FileAccessDenied);
    }
}