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
// 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::cluster::rpc::client::is_network_like_disk_error;
use crate::config::storageclass;
use crate::core::pools::PoolMetaBootstrapAuthority;
use crate::disk::error_reduce::{count_errs, reduce_write_quorum_errs};
use crate::disk::{self, DiskAPI};
use crate::error::{Error, Result};
use crate::runtime::instance::InstanceContext;
use crate::runtime::sources::{quarantine_local_disks, reconcile_local_disk_ids};
use crate::{
    disk::{
        DiskInfoOptions, DiskOption, DiskStore, FORMAT_CONFIG_FILE, MIGRATING_META_BUCKET, RUSTFS_META_BUCKET,
        error::DiskError,
        format::{FormatBackend, FormatErasureVersion, FormatMetaVersion, FormatV3},
        new_disk,
    },
    layout::endpoints::Endpoints,
};
use futures::{future::join_all, stream, stream::StreamExt};
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};
use tokio::io::AsyncReadExt;
use tracing::{debug, error, info, warn};
use uuid::Uuid;

const LEGACY_FORMAT_READ_CONCURRENCY: usize = 16;
const LEGACY_FORMAT_BASE_MAX_BYTES: usize = 16 * 1024;
const LEGACY_FORMAT_MAX_BYTES_PER_DISK: usize = 64;

pub async fn init_disks(eps: &Endpoints, opt: &DiskOption) -> (Vec<Option<DiskStore>>, Vec<Option<DiskError>>) {
    let mut futures = Vec::with_capacity(eps.as_ref().len());

    for ep in eps.as_ref().iter() {
        futures.push(new_disk(ep, opt));
    }

    let mut res = Vec::with_capacity(eps.as_ref().len());
    let mut errors = Vec::with_capacity(eps.as_ref().len());

    let results = join_all(futures).await;
    for result in results {
        match result {
            Ok(s) => {
                res.push(Some(s));
                errors.push(None);
            }
            Err(e) => {
                res.push(None);
                errors.push(Some(e));
            }
        }
    }

    (res, errors)
}

#[cfg(test)]
pub async fn connect_load_init_formats(
    first_disk: bool,
    disks: &mut [Option<DiskStore>],
    set_count: usize,
    set_drive_count: usize,
    deployment_id: Option<Uuid>,
) -> Result<FormatV3> {
    let instance_ctx = crate::runtime::global::current_ctx();
    connect_load_init_formats_with_instance_ctx(&instance_ctx, first_disk, disks, set_count, set_drive_count, deployment_id)
        .await
        .map(|loaded| loaded.format)
}

pub(crate) struct LoadedFormat {
    pub(crate) format: FormatV3,
    pub(crate) pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority,
}

pub(crate) async fn connect_load_init_formats_with_instance_ctx(
    instance_ctx: &Arc<InstanceContext>,
    first_disk: bool,
    disks: &mut [Option<DiskStore>],
    set_count: usize,
    set_drive_count: usize,
    deployment_id: Option<Uuid>,
) -> Result<LoadedFormat> {
    let (formats, errs) = load_format_erasure_all(disks, false).await;

    check_disk_fatal_errs(&errs)?;

    // Transient network errors still follow the first-node wait path so peers
    // can come online, but they are never fresh-cluster authority below.
    let all_unformatted = errs.iter().all(is_unformatted_or_transient_network);
    // Fresh-cluster authority requires a response from every configured disk.
    // A transiently unreachable peer may belong to an existing cluster and
    // must never be treated as proof that the topology is new.
    let fresh_bootstrap_proven = should_init_erasure_disks(&errs);
    let formats_present = formats.iter().flatten().count();
    let mut format_quorum = (formats_present > 0).then(|| select_format_erasure_in_quorum(&formats, 0));
    // A resized pool may never reach quorum under its new endpoint count.
    // Diagnose a valid, unambiguous stored layout before migration or waiting.
    // A healthy quorum still takes precedence over foreign minority formats;
    // conflicting or malformed observations retain their existing error path.
    if format_quorum.as_ref().is_some_and(Result::is_err)
        && let Some(reference) = formats.iter().flatten().next()
        && formats.iter().flatten().all(|format| {
            format.shared_identity() == reference.shared_identity()
                && reference.erasure.sets.iter().flatten().any(|id| *id == format.erasure.this)
        })
        && let Err(err @ (Error::UnsupportedSnsdExpansion { .. } | Error::PoolTopologyMismatch { .. })) =
            check_format_erasure_value_for_topology(reference, formats.len(), set_drive_count)
    {
        return Err(err);
    }
    if format_quorum.as_ref().is_none_or(Result::is_err)
        && errs.iter().any(|error| {
            matches!(
                error,
                Some(DiskError::InconsistentDisk | DiskError::CorruptedFormat | DiskError::CorruptedBackend)
            )
        })
    {
        return Err(Error::CorruptedFormat);
    }
    let resumable_partial_migration = formats_present > 0
        && errs.iter().any(|error| matches!(error, Some(DiskError::UnformattedDisk)))
        && format_quorum.as_ref().is_some_and(Result::is_err)
        && formats.iter().zip(&errs).all(|(format, error)| {
            format.is_some() || matches!(error, Some(DiskError::UnformattedDisk | DiskError::DiskNotFound))
        });

    if first_disk && (all_unformatted || resumable_partial_migration) {
        info!(all_unformatted, resumable_partial_migration, "checking for a legacy storage format");
        match try_migrate_format(disks, &formats, set_count, set_drive_count).await {
            Ok(LegacyFormatOutcome::Migrated { format, quorum_members }) => {
                info!("Migrated format from MinIO config");
                retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, set_drive_count).await?;
                return Ok(LoadedFormat {
                    format: *format,
                    pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::LegacyAdoption,
                });
            }
            Ok(LegacyFormatOutcome::Incompatible) => {
                error!(
                    event = "legacy_format_migration_rejected",
                    component = "ecstore",
                    subsystem = "store_init",
                    state = "incompatible",
                    "detected MinIO format.json but could not migrate it safely"
                );
                return Err(Error::CorruptedFormat);
            }
            Ok(LegacyFormatOutcome::None) => {}
            Err(e) => return Err(e),
        }
        if fresh_bootstrap_proven {
            let fm = init_format_erasure(instance_ctx, disks, set_count, set_drive_count, deployment_id).await?;
            return Ok(LoadedFormat {
                format: fm,
                pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::Fresh,
            });
        }
    }

    info!(
        "first_disk: {}, should_init_erasure_disks: {}",
        first_disk,
        should_init_erasure_disks(&errs)
    );

    let unformatted = errs.iter().filter(|e| is_unformatted_or_transient_network(e)).count() > (errs.len() / 2);
    if unformatted && !first_disk {
        return Err(Error::NotFirstDisk);
    }

    if unformatted && first_disk {
        return Err(Error::FirstDiskWait);
    }

    let (fm, quorum_members) = match format_quorum.take() {
        Some(result) => result?,
        None => select_format_erasure_in_quorum(&formats, 0)?,
    };
    check_format_erasure_value_for_topology(&fm, formats.len(), set_drive_count)?;
    retain_format_quorum_members(instance_ctx, disks, &fm, &quorum_members, set_drive_count).await?;

    Ok(LoadedFormat {
        format: fm,
        pool_meta_bootstrap_authority: verified_legacy_adoption_source(disks, &formats, set_count, set_drive_count).await?,
    })
}

async fn verified_legacy_adoption_source(
    disks: &[Option<DiskStore>],
    rustfs_formats: &[Option<FormatV3>],
    set_count: usize,
    set_drive_count: usize,
) -> Result<PoolMetaBootstrapAuthority> {
    match try_migrate_format(disks, rustfs_formats, set_count, set_drive_count).await {
        Ok(LegacyFormatOutcome::Migrated { .. }) => Ok(PoolMetaBootstrapAuthority::LegacyAdoption),
        Ok(LegacyFormatOutcome::None | LegacyFormatOutcome::Incompatible) => Ok(PoolMetaBootstrapAuthority::None),
        Err(err) => {
            debug!(
                error = %err,
                "legacy adoption proof skipped because legacy format verification failed"
            );
            Ok(PoolMetaBootstrapAuthority::None)
        }
    }
}

