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
// 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_object_disk_read_timeout;
use crate::disk::error::{Error, Result};
use crate::erasure::coding::BitrotReader;
use crate::erasure::coding::BitrotWriterWrapper;
use crate::erasure::coding::encode::MultiWriter;
use bytes::Bytes;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use std::io;
use std::io::ErrorKind;
use std::time::Duration;
use tokio::io::AsyncRead;
use tracing::{trace, warn};

const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_ERASURE: &str = "erasure";
const EVENT_ERASURE_HEAL_STARTED: &str = "erasure_heal_started";

async fn read_heal_shards<R>(
    readers: &mut [Option<BitrotReader<R>>],
    shard_size: usize,
    read_timeout: Duration,
) -> (Vec<Option<Vec<u8>>>, Vec<Option<Error>>)
where
    R: AsyncRead + Unpin + Send + Sync,
{
    let num_readers = readers.len();
    let mut shards = vec![None; num_readers];
    let mut errs = vec![None; num_readers];
    let mut retire_readers = Vec::new();

    if shard_size == 0 {
        return (shards, errs);
    }

    {
        let mut futures = FuturesUnordered::new();
        for (index, reader) in readers.iter_mut().enumerate() {
            let Some(reader) = reader else {
                errs[index] = Some(Error::FileNotFound);
                continue;
            };

            futures.push(Box::pin(async move {
                let mut buf = vec![0; shard_size];
                let read_result = if read_timeout.is_zero() {
                    reader.read(&mut buf).await
                } else {
                    match tokio::time::timeout(read_timeout, reader.read(&mut buf)).await {
                        Ok(result) => result,
                        Err(_) => {
                            return (
                                index,
                                Err(Error::from(io::Error::new(ErrorKind::TimedOut, "heal shard read timed out"))),
                                true,
                            );
                        }
                    }
                };

                match read_result {
                    Ok(n) => {
                        buf.truncate(n);
                        (index, Ok(buf), false)
                    }
                    Err(err) => {
                        let should_retire = err.kind() == ErrorKind::TimedOut;
                        (index, Err(Error::from(err)), should_retire)
                    }
                }
            }));
        }

        while let Some((index, result, should_retire)) = futures.next().await {
            match result {
                Ok(shard) => {
                    shards[index] = Some(shard);
                }
                Err(err) => {
                    errs[index] = Some(err);
                    if should_retire {
                        retire_readers.push(index);
                    }
                }
            }
        }
    }

    for index in retire_readers {
        readers[index] = None;
        warn!(shard_index = index, "retiring timed-out heal shard reader");
    }

    (shards, errs)
}

fn heal_writer_failure(writers: &mut MultiWriter<'_>, error: io::Error) -> Error {
    writers
        .take_retryable_internode_write_failure()
        .map(|error| Error::RemoteClientUnavailable(error.to_string()))
        .unwrap_or_else(|| error.into())
}