async fn retain_format_quorum_members(
    instance_ctx: &Arc<InstanceContext>,
    disks: &mut [Option<DiskStore>],
    format: &FormatV3,
    quorum_members: &[bool],
    set_drive_count: usize,
) -> Result<()> {
    if set_drive_count == 0 || quorum_members.len() != disks.len() {
        return Err(Error::CorruptedFormat);
    }

    let pool_idx = disks
        .iter()
        .flatten()
        .map(|disk| disk.endpoint().pool_idx)
        .find_map(|pool_idx| usize::try_from(pool_idx).ok());
    let registered_endpoints = if let Some(pool_idx) = pool_idx {
        instance_ctx
            .local_disk_set_drives()
            .read()
            .await
            .get(pool_idx)
            .map(|sets| {
                sets.iter()
                    .flat_map(|set| set.iter())
                    .map(|disk| disk.as_ref().map(|disk| disk.endpoint()))
                    .collect::<Vec<_>>()
            })
            .filter(|endpoints| endpoints.len() == disks.len())
    } else {
        None
    };
    let endpoints = disks
        .iter()
        .enumerate()
        .map(|(index, disk)| {
            disk.as_ref()
                .map(|disk| disk.endpoint())
                .or_else(|| registered_endpoints.as_ref()?.get(index)?.clone())
        })
        .collect::<Vec<_>>();

    let mut member_disk_ids = vec![None; disks.len()];
    let mut local_pool_endpoints = Vec::new();
    let mut selected_local_disk_ids = Vec::new();
    let mut quarantined_endpoints = Vec::new();
    for (index, ((disk, endpoint), belongs_to_quorum)) in disks.iter().zip(&endpoints).zip(quorum_members).enumerate() {
        if let Some(endpoint) = endpoint.as_ref().filter(|endpoint| endpoint.is_local) {
            local_pool_endpoints.push(endpoint.to_string());
            if !belongs_to_quorum {
                quarantined_endpoints.push(endpoint.clone());
            }
        }
        if !belongs_to_quorum {
            continue;
        }
        let disk = disk.as_ref().ok_or(Error::CorruptedFormat)?;
        let disk_id = format
            .erasure
            .sets
            .get(index / set_drive_count)
            .and_then(|set| set.get(index % set_drive_count))
            .copied()
            .ok_or(Error::CorruptedFormat)?;
        member_disk_ids[index] = Some(disk_id);
        if disk.is_local() {
            selected_local_disk_ids.push((disk_id, disk.endpoint().to_string()));
        }
    }
    quarantine_local_disks(instance_ctx, &quarantined_endpoints).await?;

    for (disk, disk_id) in disks.iter().zip(member_disk_ids) {
        if let Some(disk) = disk {
            disk.set_disk_id_state(disk_id).await?;
        }
    }
    reconcile_local_disk_ids(instance_ctx, &local_pool_endpoints, &selected_local_disk_ids).await;
    for (disk, belongs_to_quorum) in disks.iter_mut().zip(quorum_members) {
        if !belongs_to_quorum {
            *disk = None;
        }
    }
    Ok(())
}

pub fn should_init_erasure_disks(errs: &[Option<DiskError>]) -> bool {
    count_errs(errs, &DiskError::UnformattedDisk) == errs.len()
}

/// Returns `true` for errors that stay on the first-node wait path. This is not
/// fresh-cluster proof; only [`should_init_erasure_disks`] grants that.
fn is_unformatted_or_transient_network(err: &Option<DiskError>) -> bool {
    matches!(err, Some(DiskError::UnformattedDisk)) || err.as_ref().is_some_and(is_network_like_disk_error)
}

pub fn check_disk_fatal_errs(errs: &[Option<DiskError>]) -> disk::error::Result<()> {
    if count_errs(errs, &DiskError::UnsupportedDisk) == errs.len() {
        return Err(DiskError::UnsupportedDisk);
    }

    if count_errs(errs, &DiskError::FileAccessDenied) == errs.len() {
        return Err(DiskError::FileAccessDenied);
    }

    if count_errs(errs, &DiskError::DiskNotDir) == errs.len() {
        return Err(DiskError::DiskNotDir);
    }

    Ok(())
}

async fn init_format_erasure(
    instance_ctx: &Arc<InstanceContext>,
    disks: &mut [Option<DiskStore>],
    set_count: usize,
    set_drive_count: usize,
    deployment_id: Option<Uuid>,
) -> Result<FormatV3> {
    let fm = FormatV3::new(set_count, set_drive_count);
    let mut fms = vec![None; disks.len()];
    for i in 0..set_count {
        for j in 0..set_drive_count {
            let idx = i * set_drive_count + j;
            let mut newfm = fm.clone();
            newfm.erasure.this = fm.erasure.sets[i][j];
            if let Some(id) = deployment_id {
                newfm.id = id;
            }

            fms[idx] = Some(newfm);
        }
    }

    write_format_file_all(disks, &fms).await?;
    let format = get_format_erasure_in_quorum(&fms, 0)?;
    let quorum_members = vec![true; disks.len()];
    retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, set_drive_count).await?;
    Ok(format)
}

/// Outcome of attempting to migrate an on-disk MinIO `format.json`.
enum LegacyFormatOutcome {
    /// A compatible MinIO format was found and migrated into RustFS format files.
    /// Boxed to keep the enum small (`FormatV3` is large; the others are unit variants).
    Migrated {
        format: Box<FormatV3>,
        quorum_members: Vec<bool>,
    },
    /// A MinIO `format.json` was present but could not be migrated (topology /
    /// version mismatch, or a parse failure). The caller must decide how to
    /// proceed; creating a fresh format would leave the legacy objects unreadable.
    Incompatible,
    /// No MinIO `format.json` was present on any disk (a normal fresh install).
    None,
}

/// Tries to migrate an on-disk MinIO `format.json` into RustFS format files.
///
/// Returns [`LegacyFormatOutcome`] describing whether a legacy format was present
/// and, if so, whether it was compatible. `Err` is returned for read or persist
/// failures that prevent a conclusive migration decision.
async fn try_migrate_format(
    disks: &[Option<DiskStore>],
    rustfs_formats: &[Option<FormatV3>],
    set_count: usize,
    set_drive_count: usize,
) -> Result<LegacyFormatOutcome> {
    let legacy_format_max_bytes = legacy_format_max_bytes(disks.len())?;
    let mut legacy_seen = false;
    let mut invalid_legacy_format = false;
    let mut read_error: Option<Error> = None;
    let mut legacy_formats = vec![None; disks.len()];

    let reads = stream::iter(disks.iter().enumerate().map(|(index, disk)| async move {
        let Some(disk) = disk else {
            return (index, None);
        };
        let reader = match disk.read_file(MIGRATING_META_BUCKET, FORMAT_CONFIG_FILE).await {
            Ok(reader) => reader,
            Err(DiskError::FileNotFound | DiskError::VolumeNotFound) => return (index, None),
            Err(err) => return (index, Some(Err(err))),
        };
        let data = match read_legacy_format_bytes(reader, legacy_format_max_bytes).await {
            Ok(data) => data,
            Err(err) => return (index, Some(Err(err))),
        };
        if data.is_empty() {
            return (index, Some(Ok(None)));
        }

        match FormatV3::try_from(data.as_slice()) {
            Ok(format) => (index, Some(Ok(Some(format)))),
            Err(err) => {
                warn!(
                    event = "legacy_format_decode_failed",
                    component = "ecstore",
                    subsystem = "store_init",
                    disk_index = index,
                    error = %err,
                    "failed to decode legacy storage format"
                );
                (index, Some(Ok(None)))
            }
        }
    }))
    .buffer_unordered(LEGACY_FORMAT_READ_CONCURRENCY);
    tokio::pin!(reads);
    while let Some((index, read)) = reads.next().await {
        let Some(read) = read else {
            continue;
        };
        legacy_seen = true;
        match read {
            Ok(Some(format)) => legacy_formats[index] = Some(format),
            Ok(None) => invalid_legacy_format = true,
            Err(err) => {
                read_error.get_or_insert_with(|| err.into());
            }
        }
    }

    if let Some(err) = read_error {
        return Err(err);
    }
    if !legacy_seen {
        return Ok(LegacyFormatOutcome::None);
    }
    if invalid_legacy_format {
        return Ok(LegacyFormatOutcome::Incompatible);
    }

    let format = match get_format_erasure_in_quorum(&legacy_formats, 0) {
        Ok(format) => format,
        Err(_) => return Ok(LegacyFormatOutcome::Incompatible),
    };
    if format.erasure.sets.len() != set_count
        || check_format_erasure_value_for_topology(&format, disks.len(), set_drive_count).is_err()
        || !formats_match_reference_slots(&legacy_formats, &format, 0)
        || !formats_match_reference_slots(rustfs_formats, &format, 0)
    {
        return Ok(LegacyFormatOutcome::Incompatible);
    }

    let mut formats_to_write = vec![None; disks.len()];
    for (index, disk) in disks.iter().enumerate() {
        if disk.is_some() {
            let mut disk_format = format.clone();
            disk_format.erasure.this = format.erasure.sets[index / set_drive_count][index % set_drive_count];
            formats_to_write[index] = Some(disk_format);
        }
    }

    let writes = disks
        .iter()
        .zip(&formats_to_write)
        .zip(rustfs_formats)
        .filter_map(|((disk, format), existing)| {
            if existing.is_some() {
                return None;
            }
            Some(write_format_file(disk.as_ref()?, format.as_ref()?))
        });
    let mut write_error = None;
    for result in join_all(writes).await {
        if let Err(error) = result {
            write_error.get_or_insert(error);
        }
    }
    let (persisted_formats, persisted_errors) = load_format_erasure_all(disks, false).await;
    let Some((persisted_format, quorum_members)) =
        select_persisted_migration_format(&persisted_formats, persisted_errors, &format, set_drive_count, write_error)?
    else {
        return Ok(LegacyFormatOutcome::Incompatible);
    };

    Ok(LegacyFormatOutcome::Migrated {
        format: Box::new(persisted_format),
        quorum_members,
    })
}

fn select_persisted_migration_format(
    persisted_formats: &[Option<FormatV3>],
    persisted_errors: Vec<Option<DiskError>>,
    reference: &FormatV3,
    set_drive_count: usize,
    write_error: Option<DiskError>,
) -> Result<Option<(FormatV3, Vec<bool>)>> {
    if !formats_match_reference_slots(persisted_formats, reference, 0) {
        return Ok(None);
    }
    let quorum_error = match select_format_erasure_in_quorum(persisted_formats, 0) {
        Ok((format, quorum_members)) => {
            check_format_erasure_value_for_topology(&format, persisted_formats.len(), set_drive_count)?;
            return Ok(Some((format, quorum_members)));
        }
        Err(error) => error,
    };
    if let Some(error) = persisted_errors
        .into_iter()
        .flatten()
        .find(|error| !matches!(error, DiskError::UnformattedDisk | DiskError::DiskNotFound))
    {
        return match error {
            DiskError::CorruptedFormat | DiskError::CorruptedBackend | DiskError::InconsistentDisk => Ok(None),
            error => Err(error.into()),
        };
    }
    Err(write_error.map_or(quorum_error, Into::into))
}

fn legacy_format_max_bytes(disk_count: usize) -> Result<usize> {
    disk_count
        .checked_mul(LEGACY_FORMAT_MAX_BYTES_PER_DISK)
        .and_then(|size| size.checked_add(LEGACY_FORMAT_BASE_MAX_BYTES))
        .ok_or_else(|| Error::other("legacy format size limit overflow"))
}

async fn read_legacy_format_bytes(reader: impl tokio::io::AsyncRead + Unpin, max_bytes: usize) -> disk::error::Result<Vec<u8>> {
    let read_limit = max_bytes.checked_add(1).ok_or(DiskError::CorruptedFormat)?;
    let mut data = Vec::with_capacity(read_limit.min(64 * 1024));
    reader
        .take(u64::try_from(read_limit).map_err(|_| DiskError::CorruptedFormat)?)
        .read_to_end(&mut data)
        .await?;
    if data.len() > max_bytes {
        return Err(DiskError::CorruptedFormat);
    }
    Ok(data)
}

pub(crate) fn formats_match_reference_slots(formats: &[Option<FormatV3>], reference: &FormatV3, slot_offset: usize) -> bool {
    let Ok(set_drive_count) = validate_format_erasure_layout(reference) else {
        return false;
    };

    formats.iter().enumerate().all(|(index, format)| {
        format.as_ref().is_none_or(|format| {
            format.shared_identity() == reference.shared_identity()
                && slot_offset
                    .checked_add(index)
                    .and_then(|slot| {
                        reference
                            .erasure
                            .sets
                            .get(slot / set_drive_count)
                            .and_then(|set| set.get(slot % set_drive_count))
                    })
                    .is_some_and(|expected| *expected == format.erasure.this)
        })
    })
}

pub fn get_format_erasure_in_quorum(formats: &[Option<FormatV3>], slot_offset: usize) -> Result<FormatV3> {
    select_format_erasure_in_quorum(formats, slot_offset).map(|(format, _)| format)
}

pub(crate) fn select_format_erasure_in_quorum(formats: &[Option<FormatV3>], slot_offset: usize) -> Result<(FormatV3, Vec<bool>)> {
    let mut candidates = HashMap::new();
    let formats_present = formats.iter().flatten().count();
    let required_votes = formats.len() / 2 + 1;

    for (index, format) in formats
        .iter()
        .enumerate()
        .filter_map(|(index, format)| Some((index, format.as_ref()?)))
    {
        let Some(slot) = slot_offset.checked_add(index) else {
            continue;
        };
        let (representative, set_drive_count, member_indices) = candidates
            .entry(format.shared_identity())
            .or_insert_with(|| (format, validate_format_erasure_layout(format).ok(), Vec::new()));
        let Some(set_drive_count) = *set_drive_count else {
            continue;
        };
        if representative
            .erasure
            .sets
            .get(slot / set_drive_count)
            .and_then(|set| set.get(slot % set_drive_count))
            .is_some_and(|expected| *expected == format.erasure.this)
        {
            member_indices.push(index);
        }
    }

    let candidate_groups = candidates
        .values()
        .filter(|(_, _, member_indices)| !member_indices.is_empty())
        .count();
    let log_quorum_failure = |max_votes| {
        warn!(
            event = "format_quorum_failed",
            component = "ecstore",
            subsystem = "store_init",
            state = "rejected",
            formats_total = formats.len(),
            formats_present,
            candidate_groups,
            max_votes,
            required_votes,
            "storage format quorum not reached"
        );
    };
    let Some((format, _, member_indices)) = candidates
        .into_values()
        .max_by_key(|(_, _, member_indices)| member_indices.len())
    else {
        log_quorum_failure(0);
        return Err(Error::ErasureReadQuorum);
    };

    let max_count = member_indices.len();
    if max_count < required_votes {
        log_quorum_failure(max_count);
        return Err(Error::ErasureReadQuorum);
    }

    let mut format = (*format).clone();
    format.erasure.this = Uuid::nil();
    format.disk_info = None;

    let mut member_mask = vec![false; formats.len()];
    for index in member_indices {
        member_mask[index] = true;
    }

    Ok((format, member_mask))
}

pub fn check_format_erasure_values(
    formats: &[Option<FormatV3>],
    // disks: &Vec<Option<DiskStore>>,
    set_drive_count: usize,
) -> Result<()> {
    let mut checked_identities = HashSet::new();
    for format in formats.iter().flatten() {
        // `shared_identity` contains every persisted field inspected by the
        // validators; only the per-slot UUID and runtime-only disk info differ.
        if checked_identities.insert(format.shared_identity()) {
            check_format_erasure_value_for_topology(format, formats.len(), set_drive_count)?;
        }
    }
    Ok(())
}

fn check_format_erasure_value_for_topology(format: &FormatV3, format_count: usize, set_drive_count: usize) -> Result<()> {
    let set_drive_count_in_format = validate_format_erasure_layout(format)?;
    let format_drive_count = format
        .erasure
        .sets
        .len()
        .checked_mul(set_drive_count_in_format)
        .ok_or_else(|| Error::other("erasure set drive count overflow"))?;
    if format_drive_count == 1 && format_count > 1 {
        return Err(Error::UnsupportedSnsdExpansion {
            configured_drives: format_count,
        });
    }
    if format_count != format_drive_count || set_drive_count_in_format != set_drive_count {
        return Err(Error::PoolTopologyMismatch {
            stored_drives: format_drive_count,
            stored_set_drive_count: set_drive_count_in_format,
            configured_drives: format_count,
            configured_set_drive_count: set_drive_count,
        });
    }
    Ok(())
}

fn check_format_erasure_value(format: &FormatV3) -> Result<()> {
    if format.version != FormatMetaVersion::V1 {
        return Err(Error::other("invalid FormatMetaVersion"));
    }

    if !matches!(format.format, FormatBackend::Erasure | FormatBackend::ErasureSingle) {
        return Err(Error::other("invalid FormatBackend"));
    }

    if format.id.is_nil() || format.id == Uuid::max() {
        return Err(Error::other("invalid deployment ID"));
    }

    if format.erasure.version != FormatErasureVersion::V3 {
        return Err(Error::other("invalid FormatErasureVersion"));
    }
    Ok(())
}

fn validate_format_erasure_layout(format: &FormatV3) -> Result<usize> {
    check_format_erasure_value(format)?;

    let set_drive_count = format
        .erasure
        .sets
        .first()
        .map(Vec::len)
        .filter(|count| *count > 0)
        .ok_or_else(|| Error::other("erasure.sets must contain at least one drive"))?;
    if format.erasure.sets.iter().any(|set| set.len() != set_drive_count) {
        return Err(Error::other("erasure.sets must be rectangular"));
    }
    let drive_count = format
        .erasure
        .sets
        .len()
        .checked_mul(set_drive_count)
        .ok_or_else(|| Error::other("erasure set drive count overflow"))?;
    let mut disk_ids = HashSet::with_capacity(drive_count);

    for disk_id in format.erasure.sets.iter().flatten() {
        if disk_id.is_nil() || *disk_id == Uuid::max() {
            return Err(Error::other("erasure.sets contains an invalid disk UUID"));
        }
        if !disk_ids.insert(*disk_id) {
            return Err(Error::other("erasure.sets contains a duplicate disk UUID"));
        }
    }

    Ok(set_drive_count)
}