impl super::Erasure {
    pub async fn heal<R>(
        &self,
        writers: &mut [Option<BitrotWriterWrapper>],
        readers: Vec<Option<BitrotReader<R>>>,
        total_length: usize,
        _prefer: &[bool],
    ) -> Result<()>
    where
        R: AsyncRead + Unpin + Send + Sync,
    {
        trace!(
            event = EVENT_ERASURE_HEAL_STARTED,
            component = LOG_COMPONENT_ECSTORE,
            subsystem = LOG_SUBSYSTEM_ERASURE,
            writer_count = writers.len(),
            reader_count = readers.len(),
            total_length,
            "Erasure heal started"
        );
        if writers.len() != self.parity_shards + self.data_shards {
            return Err(Error::other("invalid argument"));
        }
        let mut readers = readers;

        let start_block = 0;
        let mut end_block = total_length / self.block_size;
        if !total_length.is_multiple_of(self.block_size) {
            end_block += 1;
        }

        // Heal is best-effort per target disk. A single replacement disk failing to
        // write one block must not abort healing on the other healthy replacement
        // disks: requiring every target to succeed (write_quorum == available_writers)
        // let one flapping disk block redundancy recovery for the whole object and
        // kept the erasure set under-protected indefinitely. Upstream MinIO uses
        // writeQuorum == 1 for heal so partial progress commits; MultiWriter already
        // marks a failed writer as None (see encode.rs `write_shard`) and the ops
        // layer (set_disk/ops/heal.rs) then drops the failed writer while committing
        // the survivors. Reconstruction correctness is still guaranteed by the
        // read-side quorum check and parity cross-checks below, which are unaffected.
        let write_quorum = 1;
        let mut writers = MultiWriter::new(writers, write_quorum);
        let read_timeout = get_object_disk_read_timeout();
        let shard_file_size = self.shard_file_size(total_length as i64) as usize;

        for block_index in start_block..end_block {
            let shard_offset = block_index * self.shard_size();
            let shard_size = self.shard_size().min(shard_file_size.saturating_sub(shard_offset));
            let (mut shards, errs) = read_heal_shards(&mut readers, shard_size, read_timeout).await;

            // Every source shard is already bitrot-verified by its reader, so any
            // data_shards survivors are sufficient to reconstruct — requiring more
            // would make objects unhealable after losing exactly parity_shards disks,
            // the failure EC is sized to tolerate. The parity cross-checks below stay
            // opportunistic: they run whenever surplus source shards exist.
            let available_shards = errs.iter().filter(|e| e.is_none()).count();
            if available_shards < self.data_shards {
                warn!(
                    required_data_shards = self.data_shards,
                    available_shards,
                    total_shards = errs.len(),
                    errors = ?errs,
                    "Erasure heal read quorum unavailable"
                );
                return Err(Error::ErasureReadQuorum);
            }

            let source_parity = shards
                .iter()
                .enumerate()
                .skip(self.data_shards)
                .filter_map(|(index, shard)| shard.as_ref().map(|shard| (index, shard.clone())))
                .collect::<Vec<_>>();
            if self.parity_shards > 0 {
                self.decode_data_and_parity(&mut shards)?;
                if !source_parity.is_empty() && !self.verify_data_and_parity(&shards)? {
                    return Err(Error::other("can not reconstruct data: inconsistent heal source shards"));
                }
                for (index, source) in source_parity {
                    let Some(rebuilt) = shards[index].as_ref() else {
                        return Err(Error::other("can not reconstruct data: missing rebuilt parity shard"));
                    };
                    if rebuilt != &source {
                        return Err(Error::other("can not reconstruct data: inconsistent heal source shards"));
                    }
                }
            }

            let shards = shards
                .into_iter()
                .map(|s| Bytes::from(s.unwrap_or_default()))
                .collect::<Vec<_>>();

            if let Err(error) = writers.write(shards).await {
                return Err(heal_writer_failure(&mut writers, error));
            }
        }

        if let Err(error) = writers.shutdown().await {
            return Err(heal_writer_failure(&mut writers, error));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::erasure::coding::{CustomWriter, Erasure};
    use rustfs_utils::HashAlgorithm;
    use std::io::{self, Cursor};
    use std::pin::Pin;
    use std::task::{Context, Poll};
    use tokio::io::{AsyncWrite, ReadBuf};

    /// An `AsyncWrite` that accepts writes until `fail_at` bytes have been
    /// written, then fails every subsequent write. Used to simulate a
    /// replacement disk that starts failing on a mid-object block.
    struct FailAfterBytes {
        written: usize,
        fail_at: usize,
    }

    impl AsyncWrite for FailAfterBytes {
        fn poll_write(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
            if self.written >= self.fail_at {
                return Poll::Ready(Err(io::Error::other("injected heal write failure")));
            }
            self.written += buf.len();
            Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    struct InternodeFailureWriter {
        fail_on_write: bool,
        status: http::StatusCode,
    }

    impl InternodeFailureWriter {
        fn error(&self) -> io::Error {
            rustfs_rio::new_test_internode_http_io_error(rustfs_rio::InternodeHttpErrorKind::HttpStatus(self.status))
        }
    }

    impl AsyncWrite for InternodeFailureWriter {
        fn poll_write(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
            Poll::Ready(if self.fail_on_write {
                Err(self.error())
            } else {
                Ok(buf.len())
            })
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Err(self.error()))
        }
    }

    struct PendingReader;

    impl AsyncRead for PendingReader {
        fn poll_read(self: Pin<&mut Self>, _cx: &mut Context<'_>, _buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
            Poll::Pending
        }
    }

    struct FailingReader;

    impl AsyncRead for FailingReader {
        fn poll_read(self: Pin<&mut Self>, _cx: &mut Context<'_>, _buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Err(io::Error::other("synthetic heal read failure")))
        }
    }

    fn inline_writer(shard_size: usize) -> BitrotWriterWrapper {
        BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), shard_size, HashAlgorithm::None)
    }

    #[tokio::test]
    async fn read_heal_shards_returns_empty_slots_for_zero_sized_shards() {
        let mut readers = vec![
            Some(BitrotReader::new(Cursor::new(vec![1, 2, 3]), 0, HashAlgorithm::None, false)),
            None,
        ];

        let (shards, errs) = read_heal_shards(&mut readers, 0, Duration::ZERO).await;

        assert_eq!(shards, vec![None, None]);
        assert_eq!(errs, vec![None, None]);
    }

    #[tokio::test]
    async fn read_heal_shards_records_reader_errors_and_retiring_timeouts() {
        let mut readers = vec![Some(BitrotReader::new(FailingReader, 4, HashAlgorithm::None, false))];

        let (shards, errs) = read_heal_shards(&mut readers, 4, Duration::ZERO).await;

        assert!(shards[0].is_none());
        assert!(
            errs[0]
                .as_ref()
                .is_some_and(|err| err.to_string().contains("synthetic heal read failure"))
        );
        assert!(readers[0].is_some(), "ordinary read errors must not retire readers");

        let mut timeout_readers = vec![Some(BitrotReader::new(PendingReader, 4, HashAlgorithm::None, false))];
        let (shards, errs) = read_heal_shards(&mut timeout_readers, 4, Duration::from_millis(1)).await;

        assert_eq!(shards, vec![None]);
        assert!(errs[0].as_ref().is_some_and(|err| err.to_string().contains("timed out")));
        assert!(timeout_readers[0].is_none(), "timed-out readers are retired");
    }

    #[tokio::test]
    async fn heal_rejects_invalid_writer_shape_before_reading() {
        let erasure = Erasure::new(2, 1, 64);
        let mut writers = vec![Some(inline_writer(erasure.shard_size()))];
        let readers: Vec<Option<BitrotReader<Cursor<Vec<u8>>>>> = Vec::new();

        let err = erasure
            .heal(&mut writers, readers, 0, &[])
            .await
            .expect_err("invalid writer count must fail");

        assert!(err.to_string().contains("invalid argument"));
    }

    #[tokio::test]
    async fn heal_empty_object_only_shuts_down_available_writers() {
        let erasure = Erasure::new(2, 1, 64);
        let mut writers = (0..erasure.total_shard_count())
            .map(|_| Some(inline_writer(erasure.shard_size())))
            .collect::<Vec<_>>();
        let readers: Vec<Option<BitrotReader<Cursor<Vec<u8>>>>> = Vec::new();

        erasure
            .heal(&mut writers, readers, 0, &[])
            .await
            .expect("empty object heal should only close writers");

        assert!(writers.iter().all(Option::is_some));
    }

    #[tokio::test]
    async fn heal_maps_put_file_epoch_conflict_to_retryable_remote_unavailable() {
        for status in [http::StatusCode::CONFLICT, http::StatusCode::BAD_REQUEST] {
            for (fail_on_write, data) in [
                (false, b"".as_slice()),
                (false, b"payload".as_slice()),
                (true, b"payload".as_slice()),
            ] {
                let erasure = Erasure::new(2, 1, 64);
                let encoded = erasure.encode_data(data).expect("source shards should encode");
                let readers = encoded
                    .iter()
                    .enumerate()
                    .map(|(index, shard)| {
                        (index < erasure.data_shards).then(|| {
                            BitrotReader::new(Cursor::new(shard.to_vec()), erasure.shard_size(), HashAlgorithm::None, false)
                        })
                    })
                    .collect::<Vec<_>>();
                let mut writers = (0..erasure.total_shard_count())
                    .map(|index| {
                        (index == erasure.data_shards).then(|| {
                            BitrotWriterWrapper::new(
                                CustomWriter::new_tokio_writer(InternodeFailureWriter { fail_on_write, status }),
                                erasure.shard_size(),
                                HashAlgorithm::None,
                            )
                        })
                    })
                    .collect::<Vec<_>>();
                let error = erasure
                    .heal(&mut writers, readers, data.len(), &[])
                    .await
                    .expect_err("failed sole target must not satisfy heal write quorum");
                assert_eq!(
                    matches!(error, Error::RemoteClientUnavailable(_)),
                    status == http::StatusCode::CONFLICT,
                    "status={status}, fail_on_write={fail_on_write}, len={}, error={error:?}",
                    data.len()
                );
                assert!(writers.iter().all(Option::is_none), "failed target must not be committed");
            }
        }
    }

    #[tokio::test]
    async fn heal_epoch_conflict_does_not_abort_healthy_target() {
        for fail_on_write in [false, true] {
            let erasure = Erasure::new(2, 2, 64);
            let data = b"healthy target must retain exact reconstructed bytes";
            let encoded = erasure.encode_data(data).expect("source shards should encode");
            let readers = encoded
                .iter()
                .enumerate()
                .map(|(index, shard)| {
                    (index < erasure.data_shards)
                        .then(|| BitrotReader::new(Cursor::new(shard.to_vec()), erasure.shard_size(), HashAlgorithm::None, false))
                })
                .collect::<Vec<_>>();
            let mut writers = vec![
                None,
                None,
                Some(BitrotWriterWrapper::new(
                    CustomWriter::new_tokio_writer(InternodeFailureWriter {
                        fail_on_write,
                        status: http::StatusCode::CONFLICT,
                    }),
                    erasure.shard_size(),
                    HashAlgorithm::None,
                )),
                Some(inline_writer(erasure.shard_size())),
            ];
            erasure
                .heal(&mut writers, readers, data.len(), &[])
                .await
                .expect("one healthy target must still satisfy the existing heal quorum");
            assert!(writers[2].is_none(), "conflicting target must be dropped");
            assert_eq!(
                writers[3]
                    .take()
                    .expect("healthy target remains")
                    .into_inline_data()
                    .expect("inline target data"),
                encoded[3].to_vec()
            );
        }
    }

    #[tokio::test]
    async fn heal_reconstructs_missing_parity_shard() {
        let erasure = Erasure::new(2, 2, 64);
        let data = b"heal should write a rebuilt parity shard";
        let encoded = erasure.encode_data(data).expect("encode should succeed");
        let missing_parity = erasure.data_shards;

        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index == missing_parity {
                    None
                } else {
                    Some(BitrotReader::new(
                        Cursor::new(shard.to_vec()),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                        false,
                    ))
                }
            })
            .collect::<Vec<_>>();