// load_format_erasure_all reads all format.json files
pub async fn load_format_erasure_all(disks: &[Option<DiskStore>], heal: bool) -> (Vec<Option<FormatV3>>, Vec<Option<DiskError>>) {
    let mut futures = Vec::with_capacity(disks.len());
    let mut datas = Vec::with_capacity(disks.len());
    let mut errors = Vec::with_capacity(disks.len());

    for disk in disks.iter() {
        futures.push(async move {
            if let Some(disk) = disk {
                load_format_erasure(disk, heal).await
            } else {
                Err(DiskError::DiskNotFound)
            }
        });
    }

    let results = join_all(futures).await;
    for result in results {
        match result {
            Ok(s) => {
                datas.push(Some(s));
                errors.push(None);
            }
            Err(e) => {
                datas.push(None);
                errors.push(Some(e));
            }
        }
    }

    // Log aggregation summary of format load results
    let ok_count = errors.iter().filter(|e| e.is_none()).count();
    let err_count = errors.iter().filter(|e| e.is_some()).count();
    // Count occurrences of each unique error
    let mut err_counts: HashMap<String, usize> = HashMap::new();
    for err in errors.iter().flatten() {
        *err_counts.entry(format!("{err}")).or_default() += 1;
    }
    if !err_counts.is_empty() {
        debug!(
            disks_ok = ok_count,
            disks_err = err_count,
            disks_total = disks.len(),
            "load format erasure all errors: {:?}",
            err_counts
        );
    }

    (datas, errors)
}

pub async fn load_format_erasure(disk: &DiskStore, heal: bool) -> disk::error::Result<FormatV3> {
    let data = disk
        .read_all(RUSTFS_META_BUCKET, FORMAT_CONFIG_FILE)
        .await
        .map_err(|e| match e {
            DiskError::FileNotFound => DiskError::UnformattedDisk,
            DiskError::DiskNotFound => DiskError::UnformattedDisk,
            _ => {
                warn!("load_format_erasure err: {:?} {:?}", disk.to_string(), e);
                e
            }
        })?;

    let mut fm = FormatV3::try_from(data.as_ref())?;

    if heal {
        let info = disk
            .disk_info(&DiskInfoOptions {
                noop: heal,
                ..Default::default()
            })
            .await?;
        fm.disk_info = Some(info);
    }

    Ok(fm)
}

async fn write_format_file_all(disks: &[Option<DiskStore>], formats: &[Option<FormatV3>]) -> disk::error::Result<()> {
    let futures = disks.iter().zip(formats).map(|(disk, format)| async move {
        let disk = disk.as_ref().ok_or(DiskError::DiskNotFound)?;
        let format = format.as_ref().ok_or_else(|| DiskError::other("format is none"))?;
        write_format_file(disk, format).await
    });
    let mut errors = Vec::with_capacity(disks.len());

    let results = join_all(futures).await;
    for result in results {
        match result {
            Ok(_) => {
                errors.push(None);
            }
            Err(e) => {
                errors.push(Some(e));
            }
        }
    }

    if let Some(e) = reduce_write_quorum_errs(&errors, &[], disks.len()) {
        return Err(e);
    }

    Ok(())
}

pub async fn save_format_file(disk: &Option<DiskStore>, format: &Option<FormatV3>) -> disk::error::Result<()> {
    let Some(disk) = disk else {
        return Err(DiskError::DiskNotFound);
    };

    let Some(format) = format else {
        return Err(DiskError::other("format is none"));
    };

    write_format_file(disk, format).await?;
    disk.set_disk_id(Some(format.erasure.this)).await?;

    Ok(())
}

async fn write_format_file(disk: &DiskStore, format: &FormatV3) -> disk::error::Result<()> {
    let json_data = format.to_json()?;

    let tmpfile = Uuid::new_v4().to_string();

    disk.write_all(RUSTFS_META_BUCKET, tmpfile.as_str(), json_data.into_bytes().into())
        .await?;

    disk.rename_file(RUSTFS_META_BUCKET, tmpfile.as_str(), RUSTFS_META_BUCKET, FORMAT_CONFIG_FILE)
        .await?;

    Ok(())
}

pub fn ec_drives_no_config(set_drive_count: usize) -> Result<usize> {
    let parity = storageclass::default_parity_count(set_drive_count);
    storageclass::validate_parity(parity, set_drive_count)?;
    Ok(parity)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::endpoint::Endpoint;
    use crate::runtime::global::{current_ctx, reset_local_disk_test_state};
    use crate::runtime::sources::{local_disk_path_by_id, record_local_disks};
    use crate::store::peer::{find_local_disk_by_ref, prewarm_local_disk_id_map_with_instance_ctx};
    use serial_test::serial;

    async fn local_disks(count: usize) -> (tempfile::TempDir, Vec<Option<DiskStore>>) {
        local_disks_with_set_width(count, count).await
    }

    async fn local_disks_with_set_width(count: usize, set_width: usize) -> (tempfile::TempDir, Vec<Option<DiskStore>>) {
        let temp_dir = tempfile::tempdir().expect("temporary disk root should be created");
        let mut endpoints = Vec::with_capacity(count);
        for disk_index in 0..count {
            let path = temp_dir.path().join(format!("disk-{disk_index}"));
            tokio::fs::create_dir_all(&path)
                .await
                .expect("temporary disk path should be created");
            let mut endpoint =
                Endpoint::try_from(path.to_str().expect("temporary disk path should be UTF-8")).expect("endpoint should parse");
            endpoint.set_pool_index(0);
            endpoint.set_set_index(disk_index / set_width);
            endpoint.set_disk_index(disk_index % set_width);
            endpoints.push(endpoint);
        }

        let (disks, errors) = init_disks(
            &Endpoints::from(endpoints),
            &DiskOption {
                cleanup: false,
                health_check: false,
            },
        )
        .await;
        assert!(errors.iter().all(Option::is_none), "local disk initialization failed: {errors:?}");

        (temp_dir, disks)
    }

    async fn two_local_disks_with_missing_third() -> (tempfile::TempDir, Vec<Option<DiskStore>>) {
        let (temp_dir, mut disks) = local_disks(2).await;
        disks.push(None);

        (temp_dir, disks)
    }

    async fn format_bytes(disks: &[Option<DiskStore>]) -> Vec<Option<Vec<u8>>> {
        let mut snapshots = Vec::with_capacity(disks.len());
        for disk in disks {
            let disk = disk.as_ref().expect("snapshot disk should exist");
            // Inspect bytes even when the disk wrapper rejects a format whose
            // stored slot differs from the attempted new endpoint geometry.
            match tokio::fs::read(disk.path().join(RUSTFS_META_BUCKET).join(FORMAT_CONFIG_FILE)).await {
                Ok(data) => snapshots.push(Some(data)),
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => snapshots.push(None),
                Err(err) => panic!("format snapshot failed: {err}"),
            }
        }
        snapshots
    }

    async fn write_legacy_format(disk: &Option<DiskStore>, format: &FormatV3) {
        write_legacy_bytes(disk, bytes::Bytes::from(format.to_json().expect("legacy format should serialize"))).await;
    }

    async fn write_legacy_majority(disks: &[Option<DiskStore>], format: &FormatV3) {
        for (index, disk) in disks.iter().enumerate().take(disks.len() / 2 + 1) {
            let mut disk_format = format.clone();
            disk_format.erasure.this = format.erasure.sets[0][index];
            write_legacy_format(disk, &disk_format).await;
        }
    }

    async fn write_legacy_bytes(disk: &Option<DiskStore>, data: bytes::Bytes) {
        let disk = disk.as_ref().expect("legacy disk should exist");
        if let Err(err) = disk.make_volume(MIGRATING_META_BUCKET).await {
            assert_eq!(err, DiskError::VolumeExists, "legacy metadata volume should be created");
        }
        disk.write_all(MIGRATING_META_BUCKET, FORMAT_CONFIG_FILE, data)
            .await
            .expect("legacy format should be written");
    }

    async fn write_rustfs_bytes(disk: &Option<DiskStore>, data: bytes::Bytes) {
        let disk = disk.as_ref().expect("RustFS disk should exist");
        if let Err(err) = disk.make_volume(RUSTFS_META_BUCKET).await {
            assert_eq!(err, DiskError::VolumeExists, "RustFS metadata volume should be created");
        }
        disk.write_all(RUSTFS_META_BUCKET, FORMAT_CONFIG_FILE, data)
            .await
            .expect("RustFS format should be written");
    }

    #[tokio::test]
    async fn legacy_format_reader_rejects_oversized_input() {
        let max_bytes = 32;
        let accepted = read_legacy_format_bytes(std::io::Cursor::new(vec![0; max_bytes]), max_bytes)
            .await
            .expect("input at the limit should be accepted");
        assert_eq!(accepted.len(), max_bytes);

        let err = read_legacy_format_bytes(std::io::Cursor::new(vec![0; max_bytes + 1]), max_bytes)
            .await
            .expect_err("input above the limit must be rejected before parsing");
        assert_eq!(err, DiskError::CorruptedFormat);
    }

    #[tokio::test]
    async fn oversized_legacy_format_fails_closed_without_rustfs_writes() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        let oversized_len = legacy_format_max_bytes(disks.len()).expect("size limit should resolve") + 1;
        for (index, disk) in disks.iter().enumerate().take(2) {
            let mut disk_format = legacy.clone();
            disk_format.erasure.this = legacy.erasure.sets[0][index];
            let mut data = disk_format.to_json().expect("legacy format should serialize").into_bytes();
            data.resize(oversized_len, b' ');
            write_legacy_bytes(disk, data.into()).await;
        }

        let error = connect_load_init_formats(true, &mut disks, 1, 3, None)
            .await
            .expect_err("oversized legacy metadata must be rejected");
        assert!(matches!(error, Error::CorruptedFormat), "unexpected error: {error:?}");
        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "oversized legacy metadata must not be migrated");
        assert!(
            errors.iter().all(|error| matches!(error, Some(DiskError::UnformattedDisk))),
            "oversized legacy metadata must not create RustFS format files: {errors:?}"
        );
    }

    #[test]
    fn ec_drives_no_config_uses_topology_defaults() {
        assert_eq!(ec_drives_no_config(1).expect("single-drive topology should resolve"), 0);
        assert_eq!(ec_drives_no_config(2).expect("two-drive topology should resolve"), 1);
        assert_eq!(ec_drives_no_config(6).expect("six-drive topology should resolve"), 3);
    }

    #[test]
    fn format_quorum_rejects_duplicate_sentinel_and_ragged_layouts() {
        let mut duplicate = FormatV3::new(1, 3);
        duplicate.erasure.sets[0][1] = duplicate.erasure.sets[0][0];

        let mut nil = FormatV3::new(1, 3);
        nil.erasure.sets[0][2] = Uuid::nil();

        let mut max = FormatV3::new(1, 3);
        max.erasure.sets[0][2] = Uuid::max();

        let mut ragged = FormatV3::new(2, 2);
        ragged.erasure.sets[1].pop();

        for (name, format, total_slots, voting_slots) in [
            ("duplicate", duplicate, 3, vec![0, 1]),
            ("nil", nil, 3, vec![0, 1]),
            ("max", max, 3, vec![0, 1]),
            ("ragged", ragged, 4, vec![0, 1, 2]),
        ] {
            let set_drive_count = format.erasure.sets[0].len();
            let mut formats = vec![None; total_slots];
            for index in voting_slots {
                let mut vote = format.clone();
                vote.erasure.this = format.erasure.sets[index / set_drive_count][index % set_drive_count];
                formats[index] = Some(vote);
            }

            assert!(
                matches!(get_format_erasure_in_quorum(&formats, 0), Err(Error::ErasureReadQuorum)),
                "{name} layout must not form a format quorum"
            );
            assert!(
                check_format_erasure_values(&formats, set_drive_count).is_err(),
                "{name} layout must fail startup format validation"
            );
        }
    }

    #[test]
    fn format_quorum_rejects_unknown_backend_and_invalid_deployment_ids() {
        let mut unknown_backend = FormatV3::new(1, 3);
        unknown_backend.format = FormatBackend::Unknown;

        let mut nil_deployment = FormatV3::new(1, 3);
        nil_deployment.id = Uuid::nil();

        let mut max_deployment = FormatV3::new(1, 3);
        max_deployment.id = Uuid::max();

        for (name, format) in [
            ("unknown backend", unknown_backend),
            ("nil deployment ID", nil_deployment),
            ("max deployment ID", max_deployment),
        ] {
            let mut formats = vec![None; 3];
            for (index, slot) in formats.iter_mut().take(2).enumerate() {
                let mut vote = format.clone();
                vote.erasure.this = format.erasure.sets[0][index];
                *slot = Some(vote);
            }

            assert!(
                matches!(get_format_erasure_in_quorum(&formats, 0), Err(Error::ErasureReadQuorum)),
                "{name} must not form a format quorum"
            );
        }
    }

    #[test]
    fn reference_slot_validation_rejects_wrong_slot_and_foreign_minorities() {
        let reference = FormatV3::new(1, 3);
        let mut formats = (0..3)
            .map(|index| {
                let mut format = reference.clone();
                format.erasure.this = reference.erasure.sets[0][index];
                Some(format)
            })
            .collect::<Vec<_>>();
        assert!(formats_match_reference_slots(&formats, &reference, 0));

        formats[2].as_mut().expect("third format should exist").erasure.this = reference.erasure.sets[0][0];
        assert!(!formats_match_reference_slots(&formats, &reference, 0));

        formats[2] = {
            let mut foreign = reference.clone();
            foreign.id = Uuid::new_v4();
            foreign.erasure.this = foreign.erasure.sets[0][2];
            Some(foreign)
        };
        assert!(!formats_match_reference_slots(&formats, &reference, 0));
    }

    #[tokio::test]
    async fn existing_format_load_succeeds_with_a_strict_majority() {
        let (_temp_dir, mut disks) = two_local_disks_with_missing_third().await;
        let mut format = FormatV3::new(1, 3);
        let mut expected = format.clone();
        expected.erasure.this = Uuid::nil();

        format.erasure.this = format.erasure.sets[0][0];
        save_format_file(&disks[0], &Some(format.clone()))
            .await
            .expect("existing format should be written to the first disk");
        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::ErasureReadQuorum)
        ));
        assert!(matches!(
            load_format_erasure(disks[1].as_ref().expect("second disk should exist"), false).await,
            Err(DiskError::UnformattedDisk)
        ));

        format.erasure.this = format.erasure.sets[0][1];
        save_format_file(&disks[1], &Some(format))
            .await
            .expect("existing format should be written to the second disk");

        assert_eq!(
            connect_load_init_formats(true, &mut disks, 1, 3, None)
                .await
                .expect("two existing formats should satisfy the production load path"),
            expected
        );
    }

    #[tokio::test]
    async fn single_drive_format_rejects_in_place_expansion_without_writes() {
        for configured_drives in [2, 4] {
            for first_disk in [false, true] {
                let (_temp_dir, mut disks) = local_disks(configured_drives).await;
                let mut original = FormatV3::new(1, 1);
                original.erasure.this = original.erasure.sets[0][0];
                save_format_file(&disks[0], &Some(original))
                    .await
                    .expect("SNSD format should be written");
                let before = format_bytes(&disks).await;

                let err = connect_load_init_formats(first_disk, &mut disks, 1, configured_drives, None)
                    .await
                    .expect_err("an existing SNSD deployment cannot expand in place");
                let message = err.to_string();
                assert!(message.contains("SNSD"), "expected a single-drive expansion error: {message}");
                assert!(message.contains("migrate data through S3"), "expected actionable guidance: {message}");
                assert_eq!(format_bytes(&disks).await, before, "neither old nor new formats may be written");
            }
        }
    }

    #[tokio::test]
    async fn existing_pool_rejects_drive_count_or_set_width_changes_without_writes() {
        for (stored_sets, stored_width, configured_sets, configured_width) in
            [(1, 4, 1, 6), (1, 4, 1, 8), (1, 4, 1, 2), (1, 4, 2, 2), (2, 2, 1, 4)]
        {
            for first_disk in [false, true] {
                let (_temp_dir, mut disks) =
                    local_disks_with_set_width(configured_sets * configured_width, configured_width).await;
                let original = FormatV3::new(stored_sets, stored_width);
                for (disk, disk_id) in disks.iter().zip(original.erasure.sets.iter().flatten()) {
                    let mut format = original.clone();
                    format.erasure.this = *disk_id;
                    save_format_file(disk, &Some(format))
                        .await
                        .expect("existing format should be written");
                }
                let before = format_bytes(&disks).await;

                let err = connect_load_init_formats(first_disk, &mut disks, configured_sets, configured_width, None)
                    .await
                    .expect_err("an existing pool's geometry is immutable");
                let message = err.to_string();
                assert!(message.contains("pool topology mismatch"), "expected a topology error: {message}");
                assert!(
                    message.contains(&format!("stored 4 drives with {stored_width} drives per erasure set")),
                    "expected stored geometry: {message}"
                );
                assert!(message.contains("append a new pool"), "expected expansion guidance: {message}");
                assert_eq!(format_bytes(&disks).await, before, "rejection must not rewrite any format");
            }
        }
    }

    #[tokio::test]
    async fn subquorum_existing_layout_with_missing_drives_is_not_expansion() {
        let (_temp_dir, mut disks) = local_disks(1).await;
        let mut original = FormatV3::new(1, 4);
        original.erasure.this = original.erasure.sets[0][0];
        save_format_file(&disks[0], &Some(original))
            .await
            .expect("existing format should be written");
        disks.extend([None, None, None]);

        for first_disk in [false, true] {
            assert!(matches!(
                connect_load_init_formats(first_disk, &mut disks, 1, 4, None).await,
                Err(Error::ErasureReadQuorum)
            ));
        }
    }

    #[tokio::test]
    async fn conflicting_layouts_without_quorum_are_not_expansion_proof() {
        let (_temp_dir, mut disks) = local_disks(2).await;
        for (index, (disk, width)) in disks.iter().zip([4, 2]).enumerate() {
            let mut format = FormatV3::new(1, width);
            format.erasure.this = format.erasure.sets[0][index];
            save_format_file(disk, &Some(format))
                .await
                .expect("existing format should be written");
        }
        disks.extend([None, None]);

        let result = connect_load_init_formats(true, &mut disks, 1, 4, None).await;
        assert!(matches!(result, Err(Error::ErasureReadQuorum)), "conflicting layout result: {result:?}");
    }

    #[tokio::test]
    async fn existing_format_quorum_ignores_single_drive_outlier() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        for (index, disk) in disks.iter().enumerate() {
            // Slot zero lets the SNSD outlier pass the disk wrapper's own
            // slot check, so quorum selection must exclude the parsed format.
            let mut format = if index == 0 { FormatV3::new(1, 1) } else { majority.clone() };
            format.erasure.this = format.erasure.sets[0][index];
            save_format_file(disk, &Some(format))
                .await
                .expect("existing format should be written");
        }

        let loaded = connect_load_init_formats(true, &mut disks, 1, 3, None)
            .await
            .expect("a foreign SNSD outlier must not block a healthy majority");
        assert_eq!(loaded.shared_identity(), majority.shared_identity());
        assert!(disks[0].is_none(), "the foreign single-drive format must be quarantined");
    }

    #[tokio::test]
    async fn multi_drive_pool_expansion_preserves_existing_format() {
        let (_original_dir, mut disks) = local_disks(4).await;
        let (_new_dir, mut new_disks) = local_disks(4).await;
        let original = connect_load_init_formats(true, &mut disks, 1, 4, None)
            .await
            .expect("original multi-drive pool should initialize");
        let before = format_bytes(&disks).await;

        let added = connect_load_init_formats(true, &mut new_disks, 1, 4, Some(original.id))
            .await
            .expect("a new multi-drive pool should initialize with the existing deployment ID");
        assert_eq!(added.id, original.id);
        assert_ne!(added.erasure.sets, original.erasure.sets);
        assert_eq!(format_bytes(&disks).await, before);
        assert_eq!(
            connect_load_init_formats(true, &mut disks, 1, 4, Some(original.id))
                .await
                .expect("the original pool should restart with unchanged geometry"),
            original
        );
        assert_eq!(
            connect_load_init_formats(true, &mut new_disks, 1, 4, Some(original.id))
                .await
                .expect("the new pool should restart with its own format"),
            added
        );
    }

    #[tokio::test]
    async fn store_startup_rejects_pool_resize_before_retry_loop() {
        use crate::layout::endpoints::{EndpointServerPools, PoolEndpoints};
        use tokio_util::sync::CancellationToken;

        for (stored_width, configured_width) in [(1, 4), (4, 8)] {
            let (_temp_dir, disks) = local_disks(configured_width).await;
            let original = FormatV3::new(1, stored_width);
            for (disk, disk_id) in disks.iter().zip(&original.erasure.sets[0]) {
                let mut format = original.clone();
                format.erasure.this = *disk_id;
                save_format_file(disk, &Some(format))
                    .await
                    .expect("old format should be written");
            }
            let before = format_bytes(&disks).await;
            let endpoints = disks.iter().flatten().map(|disk| disk.endpoint()).collect::<Vec<_>>();
            let pools = EndpointServerPools::from(vec![PoolEndpoints {
                legacy: true,
                set_count: 1,
                drives_per_set: configured_width,
                endpoints: Endpoints::from(endpoints),
                cmd_line: "test-pool".to_string(),
                platform: String::new(),
            }]);
            let shutdown = CancellationToken::new();
            let result = temp_env::async_with_vars(
                [
                    (storageclass::STANDARD_ENV, None::<&str>),
                    (storageclass::RRS_ENV, None::<&str>),
                    (storageclass::OPTIMIZE_ENV, None::<&str>),
                    (storageclass::INLINE_BLOCK_ENV, None::<&str>),
                ],
                tokio::time::timeout(
                    std::time::Duration::from_secs(5),
                    crate::store::ECStore::new_with_instance_ctx(
                        "127.0.0.1:0".parse().expect("test address"),
                        pools,
                        shutdown.clone(),
                        Arc::new(InstanceContext::new()),
                    ),
                ),
            )
            .await;
            shutdown.cancel();
            let err = result
                .expect("invalid topology must abort without the format retry backoff")
                .expect_err("resize must fail");
            match stored_width {
                1 => assert!(matches!(err, Error::UnsupportedSnsdExpansion { configured_drives: 4 }), "{err}"),
                _ => assert!(
                    matches!(
                        err,
                        Error::PoolTopologyMismatch {
                            stored_drives: 4,
                            configured_drives: 8,
                            ..
                        }
                    ),
                    "{err}"
                ),
            }
            assert_eq!(format_bytes(&disks).await, before, "failed store startup must not write formats");
        }
    }

    #[tokio::test]
    async fn existing_format_load_rejects_conflicting_formats_without_a_majority() {
        let (_temp_dir, mut disks) = two_local_disks_with_missing_third().await;
        let mut first = FormatV3::new(1, 3);
        first.erasure.this = first.erasure.sets[0][0];
        save_format_file(&disks[0], &Some(first))
            .await
            .expect("first existing format should be written");

        let mut second = FormatV3::new(1, 3);
        second.erasure.this = second.erasure.sets[0][1];
        save_format_file(&disks[1], &Some(second))
            .await
            .expect("conflicting existing format should be written");

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::ErasureReadQuorum)
        ));
    }

    #[tokio::test]
    async fn existing_format_load_excludes_disks_outside_the_selected_quorum() {
        for wrong_slot_id in [false, true] {
            let (_temp_dir, mut disks) = local_disks(3).await;
            let mut majority = FormatV3::new(1, 3);
            let mut expected = majority.clone();
            expected.erasure.this = Uuid::nil();

            for (index, disk) in disks.iter().take(2).enumerate() {
                majority.erasure.this = majority.erasure.sets[0][index];
                save_format_file(disk, &Some(majority.clone()))
                    .await
                    .expect("majority format should be written");
            }

            let mut outlier = if wrong_slot_id {
                majority.clone()
            } else {
                FormatV3::new(1, 3)
            };
            outlier.erasure.this = if wrong_slot_id {
                outlier.erasure.sets[0][0]
            } else {
                outlier.erasure.sets[0][2]
            };
            save_format_file(&disks[2], &Some(outlier))
                .await
                .expect("outlier format should be written");

            assert_eq!(
                connect_load_init_formats(true, &mut disks, 1, 3, None)
                    .await
                    .expect("two valid members should select the majority format"),
                expected
            );
            assert!(disks[0].is_some() && disks[1].is_some());
            assert!(disks[2].is_none(), "the outlier disk must not enter the selected erasure set");
        }
    }

    #[tokio::test]
    #[serial]
    async fn existing_format_load_publishes_only_validated_quorum_disk_ids() {
        reset_local_disk_test_state().await;
        let (_temp_dir, mut disks) = local_disks(5).await;
        let canonical = FormatV3::new(1, 5);
        for (index, disk) in disks.iter().enumerate().take(3) {
            let mut disk_format = canonical.clone();
            disk_format.erasure.this = canonical.erasure.sets[0][index];
            save_format_file(disk, &Some(disk_format))
                .await
                .expect("canonical format should be written");
        }
        let canonical_id = canonical.erasure.sets[0][0];
        let mut foreign = FormatV3::new(1, 5);
        foreign.erasure.this = foreign.erasure.sets[0][4];
        let foreign_id = foreign.erasure.this;
        save_format_file(&disks[4], &Some(foreign))
            .await
            .expect("foreign format should be written");
        let mut collision = FormatV3::new(1, 5);
        collision.erasure.sets[0][3] = canonical_id;
        collision.erasure.this = canonical_id;
        save_format_file(&disks[3], &Some(collision))
            .await
            .expect("foreign collision format should be written");
        let canonical_endpoint = disks[0].as_ref().expect("canonical disk should exist").endpoint().to_string();
        let collision_endpoint = disks[3].as_ref().expect("collision disk should exist").endpoint().to_string();
        let foreign_endpoint = disks[4].as_ref().expect("foreign disk should exist").endpoint().to_string();
        let prewarm_endpoints = Endpoints::from(
            disks
                .iter()
                .map(|disk| disk.as_ref().expect("test disk should exist").endpoint())
                .collect::<Vec<_>>(),
        );
        for disk in disks.iter().flatten() {
            disk.set_disk_id(None).await.expect("test disk ID should be reset");
        }
        let (prewarm_disks, prewarm_errors) = init_disks(
            &prewarm_endpoints,
            &DiskOption {
                cleanup: false,
                health_check: false,
            },
        )
        .await;
        assert!(prewarm_errors.iter().all(Option::is_none));
        let prewarm_disks = prewarm_disks
            .into_iter()
            .map(|disk| disk.expect("prewarm disk should exist"))
            .collect::<Vec<_>>();
        let instance_ctx = current_ctx();
        record_local_disks(&instance_ctx, prewarm_disks.clone()).await;
        *instance_ctx.local_disk_set_drives().write().await = vec![vec![prewarm_disks.into_iter().map(Some).collect()]];
        prewarm_local_disk_id_map_with_instance_ctx(&instance_ctx).await;
        instance_ctx
            .local_disk_id_map()
            .write()
            .await
            .insert(canonical_id, collision_endpoint.clone());
        assert!(local_disk_path_by_id(&foreign_id).await.is_some(), "foreign ID should be prewarmed");
        assert_eq!(local_disk_path_by_id(&canonical_id).await, Some(collision_endpoint));
        disks[4] = None;

        connect_load_init_formats(true, &mut disks, 1, 5, None)
            .await
            .expect("the canonical strict majority should load");

        assert!(disks[..3].iter().all(Option::is_some));
        assert!(disks[3..].iter().all(Option::is_none));
        assert_eq!(local_disk_path_by_id(&canonical_id).await, Some(canonical_endpoint.clone()));
        assert_eq!(local_disk_path_by_id(&foreign_id).await, None);
        assert!(
            instance_ctx
                .local_disk_map()
                .read()
                .await
                .get(&foreign_endpoint)
                .is_some_and(Option::is_none)
        );
        assert!(instance_ctx.local_disk_set_drives().read().await[0][0][4].is_none());
        assert!(find_local_disk_by_ref(&foreign_id.to_string()).await.is_none());
        assert_eq!(
            find_local_disk_by_ref(&canonical_id.to_string())
                .await
                .map(|disk| disk.endpoint().to_string()),
            Some(canonical_endpoint)
        );
        reset_local_disk_test_state().await;
    }

    #[test]
    fn persisted_migration_quorum_ignores_nonmember_read_errors() {
        for drive_count in [3, 4] {
            let reference = FormatV3::new(1, drive_count);
            let required = drive_count / 2 + 1;
            let mut formats = vec![None; drive_count];
            let mut errors = (0..drive_count).map(|_| None).collect::<Vec<Option<DiskError>>>();
            for (index, format) in formats.iter_mut().enumerate().take(required) {
                let mut disk_format = reference.clone();
                disk_format.erasure.this = reference.erasure.sets[0][index];
                *format = Some(disk_format);
            }
            errors[drive_count - 1] = Some(DiskError::FaultyDisk);

            let (selected, members) =
                select_persisted_migration_format(&formats, errors, &reference, drive_count, Some(DiskError::FaultyDisk))
                    .expect("a persisted strict majority must outrank a nonmember read error")
                    .expect("the persisted formats should be compatible");

            assert_eq!(selected.shared_identity(), reference.shared_identity());
            assert_eq!(members.iter().filter(|member| **member).count(), required);
            assert!(members[..required].iter().all(|member| *member));
            assert!(members[required..].iter().all(|member| !*member));
        }
    }

    #[tokio::test]
    async fn existing_format_load_excludes_a_malformed_outlier() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let mut majority = FormatV3::new(1, 3);
        let mut expected = majority.clone();
        expected.erasure.this = Uuid::nil();

        for (index, disk) in disks.iter().take(2).enumerate() {
            majority.erasure.this = majority.erasure.sets[0][index];
            save_format_file(disk, &Some(majority.clone()))
                .await
                .expect("majority format should be written");
        }
        let mut malformed = majority;
        malformed.erasure.sets[0][1] = malformed.erasure.sets[0][0];
        malformed.erasure.this = malformed.erasure.sets[0][2];
        save_format_file(&disks[2], &Some(malformed))
            .await
            .expect("malformed outlier should be written");

        assert_eq!(
            connect_load_init_formats(true, &mut disks, 1, 3, None)
                .await
                .expect("one malformed outlier must not block a valid strict majority"),
            expected
        );
        assert!(disks[0].is_some() && disks[1].is_some());
        assert!(disks[2].is_none(), "the malformed outlier must be isolated");
    }

    #[tokio::test]
    async fn fresh_format_load_initializes_all_disks() {
        let (_temp_dir, mut disks) = local_disks(3).await;

        let loaded = connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 3, None)
            .await
            .expect("fresh disks should receive a storage format");
        assert_eq!(loaded.pool_meta_bootstrap_authority, PoolMetaBootstrapAuthority::Fresh);
        let format = loaded.format;

        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(errors.iter().all(Option::is_none), "every disk should load its fresh format: {errors:?}");
        assert!(
            formats_match_reference_slots(&formats, &format, 0),
            "fresh format publication must preserve every disk slot"
        );
    }

    #[tokio::test]
    async fn fresh_format_load_does_not_initialize_with_a_missing_disk() {
        let (_temp_dir, mut disks) = two_local_disks_with_missing_third().await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::FirstDiskWait)
        ));
        assert!(matches!(
            connect_load_init_formats(false, &mut disks, 1, 3, None).await,
            Err(Error::NotFirstDisk)
        ));

        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none));
        assert!(matches!(
            errors.as_slice(),
            [
                Some(DiskError::UnformattedDisk),
                Some(DiskError::UnformattedDisk),
                Some(DiskError::DiskNotFound)
            ]
        ));
    }

    #[tokio::test]
    async fn compatible_legacy_format_migrates() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;

        let mut expected = legacy;
        expected.erasure.this = Uuid::nil();
        let loaded = connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 3, None)
            .await
            .expect("compatible legacy format should migrate");
        assert_eq!(loaded.format, expected);
        assert_eq!(loaded.pool_meta_bootstrap_authority, PoolMetaBootstrapAuthority::LegacyAdoption);
        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(
            errors.iter().all(Option::is_none),
            "every available disk should receive the migrated format"
        );
        for (index, format) in formats.iter().enumerate() {
            assert_eq!(
                format.as_ref().map(|format| format.erasure.this),
                Some(expected.erasure.sets[0][index]),
                "the migrated format must preserve each disk's physical slot"
            );
        }
    }

    #[tokio::test]
    async fn compatible_single_drive_legacy_format_marks_adoption_proof() {
        let (_temp_dir, mut disks) = local_disks(1).await;
        let legacy = FormatV3::new(1, 1);
        write_legacy_majority(&disks, &legacy).await;

        let loaded = connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 1, None)
            .await
            .expect("single-drive MinIO format should migrate");

        assert_eq!(loaded.pool_meta_bootstrap_authority, PoolMetaBootstrapAuthority::LegacyAdoption);
    }

    #[tokio::test]
    async fn existing_migrated_format_keeps_legacy_adoption_proof() {
        let (_temp_dir, mut disks) = local_disks(1).await;
        let legacy = FormatV3::new(1, 1);
        write_legacy_majority(&disks, &legacy).await;

        connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 1, None)
            .await
            .expect("first run should migrate the MinIO format");
        let loaded = connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 1, None)
            .await
            .expect("retry after a partial adoption should reload the migrated RustFS format");

        assert_eq!(loaded.pool_meta_bootstrap_authority, PoolMetaBootstrapAuthority::LegacyAdoption);
    }

    #[tokio::test]
    async fn existing_rustfs_format_without_legacy_source_is_not_legacy_adoption() {
        let (_temp_dir, mut disks) = local_disks(1).await;
        let mut format = FormatV3::new(1, 1);
        format.erasure.this = format.erasure.sets[0][0];
        save_format_file(&disks[0], &Some(format))
            .await
            .expect("existing RustFS format should be written");

        let loaded = connect_load_init_formats_with_instance_ctx(&current_ctx(), true, &mut disks, 1, 1, None)
            .await
            .expect("existing RustFS format should load");

        assert_eq!(loaded.pool_meta_bootstrap_authority, PoolMetaBootstrapAuthority::None);
    }

    #[tokio::test]
    async fn compatible_legacy_format_migrates_when_the_file_is_missing() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;
        disks[2]
            .as_ref()
            .expect("third legacy disk should exist")
            .make_volume(MIGRATING_META_BUCKET)
            .await
            .expect("legacy metadata volume should be created without a format file");

        connect_load_init_formats(true, &mut disks, 1, 3, None)
            .await
            .expect("a missing legacy format file should be initialized from the majority");
        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(
            errors.iter().all(Option::is_none),
            "every available disk should receive the migrated format"
        );
        assert_eq!(
            formats[2].as_ref().map(|format| format.erasure.this),
            Some(legacy.erasure.sets[0][2]),
            "the missing legacy format file must be replaced with the third slot"
        );
    }

    #[tokio::test]
    async fn legacy_format_migration_resumes_partial_rustfs_writes() {
        for drive_count in [3, 4] {
            let (_temp_dir, mut disks) = local_disks(drive_count).await;
            let legacy = FormatV3::new(1, drive_count);
            write_legacy_majority(&disks, &legacy).await;
            for (index, disk) in disks.iter().enumerate().take(drive_count / 2) {
                let mut disk_format = legacy.clone();
                disk_format.erasure.this = legacy.erasure.sets[0][index];
                save_format_file(disk, &Some(disk_format))
                    .await
                    .expect("partial RustFS format should be written");
            }

            let mut expected = legacy;
            expected.erasure.this = Uuid::nil();
            assert_eq!(
                connect_load_init_formats(true, &mut disks, 1, drive_count, None)
                    .await
                    .expect("a partial migration should resume from the legacy quorum"),
                expected
            );
            let (formats, errors) = load_format_erasure_all(&disks, false).await;
            assert!(errors.iter().all(Option::is_none), "the resumed migration should format every disk");
            for (index, format) in formats.iter().enumerate() {
                assert_eq!(
                    format.as_ref().map(|format| format.erasure.this),
                    Some(expected.erasure.sets[0][index]),
                    "the resumed migration must preserve each physical slot"
                );
            }
        }
    }

    #[tokio::test]
    async fn legacy_format_migration_resumes_to_quorum_with_an_unavailable_disk() {
        let (_temp_dir, mut disks) = two_local_disks_with_missing_third().await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;
        let mut partial = legacy.clone();
        partial.erasure.this = partial.erasure.sets[0][0];
        save_format_file(&disks[0], &Some(partial))
            .await
            .expect("partial RustFS format should be written");

        let mut expected = legacy;
        expected.erasure.this = Uuid::nil();
        assert_eq!(
            connect_load_init_formats(true, &mut disks, 1, 3, None)
                .await
                .expect("the available blank disk should complete the migration quorum"),
            expected
        );
        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(formats[0].is_some() && formats[1].is_some());
        assert!(formats[2].is_none());
        assert!(matches!(errors[2], Some(DiskError::DiskNotFound)));
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_foreign_partial_rustfs_format() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;
        let mut foreign = FormatV3::new(1, 3);
        foreign.erasure.this = foreign.erasure.sets[0][0];
        let foreign_id = foreign.id;
        save_format_file(&disks[0], &Some(foreign))
            .await
            .expect("foreign partial RustFS format should be written");

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert_eq!(formats[0].as_ref().map(|format| format.id), Some(foreign_id));
        assert!(formats[1..].iter().all(Option::is_none), "foreign partial state must not be extended");
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_wrong_slot_partial_rustfs_format() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;
        let mut wrong_slot = legacy;
        wrong_slot.erasure.this = wrong_slot.erasure.sets[0][1];
        save_format_file(&disks[0], &Some(wrong_slot))
            .await
            .expect("wrong-slot partial RustFS format should be written");

        let error = connect_load_init_formats(true, &mut disks, 1, 3, None)
            .await
            .expect_err("a wrong-slot partial RustFS format must be rejected");
        assert!(matches!(error, Error::CorruptedFormat), "unexpected error: {error:?}");
        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(matches!(errors[0], Some(DiskError::InconsistentDisk)));
        assert!(formats[1..].iter().all(Option::is_none), "wrong-slot partial state must not be extended");
    }

    #[tokio::test]
    async fn legacy_format_migration_does_not_extend_a_malformed_rustfs_format() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let legacy = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &legacy).await;
        write_rustfs_bytes(&disks[0], bytes::Bytes::from_static(b"{not-json")).await;

        assert!(connect_load_init_formats(true, &mut disks, 1, 3, None).await.is_err());
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "malformed partial state must not be extended");
    }

    #[tokio::test]
    async fn incompatible_legacy_format_fails_closed() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let mut legacy = FormatV3::new(1, 3);
        legacy.id = Uuid::nil();
        write_legacy_majority(&disks, &legacy).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));

        let (formats, errors) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "incompatible legacy metadata must not be replaced");
        assert!(
            errors.iter().all(|error| matches!(error, Some(DiskError::UnformattedDisk))),
            "fresh RustFS formats must not be written after a rejected migration: {errors:?}"
        );
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_foreign_minority() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &majority).await;
        let minority = FormatV3::new(1, 3);
        let mut minority_disk = minority;
        minority_disk.erasure.this = minority_disk.erasure.sets[0][2];
        write_legacy_format(&disks[2], &minority_disk).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "a foreign legacy minority must not be overwritten");
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_wrong_slot_minority() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &majority).await;
        let mut wrong_slot = majority;
        wrong_slot.erasure.this = wrong_slot.erasure.sets[0][1];
        write_legacy_format(&disks[2], &wrong_slot).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(
            formats.iter().all(Option::is_none),
            "a wrong-slot legacy minority must not be overwritten"
        );
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_malformed_minority() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &majority).await;
        write_legacy_bytes(&disks[2], bytes::Bytes::from_static(b"{not-json")).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "a malformed legacy minority must not be overwritten");
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_an_empty_minority() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &majority).await;
        write_legacy_bytes(&disks[2], bytes::Bytes::new()).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "an empty legacy minority must not be overwritten");
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_a_parseable_invalid_minority() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        let majority = FormatV3::new(1, 3);
        write_legacy_majority(&disks, &majority).await;
        let mut invalid = majority;
        invalid.id = Uuid::nil();
        invalid.erasure.this = invalid.erasure.sets[0][2];
        write_legacy_format(&disks[2], &invalid).await;

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(
            formats.iter().all(Option::is_none),
            "a parseable invalid legacy minority must not be overwritten"
        );
    }

    #[tokio::test]
    async fn legacy_format_migration_rejects_conflicting_candidates_without_a_quorum() {
        let (_temp_dir, mut disks) = local_disks(3).await;
        for (index, disk) in disks.iter().enumerate().take(2) {
            let mut disk_format = FormatV3::new(1, 3);
            disk_format.erasure.this = disk_format.erasure.sets[0][index];
            write_legacy_format(disk, &disk_format).await;
        }

        assert!(matches!(
            connect_load_init_formats(true, &mut disks, 1, 3, None).await,
            Err(Error::CorruptedFormat)
        ));
        let (formats, _) = load_format_erasure_all(&disks, false).await;
        assert!(formats.iter().all(Option::is_none), "a legacy split vote must not write RustFS formats");
    }

    #[test]
    fn is_unformatted_or_transient_network_classifies_errors() {
        // UnformattedDisk is recognized.
        assert!(is_unformatted_or_transient_network(&Some(DiskError::UnformattedDisk)));
        // None (healthy disk) is not.
        assert!(!is_unformatted_or_transient_network(&None));
        // Transient network errors are recognized.
        assert!(is_unformatted_or_transient_network(&Some(DiskError::Io(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "connection refused"
        )))));
        assert!(is_unformatted_or_transient_network(&Some(DiskError::Timeout)));
        // Non-network errors are not.
        assert!(!is_unformatted_or_transient_network(&Some(DiskError::FileNotFound)));
        assert!(!is_unformatted_or_transient_network(&Some(DiskError::CorruptedFormat)));
        assert!(!is_unformatted_or_transient_network(&Some(DiskError::DiskFull)));
        assert!(should_init_erasure_disks(&[
            Some(DiskError::UnformattedDisk),
            Some(DiskError::UnformattedDisk),
        ]));
        assert!(
            !should_init_erasure_disks(&[Some(DiskError::UnformattedDisk), Some(DiskError::Timeout)]),
            "an unreachable peer is not fresh-topology proof"
        );
    }
}