        let mut writers = (0..erasure.total_shard_count())
            .map(|index| {
                if index == missing_parity {
                    Some(inline_writer(erasure.shard_size()))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect("heal should rebuild parity");

        let healed = writers[missing_parity]
            .take()
            .expect("parity writer should remain")
            .into_inline_data()
            .expect("inline writer should retain data");
        assert_eq!(healed, encoded[missing_parity].to_vec());
    }

    #[tokio::test]
    async fn heal_reconstructs_missing_data_shard_across_multiple_blocks() {
        let erasure = Erasure::new(3, 2, 96);
        let data = (0..erasure.block_size * 2 + 17)
            .map(|index| (index % 251) as u8)
            .collect::<Vec<_>>();
        let encoded = erasure.encode_data(&data).expect("encode should succeed");
        let missing_data = 1;

        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index == missing_data {
                    None
                } else {
                    Some(BitrotReader::new(
                        Cursor::new(shard.to_vec()),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                        false,
                    ))
                }
            })
            .collect::<Vec<_>>();

        let mut writers = (0..erasure.total_shard_count())
            .map(|index| {
                if index == missing_data {
                    Some(inline_writer(erasure.shard_size()))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect("heal should rebuild data");

        let healed = writers[missing_data]
            .take()
            .expect("data writer should remain")
            .into_inline_data()
            .expect("inline writer should retain data");
        assert_eq!(healed, encoded[missing_data].to_vec());
    }

    #[tokio::test]
    async fn heal_returns_read_quorum_when_available_shards_are_insufficient() {
        let erasure = Erasure::new(3, 2, 64);
        let data = b"heal should fail before decode when too few shards are readable";
        let encoded = erasure.encode_data(data).expect("encode should succeed");

        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index < 2 {
                    Some(BitrotReader::new(
                        Cursor::new(shard.to_vec()),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                        false,
                    ))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        let mut writers = (0..erasure.total_shard_count()).map(|_| None).collect::<Vec<_>>();

        let err = erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect_err("heal should fail when available shards are below data shards");

        assert!(matches!(err, Error::ErasureReadQuorum));
    }

    #[tokio::test]
    async fn heal_rejects_inconsistent_sources_before_writing_data_shard() {
        let erasure = Erasure::new(2, 2, 64);
        let data = b"heal must not rebuild data from a stale parity shard";
        let encoded = erasure.encode_data(data).expect("encode should succeed");
        let missing_data = 1;
        let corrupt_parity = erasure.data_shards;

        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index == missing_data {
                    return None;
                }

                let mut shard = shard.to_vec();
                if index == corrupt_parity {
                    shard[0] ^= 0x5a;
                }

                Some(BitrotReader::new(Cursor::new(shard), erasure.shard_size(), HashAlgorithm::None, false))
            })
            .collect::<Vec<_>>();

        let mut writers = (0..erasure.total_shard_count())
            .map(|index| {
                if index == missing_data {
                    Some(inline_writer(erasure.shard_size()))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        let err = erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect_err("heal should reject inconsistent source shards");
        assert!(err.to_string().contains("inconsistent heal source shards"));

        let written = writers[missing_data]
            .take()
            .expect("data writer should remain")
            .into_inline_data()
            .expect("inline writer should retain data");
        assert!(written.is_empty(), "heal must fail before writing rebuilt data");
    }

    // Regression for backlog#947 (ECA-06): a single replacement disk failing to
    // write a mid-object block must not abort healing on the other healthy
    // replacement disks. Before the fix, write_quorum == available_writers made
    // MultiWriter::write return Err on the first per-writer failure, so heal
    // aborted the whole object and left the healthy targets unhealed.
    #[tokio::test]
    async fn heal_completes_healthy_targets_when_one_target_disk_fails_midway() {
        // 2 data + 3 parity: two data shards are readable sources, the three
        // parity positions are empty replacement disks to be healed.
        let erasure = Erasure::new(2, 3, 64);
        // Multiple blocks so the injected failure lands on a mid-object block.
        let data = (0..erasure.block_size * 3)
            .map(|index| (index % 251) as u8)
            .collect::<Vec<_>>();
        let encoded = erasure.encode_data(&data).expect("encode should succeed");

        // Only the two data shards survive as readable sources.
        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index < erasure.data_shards {
                    Some(BitrotReader::new(
                        Cursor::new(shard.to_vec()),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                        false,
                    ))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        // Parity index that will fail mid-way; the other two parity targets stay healthy.
        let failing_target = erasure.data_shards + 1;
        let mut writers = (0..erasure.total_shard_count())
            .map(|index| {
                if index < erasure.data_shards {
                    // Source positions get no writer.
                    None
                } else if index == failing_target {
                    // Fail after the first block's shard has been written.
                    Some(BitrotWriterWrapper::new(
                        CustomWriter::new_tokio_writer(FailAfterBytes {
                            written: 0,
                            fail_at: erasure.shard_size(),
                        }),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                    ))
                } else {
                    Some(BitrotWriterWrapper::new(
                        CustomWriter::new_inline_buffer(),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                    ))
                }
            })
            .collect::<Vec<_>>();

        erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect("heal must succeed on the healthy targets despite one failing disk");

        // The failing target was dropped (marked None) so the ops layer skips it.
        assert!(writers[failing_target].is_none(), "failing target writer must be dropped, not committed");

        // Every healthy replacement target is fully healed.
        for index in erasure.data_shards..erasure.total_shard_count() {
            if index == failing_target {
                continue;
            }
            let healed = writers[index]
                .take()
                .expect("healthy target writer should remain")
                .into_inline_data()
                .expect("inline writer should retain data");
            assert_eq!(healed, encoded[index].to_vec(), "healthy target {index} must be fully healed");
        }
    }

    // Regression for backlog#947: when every replacement disk fails to write,
    // heal must return Err (nothing is falsely reported as healed) so the ops
    // layer cleans up the tmp staging directory instead of committing.
    #[tokio::test]
    async fn heal_fails_when_all_target_disks_fail_midway() {
        let erasure = Erasure::new(2, 3, 64);
        let data = (0..erasure.block_size * 3)
            .map(|index| (index % 251) as u8)
            .collect::<Vec<_>>();
        let encoded = erasure.encode_data(&data).expect("encode should succeed");

        let readers = encoded
            .iter()
            .enumerate()
            .map(|(index, shard)| {
                if index < erasure.data_shards {
                    Some(BitrotReader::new(
                        Cursor::new(shard.to_vec()),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                        false,
                    ))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        let mut writers = (0..erasure.total_shard_count())
            .map(|index| {
                if index < erasure.data_shards {
                    None
                } else {
                    // Every replacement target fails after the first block.
                    Some(BitrotWriterWrapper::new(
                        CustomWriter::new_tokio_writer(FailAfterBytes {
                            written: 0,
                            fail_at: erasure.shard_size(),
                        }),
                        erasure.shard_size(),
                        HashAlgorithm::None,
                    ))
                }
            })
            .collect::<Vec<_>>();

        erasure
            .heal(&mut writers, readers, data.len(), &[])
            .await
            .expect_err("heal must fail when all replacement disks fail");
    }
}