// #[derive(Debug, PartialEq, thiserror::Error)]
// pub enum ErasureError {
//     #[error("erasure read quorum")]
//     ErasureReadQuorum,

//     #[error("erasure write quorum")]
//     _ErasureWriteQuorum,

//     #[error("not first disk")]
//     NotFirstDisk,

//     #[error("first disk wait")]
//     FirstDiskWait,

//     #[error("invalid part id {0}")]
//     InvalidPart(usize),
// }

// impl ErasureError {
//     pub fn is(&self, err: &Error) -> bool {
//         if let Some(e) = err.downcast_ref::<ErasureError>() {
//             return self == e;
//         }

//         false
//     }
// }

// impl ErasureError {
//     pub fn to_u32(&self) -> u32 {
//         match self {
//             ErasureError::ErasureReadQuorum => 0x01,
//             ErasureError::_ErasureWriteQuorum => 0x02,
//             ErasureError::NotFirstDisk => 0x03,
//             ErasureError::FirstDiskWait => 0x04,
//             ErasureError::InvalidPart(_) => 0x05,
//         }
//     }

//     pub fn from_u32(error: u32) -> Option<Self> {
//         match error {
//             0x01 => Some(ErasureError::ErasureReadQuorum),
//             0x02 => Some(ErasureError::_ErasureWriteQuorum),
//             0x03 => Some(ErasureError::NotFirstDisk),
//             0x04 => Some(ErasureError::FirstDiskWait),
//             0x05 => Some(ErasureError::InvalidPart(Default::default())),
//             _ => None,
//         }
//     }
// }