frankensearch-durability 0.2.1

RaptorQ durability primitives for frankensearch indices
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
//! FSVI-specific durability protector.
//!
//! Wraps the generic [`FileProtector`] with FSVI-aware features:
//! - xxh3 fast-path integrity verification (<1ms for any file size)
//! - Atomic sidecar writes via temp-file + rename
//! - File naming convention: `index.fsvi` → `index.fsvi.fec`

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use frankensearch_core::{SearchError, SearchResult};
use fsqlite_core::raptorq_integration::SymbolCodec;
use memmap2::Mmap;
use tracing::{debug, info, warn};
use xxhash_rust::xxh3::xxh3_64;

use crate::config::DurabilityConfig;
use crate::file_protector::{FileProtector, FileRepairOutcome};
use crate::metrics::DurabilityMetrics;
use crate::repair_trailer::deserialize_repair_trailer;

fn acquire_shared_fsvi_map_lock(file: &fs::File, path: &Path) -> SearchResult<()> {
    file.try_lock_shared().map_err(|error| SearchError::InvalidConfig {
        field: "fsvi.map_lock".to_owned(),
        value: path.display().to_string(),
        reason: format!(
            "cannot acquire shared reader lock before mapping this published FSVI: {error}; a writer may be active"
        ),
    })
}

fn acquire_exclusive_fsvi_writer_lock(file: &fs::File, path: &Path) -> SearchResult<()> {
    file.try_lock().map_err(|error| SearchError::InvalidConfig {
        field: "fsvi.map_lock".to_owned(),
        value: path.display().to_string(),
        reason: format!(
            "cannot acquire exclusive writer lock before repairing this published FSVI: {error}; drop live readers/writers before retrying"
        ),
    })
}

/// Result of protecting an FSVI file with repair symbols.
#[derive(Debug, Clone)]
pub struct FsviProtectionResult {
    /// Path to the `.fec` sidecar file.
    pub sidecar_path: PathBuf,
    /// Size of the source FSVI file in bytes.
    pub source_size: u64,
    /// Size of the generated sidecar in bytes.
    pub repair_size: u64,
    /// Overhead ratio (`repair_size` / `source_size`).
    pub overhead_ratio: f32,
    /// Number of source symbols.
    pub k_source: u32,
    /// Number of repair symbols.
    pub r_repair: u32,
    /// `xxh3_64` hash of the protected source file.
    pub source_hash: u64,
    /// Time spent encoding repair symbols.
    pub encode_time: Duration,
}

/// Result of repairing a corrupted FSVI file.
#[derive(Debug, Clone)]
pub struct FsviRepairResult {
    /// Number of bytes in the repaired file.
    pub bytes_written: usize,
    /// Number of repair symbols consumed during decode.
    pub symbols_used: u32,
    /// Time spent decoding and writing the repaired file.
    pub decode_time: Duration,
    /// `xxh3_64` hash of the corrupted data before repair.
    pub source_hash_before: u64,
    /// `xxh3_64` hash of the repaired data (should match the stored hash).
    pub source_hash_after: u64,
}

/// FSVI fast-path verification result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FsviVerifyResult {
    /// File integrity confirmed via `xxh3_64` hash match.
    Intact,
    /// File is corrupted. The generic verify provides CRC detail.
    Corrupted {
        /// Whether the sidecar has enough repair symbols to recover.
        repairable: bool,
    },
    /// No sidecar found — cannot verify.
    NoSidecar,
}

/// FSVI-specific durability protector with xxh3 fast-path verification
/// and atomic sidecar writes.
#[derive(Debug, Clone)]
pub struct FsviProtector {
    protector: FileProtector,
    metrics: Arc<DurabilityMetrics>,
}

impl FsviProtector {
    /// Create a new FSVI protector.
    pub fn new(codec: Arc<dyn SymbolCodec>, config: DurabilityConfig) -> SearchResult<Self> {
        let metrics = Arc::new(DurabilityMetrics::default());
        let protector = FileProtector::new_with_metrics(codec, config, Arc::clone(&metrics))?;
        Ok(Self { protector, metrics })
    }

    /// Derive the `.fec` sidecar path for an FSVI file.
    #[must_use]
    pub fn sidecar_path(fsvi_path: &Path) -> PathBuf {
        PathBuf::from(format!("{}.fec", fsvi_path.display()))
    }

    /// Protect an FSVI file by generating repair symbols and writing
    /// a `.fec` sidecar via atomic temp-file + rename.
    ///
    /// The protection is crash-safe: either the complete sidecar is
    /// visible at the `.fec` path, or it isn't. No partial writes.
    #[allow(unsafe_code)] // Mmap::map requires unsafe for memory-mapped I/O.
    pub fn protect_atomic(&self, fsvi_path: &Path) -> SearchResult<FsviProtectionResult> {
        let start = Instant::now();

        let source_lock = fs::File::open(fsvi_path).map_err(SearchError::Io)?;
        acquire_shared_fsvi_map_lock(&source_lock, fsvi_path)?;

        // Generate repair symbols via the inner protector.
        // FileProtector::protect_file now handles atomic write (temp + rename) internally.
        let protection = self.protector.protect_file(fsvi_path)?;
        let source_size = protection.source_len;
        let source_hash = protection.source_xxh3;
        let sidecar_path = protection.sidecar_path;

        let repair_size = fs::metadata(&sidecar_path).map_or(0, |metadata| metadata.len());
        // Compute in f64 first to avoid double precision loss from u64→f32.
        #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
        let overhead_ratio = if source_size > 0 {
            (repair_size as f64 / source_size as f64) as f32
        } else {
            0.0
        };

        let encode_time = start.elapsed();

        info!(
            path = %fsvi_path.display(),
            source_size,
            repair_size,
            overhead_ratio,
            source_hash,
            encode_time_ms = encode_time.as_millis(),
            "FSVI protection complete"
        );

        Ok(FsviProtectionResult {
            sidecar_path,
            source_size,
            repair_size,
            overhead_ratio,
            k_source: protection.k_source,
            r_repair: protection.repair_symbol_count,
            source_hash,
            encode_time,
        })
    }

    /// Verify integrity using the sidecar.
    ///
    /// Tries the xxh3 fast-path first (<1ms). If that fails (hash mismatch or
    /// V1 trailer), falls back to full CRC32 verification.
    #[allow(unsafe_code)] // Mmap::map requires unsafe for memory-mapped I/O.
    pub fn verify(&self, fsvi_path: &Path) -> SearchResult<FsviVerifyResult> {
        let sidecar_path = Self::sidecar_path(fsvi_path);

        if !sidecar_path.exists() {
            debug!(
                path = %fsvi_path.display(),
                "no .fec sidecar found, skipping verification"
            );
            return Ok(FsviVerifyResult::NoSidecar);
        }

        // If the source file is missing but a sidecar exists, treat as corrupted so
        // callers can attempt repair.
        let file = match fs::File::open(fsvi_path) {
            Ok(file) => file,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                // Validate the sidecar payload before declaring repairable.
                let trailer_bytes = self.protector.read_sidecar_bounded(&sidecar_path)?;
                let _ = deserialize_repair_trailer(&trailer_bytes)?;
                let repairable = self.protector.is_repairable(fsvi_path, &sidecar_path)?;
                warn!(
                    path = %fsvi_path.display(),
                    "FSVI source missing; sidecar present (treating as corrupted)"
                );
                return Ok(FsviVerifyResult::Corrupted { repairable });
            }
            Err(err) => return Err(SearchError::Io(err)),
        };

        // Fast path: xxh3 hash check
        let len = file.metadata().map_err(SearchError::Io)?.len();
        let actual_hash = if len == 0 {
            xxh3_64(&[])
        } else {
            acquire_shared_fsvi_map_lock(&file, fsvi_path)?;
            // SAFETY: the shared lock is retained by `file` for the mapping's
            // lifetime, and every FSVI writer acquires the exclusive version
            // before making a writable map.
            let mmap = unsafe { Mmap::map(&file).map_err(SearchError::Io)? };
            xxh3_64(&mmap)
        };

        // Read sidecar trailer to get expected hash
        let trailer_bytes = self.protector.read_sidecar_bounded(&sidecar_path)?;
        let (header, _) = deserialize_repair_trailer(&trailer_bytes)?;

        if header.source_xxh3 != 0 && actual_hash == header.source_xxh3 {
            debug!(
                path = %fsvi_path.display(),
                hash = actual_hash,
                "FSVI integrity verified (fast path)"
            );
            return Ok(FsviVerifyResult::Intact);
        }

        // Fallback to full CRC32 check (V1 trailer or corruption)
        let verify = self.protector.verify_file(fsvi_path, &sidecar_path)?;

        if verify.healthy {
            return Ok(FsviVerifyResult::Intact);
        }

        // Corruption detected — check if repairable
        let repairable = self.protector.is_repairable(fsvi_path, &sidecar_path)?;
        warn!(
            path = %fsvi_path.display(),
            expected_crc = verify.expected_crc32,
            actual_crc = verify.actual_crc32,
            expected_len = verify.expected_len,
            actual_len = verify.actual_len,
            "FSVI corruption detected"
        );

        Ok(FsviVerifyResult::Corrupted { repairable })
    }

    /// Attempt to repair a corrupted FSVI file using the `.fec` sidecar.
    ///
    /// On success, the corrupted file is overwritten with the repaired data.
    /// A backup of the corrupted file is created at `<path>.corrupted` before
    /// overwriting.
    #[allow(unsafe_code)] // Mmap::map requires unsafe for memory-mapped I/O.
    pub fn repair(&self, fsvi_path: &Path) -> SearchResult<FsviRepairResult> {
        let start = Instant::now();
        let sidecar_path = Self::sidecar_path(fsvi_path);

        if !sidecar_path.exists() {
            return Err(SearchError::IndexCorrupted {
                path: fsvi_path.to_path_buf(),
                detail: "no .fec sidecar available for repair".to_owned(),
            });
        }

        // Compute hash before repair (if file exists).
        let source_lock = match fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(fsvi_path)
        {
            Ok(file) => {
                acquire_exclusive_fsvi_writer_lock(&file, fsvi_path)?;
                Some(file)
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
            Err(err) => return Err(SearchError::Io(err)),
        };
        let (hash_before, len, had_source) = match source_lock.as_ref() {
            Some(file) => {
                let len = file.metadata().map_err(SearchError::Io)?.len();
                let hash_before = if len == 0 {
                    xxh3_64(&[])
                } else {
                    // SAFETY: the exclusive writer lock is retained by
                    // `source_lock` until repair completes.
                    let mmap = unsafe { Mmap::map(file).map_err(SearchError::Io)? };
                    xxh3_64(&mmap)
                };
                (hash_before, len, true)
            }
            None => (0, 0, false),
        };

        let backup_path = if had_source {
            let backup_path = PathBuf::from(format!("{}.corrupted", fsvi_path.display()));
            fs::copy(fsvi_path, &backup_path).map_err(SearchError::Io)?;
            debug!(
                backup = %backup_path.display(),
                "backed up corrupted FSVI file before repair"
            );
            Some(backup_path)
        } else {
            None
        };

        // Attempt repair
        let outcome = self.protector.repair_file(fsvi_path, &sidecar_path)?;

        let decode_time = start.elapsed();

        match outcome {
            FileRepairOutcome::NotNeeded => {
                // Clean up unnecessary backup
                if let Some(path) = &backup_path {
                    let _ = fs::remove_file(path);
                }
                Ok(FsviRepairResult {
                    bytes_written: usize::try_from(len).unwrap_or(usize::MAX),
                    symbols_used: 0,
                    decode_time,
                    source_hash_before: hash_before,
                    source_hash_after: hash_before,
                })
            }
            FileRepairOutcome::Repaired {
                bytes_written,
                symbols_used,
            } => {
                // `repair_file` atomically replaces recovered artifacts, so
                // the exclusive source handle can refer to the old inode.
                // Drop it before locking the artifact that was published.
                drop(source_lock);
                // Verify hash after repair
                let repaired_file = fs::File::open(fsvi_path).map_err(SearchError::Io)?;
                let repaired_len = repaired_file.metadata().map_err(SearchError::Io)?.len();
                let hash_after = if repaired_len == 0 {
                    xxh3_64(&[])
                } else {
                    acquire_shared_fsvi_map_lock(&repaired_file, fsvi_path)?;
                    // SAFETY: the shared lock is retained by `repaired_file`
                    // for the mapping lifetime and protects the inode repair
                    // actually published.
                    let mmap = unsafe { Mmap::map(&repaired_file).map_err(SearchError::Io)? };
                    xxh3_64(&mmap)
                };

                info!(
                    path = %fsvi_path.display(),
                    bytes_written,
                    symbols_used,
                    hash_before,
                    hash_after,
                    decode_time_ms = decode_time.as_millis(),
                    "FSVI repair successful"
                );

                Ok(FsviRepairResult {
                    bytes_written,
                    symbols_used,
                    decode_time,
                    source_hash_before: hash_before,
                    source_hash_after: hash_after,
                })
            }
            FileRepairOutcome::Unrecoverable {
                reason,
                symbols_received,
                k_required,
            } => {
                warn!(
                    path = %fsvi_path.display(),
                    ?reason,
                    symbols_received,
                    k_required,
                    "FSVI repair failed, restoring backup"
                );

                // Restore the backup
                if let Some(path) = &backup_path {
                    fs::copy(path, fsvi_path).map_err(SearchError::Io)?;
                }

                Err(SearchError::IndexCorrupted {
                    path: fsvi_path.to_path_buf(),
                    detail: format!(
                        "repair failed: {reason:?} (received {symbols_received}/{k_required} symbols)"
                    ),
                })
            }
        }
    }

    /// Convenience: verify and auto-repair if needed.
    ///
    /// Returns `Ok(true)` if the file is healthy (either originally or after repair).
    /// Returns `Ok(false)` if no sidecar exists (unprotected file).
    /// Returns `Err` if repair was attempted and failed.
    pub fn verify_and_repair(&self, fsvi_path: &Path) -> SearchResult<bool> {
        match self.verify(fsvi_path)? {
            FsviVerifyResult::Intact => Ok(true),
            FsviVerifyResult::NoSidecar => Ok(false),
            FsviVerifyResult::Corrupted { repairable: true } => {
                self.repair(fsvi_path)?;
                Ok(true)
            }
            FsviVerifyResult::Corrupted { repairable: false } => Err(SearchError::IndexCorrupted {
                path: fsvi_path.to_path_buf(),
                detail: "corruption exceeds repair capacity".to_owned(),
            }),
        }
    }

    /// Get the current durability metrics.
    pub fn metrics_snapshot(&self) -> crate::metrics::DurabilityMetricsSnapshot {
        self.metrics.snapshot()
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::Arc;
    use std::time::{SystemTime, UNIX_EPOCH};

    use fsqlite_core::raptorq_integration::{CodecDecodeResult, CodecEncodeResult, SymbolCodec};
    use fsqlite_types::cx::Cx;

    use super::{FsviProtector, FsviVerifyResult, acquire_shared_fsvi_map_lock};
    use crate::config::DurabilityConfig;

    /// Mock codec that creates simple repair symbols for testing.
    #[derive(Debug)]
    struct MockCodec;

    impl SymbolCodec for MockCodec {
        fn encode(
            &self,
            _cx: &Cx,
            source_data: &[u8],
            symbol_size: u32,
            _repair_overhead: f64,
        ) -> fsqlite_error::Result<CodecEncodeResult> {
            let symbol_size_usize = usize::try_from(symbol_size).unwrap_or(1);
            let mut source_symbols = Vec::new();
            let mut repair_symbols = Vec::new();

            let mut esi: u32 = 0;
            for chunk in source_data.chunks(symbol_size_usize) {
                let mut data = chunk.to_vec();
                if data.len() < symbol_size_usize {
                    data.resize(symbol_size_usize, 0);
                }
                source_symbols.push((esi, data.clone()));
                repair_symbols.push((esi + 1_000_000, data));
                esi = esi.saturating_add(1);
            }

            Ok(CodecEncodeResult {
                source_symbols,
                repair_symbols,
                k_source: esi,
            })
        }

        fn decode(
            &self,
            _cx: &Cx,
            symbols: &[(u32, Vec<u8>)],
            k_source: u32,
            _symbol_size: u32,
        ) -> fsqlite_error::Result<CodecDecodeResult> {
            let mut reconstructed = Vec::new();
            for source_esi in 0..k_source {
                let primary = symbols
                    .iter()
                    .find(|(esi, _)| *esi == source_esi)
                    .map(|(_, data)| data.clone());
                let fallback = symbols
                    .iter()
                    .find(|(esi, _)| *esi == source_esi + 1_000_000)
                    .map(|(_, data)| data.clone());

                match primary.or(fallback) {
                    Some(data) => reconstructed.extend_from_slice(&data),
                    None => {
                        return Ok(CodecDecodeResult::Failure {
                            reason:
                                fsqlite_core::raptorq_integration::DecodeFailureReason::InsufficientSymbols,
                            symbols_received: u32::try_from(symbols.len()).unwrap_or(u32::MAX),
                            k_required: k_source,
                        });
                    }
                }
            }

            Ok(CodecDecodeResult::Success {
                data: reconstructed,
                symbols_used: k_source,
                peeled_count: k_source,
                inactivated_count: 0,
            })
        }
    }

    /// Mock codec that emits no repair symbols (forces unrepairable corruption).
    #[derive(Debug)]
    struct NoRepairCodec;

    impl SymbolCodec for NoRepairCodec {
        fn encode(
            &self,
            _cx: &Cx,
            source_data: &[u8],
            symbol_size: u32,
            _repair_overhead: f64,
        ) -> fsqlite_error::Result<CodecEncodeResult> {
            let symbol_size_usize = usize::try_from(symbol_size).unwrap_or(1);
            let mut source_symbols = Vec::new();

            let mut esi: u32 = 0;
            for chunk in source_data.chunks(symbol_size_usize) {
                let mut data = chunk.to_vec();
                if data.len() < symbol_size_usize {
                    data.resize(symbol_size_usize, 0);
                }
                source_symbols.push((esi, data));
                esi = esi.saturating_add(1);
            }

            Ok(CodecEncodeResult {
                source_symbols,
                repair_symbols: Vec::new(),
                k_source: esi,
            })
        }

        fn decode(
            &self,
            _cx: &Cx,
            symbols: &[(u32, Vec<u8>)],
            k_source: u32,
            _symbol_size: u32,
        ) -> fsqlite_error::Result<CodecDecodeResult> {
            if symbols.len() < k_source as usize {
                return Ok(CodecDecodeResult::Failure {
                    reason:
                        fsqlite_core::raptorq_integration::DecodeFailureReason::InsufficientSymbols,
                    symbols_received: u32::try_from(symbols.len()).unwrap_or(u32::MAX),
                    k_required: k_source,
                });
            }

            Ok(CodecDecodeResult::Success {
                data: Vec::new(),
                symbols_used: k_source,
                peeled_count: 0,
                inactivated_count: 0,
            })
        }
    }

    fn temp_path(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        std::env::temp_dir().join(format!(
            "frankensearch-fsvi-{prefix}-{}-{nanos}.fsvi",
            std::process::id()
        ))
    }

    fn make_protector() -> FsviProtector {
        let config = DurabilityConfig {
            symbol_size: 256,
            // 100% overhead ensures enough repair symbols for full-file recovery.
            repair_overhead: 2.0,
            ..DurabilityConfig::default()
        };
        FsviProtector::new(Arc::new(MockCodec), config).expect("create protector")
    }

    fn make_unrepairable_protector() -> FsviProtector {
        let config = DurabilityConfig {
            symbol_size: 256,
            repair_overhead: 1.0,
            ..DurabilityConfig::default()
        };
        FsviProtector::new(Arc::new(NoRepairCodec), config).expect("create protector")
    }

    #[test]
    fn sidecar_path_appends_fec_extension() {
        let path = PathBuf::from("/tmp/index.fast.fsvi");
        let sidecar = FsviProtector::sidecar_path(&path);
        assert_eq!(sidecar, PathBuf::from("/tmp/index.fast.fsvi.fec"));
    }

    #[test]
    fn shared_mapping_refuses_a_published_fsvi_held_by_a_writer() {
        let path = temp_path("shared-map-writer-contention");
        std::fs::write(&path, b"published fsvi fixture").expect("write fixture");

        let writer = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .expect("open writer fixture");
        writer.try_lock().expect("hold exclusive writer lock");
        let reader = std::fs::File::open(&path).expect("open reader fixture");

        let error = acquire_shared_fsvi_map_lock(&reader, &path)
            .expect_err("durability verification must not map while a writer owns the artifact");
        assert!(matches!(
            error,
            frankensearch_core::SearchError::InvalidConfig { field, .. } if field == "fsvi.map_lock"
        ));

        drop(writer);
        acquire_shared_fsvi_map_lock(&reader, &path)
            .expect("reader maps only after the writer lock is released");
    }

    #[test]
    fn protect_and_verify_roundtrip() {
        let protector = make_protector();
        let path = temp_path("protect-verify");

        // Create a fake FSVI file
        let payload = vec![42_u8; 700];
        std::fs::write(&path, &payload).expect("write payload");

        // Protect
        let result = protector.protect_atomic(&path).expect("protect");
        assert!(result.sidecar_path.exists());
        assert!(result.source_size > 0);
        assert!(result.repair_size > 0);
        assert!(result.overhead_ratio > 0.0);
        assert!(result.source_hash != 0);

        // Verify
        let verify = protector.verify(&path).expect("verify");
        assert_eq!(verify, FsviVerifyResult::Intact);

        // Clean up
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&result.sidecar_path);
    }

    #[test]
    fn verify_returns_no_sidecar_when_missing() {
        let protector = make_protector();
        let path = temp_path("no-sidecar");

        std::fs::write(&path, b"data").expect("write");
        let verify = protector.verify(&path).expect("verify");
        assert_eq!(verify, FsviVerifyResult::NoSidecar);

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn verify_missing_source_with_sidecar_is_repairable() {
        let protector = make_protector();
        let path = temp_path("missing-source");

        let payload = vec![88_u8; 512];
        std::fs::write(&path, &payload).expect("write payload");
        let protection = protector.protect_atomic(&path).expect("protect");

        std::fs::remove_file(&path).expect("remove source");

        let verify = protector.verify(&path).expect("verify missing source");
        assert!(
            matches!(verify, FsviVerifyResult::Corrupted { repairable: true }),
            "expected Corrupted+repairable, got {verify:?}"
        );

        let repair = protector.repair(&path).expect("repair missing source");
        assert!(repair.bytes_written > 0);
        let restored = std::fs::read(&path).expect("read restored");
        assert_eq!(restored, payload);

        let verify_after = protector.verify(&path).expect("verify restored");
        assert_eq!(verify_after, FsviVerifyResult::Intact);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&protection.sidecar_path);
        let backup = PathBuf::from(format!("{}.corrupted", path.display()));
        let _ = std::fs::remove_file(&backup);
    }

    #[test]
    fn verify_flags_unrepairable_when_symbols_insufficient() {
        let protector = make_unrepairable_protector();
        let path = temp_path("unrepairable");

        let payload = vec![7_u8; 512];
        std::fs::write(&path, &payload).expect("write payload");

        let result = protector.protect_atomic(&path).expect("protect");
        assert!(result.sidecar_path.exists());

        let mut corrupted = payload;
        corrupted[0] ^= 0xFF;
        std::fs::write(&path, &corrupted).expect("write corrupted");

        let verify = protector.verify(&path).expect("verify");
        assert!(
            matches!(verify, FsviVerifyResult::Corrupted { repairable: false }),
            "expected unrepairable corruption, got {verify:?}"
        );

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&result.sidecar_path);
    }

    #[test]
    fn corruption_detected_and_repaired() {
        let protector = make_protector();
        let path = temp_path("corrupt-repair");

        let payload = vec![99_u8; 700];
        std::fs::write(&path, &payload).expect("write payload");

        let protection = protector.protect_atomic(&path).expect("protect");

        // Corrupt the file
        std::fs::write(&path, vec![0_u8; 700]).expect("corrupt");

        // Verify detects corruption
        let verify = protector.verify(&path).expect("verify");
        assert!(matches!(verify, FsviVerifyResult::Corrupted { .. }));

        // Repair
        let repair_result = protector.repair(&path).expect("repair");
        assert!(repair_result.bytes_written > 0);
        assert!(repair_result.symbols_used > 0);

        // Verify passes after repair
        let verify_after = protector.verify(&path).expect("verify after repair");
        assert_eq!(verify_after, FsviVerifyResult::Intact);

        // Content is restored
        let restored = std::fs::read(&path).expect("read restored");
        assert_eq!(restored, payload);

        // Clean up
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&protection.sidecar_path);
        let backup = PathBuf::from(format!("{}.corrupted", path.display()));
        let _ = std::fs::remove_file(&backup);
    }

    #[test]
    fn verify_and_repair_convenience() {
        let protector = make_protector();
        let path = temp_path("verify-repair-conv");

        let payload = vec![55_u8; 500];
        std::fs::write(&path, &payload).expect("write");
        let protection = protector.protect_atomic(&path).expect("protect");

        // Healthy file
        assert!(protector.verify_and_repair(&path).expect("healthy"));

        // Corrupt and auto-repair
        std::fs::write(&path, vec![0_u8; 500]).expect("corrupt");
        assert!(protector.verify_and_repair(&path).expect("repaired"));

        // Verify content restored
        let restored = std::fs::read(&path).expect("read");
        assert_eq!(restored, payload);

        // Clean up
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&protection.sidecar_path);
        let backup = PathBuf::from(format!("{}.corrupted", path.display()));
        let _ = std::fs::remove_file(&backup);
    }

    #[test]
    fn metrics_track_operations() {
        let protector = make_protector();
        let path = temp_path("metrics");

        std::fs::write(&path, vec![1_u8; 300]).expect("write");
        protector.protect_atomic(&path).expect("protect");

        let snap = protector.metrics_snapshot();
        assert!(snap.encode_ops >= 1);

        let sidecar = FsviProtector::sidecar_path(&path);
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&sidecar);
    }

    #[test]
    fn protect_atomic_can_replace_existing_sidecar_repeatedly() {
        let protector = make_protector();
        let path = temp_path("protect-replace-existing");
        let sidecar = FsviProtector::sidecar_path(&path);

        std::fs::write(&path, vec![7_u8; 512]).expect("write initial payload");
        protector.protect_atomic(&path).expect("first protect");
        assert!(sidecar.exists());

        std::fs::write(&path, vec![9_u8; 640]).expect("write updated payload");
        protector.protect_atomic(&path).expect("second protect");
        assert!(sidecar.exists());
        assert!(
            !PathBuf::from(format!("{}.tmp", sidecar.display())).exists(),
            "temp sidecar should be cleaned up"
        );

        let verify = protector.verify(&path).expect("verify after replace");
        assert_eq!(verify, FsviVerifyResult::Intact);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&sidecar);
        let _ = std::fs::remove_file(PathBuf::from(format!("{}.bak", sidecar.display())));
    }

    // ─── bd-c2u4 tests begin ───

    #[test]
    fn sidecar_path_nested_dirs() {
        let path = PathBuf::from("/a/b/c/deep/index.fsvi");
        assert_eq!(
            FsviProtector::sidecar_path(&path),
            PathBuf::from("/a/b/c/deep/index.fsvi.fec")
        );
    }

    #[test]
    fn sidecar_path_relative() {
        let path = PathBuf::from("data/my.fsvi");
        assert_eq!(
            FsviProtector::sidecar_path(&path),
            PathBuf::from("data/my.fsvi.fec")
        );
    }

    #[test]
    fn sidecar_path_multiple_dots() {
        let path = PathBuf::from("/tmp/index.fast.v2.fsvi");
        assert_eq!(
            FsviProtector::sidecar_path(&path),
            PathBuf::from("/tmp/index.fast.v2.fsvi.fec")
        );
    }

    #[test]
    fn sidecar_path_bare_name() {
        let path = PathBuf::from("index.fsvi");
        assert_eq!(
            FsviProtector::sidecar_path(&path),
            PathBuf::from("index.fsvi.fec")
        );
    }

    #[test]
    fn fsvi_verify_result_eq_intact() {
        assert_eq!(FsviVerifyResult::Intact, FsviVerifyResult::Intact);
    }

    #[test]
    fn fsvi_verify_result_eq_no_sidecar() {
        assert_eq!(FsviVerifyResult::NoSidecar, FsviVerifyResult::NoSidecar);
    }

    #[test]
    fn fsvi_verify_result_eq_corrupted_same() {
        assert_eq!(
            FsviVerifyResult::Corrupted { repairable: true },
            FsviVerifyResult::Corrupted { repairable: true }
        );
    }

    #[test]
    fn fsvi_verify_result_ne_corrupted_different_repairable() {
        assert_ne!(
            FsviVerifyResult::Corrupted { repairable: true },
            FsviVerifyResult::Corrupted { repairable: false }
        );
    }

    #[test]
    fn fsvi_verify_result_ne_different_variants() {
        assert_ne!(FsviVerifyResult::Intact, FsviVerifyResult::NoSidecar);
        assert_ne!(
            FsviVerifyResult::Intact,
            FsviVerifyResult::Corrupted { repairable: true }
        );
    }

    #[test]
    fn fsvi_verify_result_clone() {
        let original = FsviVerifyResult::Corrupted { repairable: true };
        let cloned = original;
        assert_eq!(original, cloned);
    }

    #[test]
    fn fsvi_verify_result_debug() {
        let intact_debug = format!("{:?}", FsviVerifyResult::Intact);
        assert!(intact_debug.contains("Intact"));

        let corrupted_debug = format!("{:?}", FsviVerifyResult::Corrupted { repairable: false });
        assert!(corrupted_debug.contains("Corrupted"));
        assert!(corrupted_debug.contains("repairable"));
    }

    #[test]
    fn fsvi_protection_result_clone() {
        let result = super::FsviProtectionResult {
            sidecar_path: PathBuf::from("/tmp/test.fec"),
            source_size: 1000,
            repair_size: 200,
            overhead_ratio: 0.2,
            k_source: 4,
            r_repair: 4,
            source_hash: 12345,
            encode_time: std::time::Duration::from_millis(5),
        };
        #[allow(clippy::redundant_clone)]
        let cloned = result.clone();
        assert_eq!(cloned.source_size, 1000);
        assert_eq!(cloned.k_source, 4);
        assert_eq!(cloned.source_hash, 12345);
    }

    #[test]
    fn fsvi_repair_result_clone() {
        let result = super::FsviRepairResult {
            bytes_written: 500,
            symbols_used: 3,
            decode_time: std::time::Duration::from_millis(10),
            source_hash_before: 111,
            source_hash_after: 222,
        };
        #[allow(clippy::redundant_clone)]
        let cloned = result.clone();
        assert_eq!(cloned.bytes_written, 500);
        assert_eq!(cloned.symbols_used, 3);
        assert_eq!(cloned.source_hash_before, 111);
        assert_eq!(cloned.source_hash_after, 222);
    }

    #[test]
    fn repair_no_sidecar_returns_error() {
        let protector = make_protector();
        let path = temp_path("repair-no-sidecar");

        std::fs::write(&path, b"some data").expect("write");

        let err = protector.repair(&path);
        assert!(err.is_err());
        let err_str = format!("{}", err.unwrap_err());
        assert!(err_str.contains("no .fec sidecar"));

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn verify_and_repair_no_sidecar_returns_false() {
        let protector = make_protector();
        let path = temp_path("vandr-no-sidecar");

        std::fs::write(&path, b"payload").expect("write");

        let result = protector.verify_and_repair(&path).expect("should succeed");
        assert!(!result, "no sidecar should return Ok(false)");

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn protect_result_has_valid_k_and_r() {
        let protector = make_protector();
        let path = temp_path("k-and-r");

        std::fs::write(&path, vec![42_u8; 1024]).expect("write");
        let result = protector.protect_atomic(&path).expect("protect");

        assert!(result.k_source > 0, "k_source must be positive");
        assert!(result.r_repair > 0, "r_repair must be positive");
        assert_eq!(result.source_size, 1024);
        assert!(result.source_hash != 0);
        assert!(!result.encode_time.is_zero() || result.encode_time == std::time::Duration::ZERO);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&result.sidecar_path);
    }

    #[test]
    fn protect_empty_file_zero_overhead() {
        let protector = make_protector();
        let path = temp_path("empty-file");

        std::fs::write(&path, b"").expect("write empty");
        let result = protector.protect_atomic(&path).expect("protect");

        assert_eq!(result.source_size, 0);
        // overhead_ratio should be 0.0 when source_size is 0
        assert!(
            (result.overhead_ratio - 0.0).abs() < f32::EPSILON,
            "empty file should have 0.0 overhead_ratio"
        );

        let sidecar = FsviProtector::sidecar_path(&path);
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&sidecar);
    }

    #[test]
    fn repair_result_hashes_differ_on_corruption() {
        let protector = make_protector();
        let path = temp_path("hash-diff");

        let payload = vec![77_u8; 600];
        std::fs::write(&path, &payload).expect("write");
        let protection = protector.protect_atomic(&path).expect("protect");

        // Corrupt
        std::fs::write(&path, vec![0_u8; 600]).expect("corrupt");

        let repair = protector.repair(&path).expect("repair");
        assert_ne!(
            repair.source_hash_before, repair.source_hash_after,
            "corrupted vs repaired hashes should differ"
        );
        assert!(repair.bytes_written > 0);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&protection.sidecar_path);
        let backup = PathBuf::from(format!("{}.corrupted", path.display()));
        let _ = std::fs::remove_file(&backup);
    }

    #[test]
    fn protect_different_payloads_produce_different_hashes() {
        let protector = make_protector();
        let path = temp_path("diff-hash");

        std::fs::write(&path, vec![1_u8; 500]).expect("write 1");
        let result1 = protector.protect_atomic(&path).expect("protect 1");
        let hash1 = result1.source_hash;

        std::fs::write(&path, vec![2_u8; 500]).expect("write 2");
        let result2 = protector.protect_atomic(&path).expect("protect 2");
        let hash2 = result2.source_hash;

        assert_ne!(
            hash1, hash2,
            "different payloads should produce different hashes"
        );

        let sidecar = FsviProtector::sidecar_path(&path);
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&sidecar);
        let _ = std::fs::remove_file(PathBuf::from(format!("{}.bak", sidecar.display())));
    }

    #[test]
    fn metrics_count_after_multiple_protect() {
        let protector = make_protector();
        let path = temp_path("multi-metrics");

        std::fs::write(&path, vec![10_u8; 256]).expect("write");
        protector.protect_atomic(&path).expect("protect 1");
        protector.protect_atomic(&path).expect("protect 2");
        protector.protect_atomic(&path).expect("protect 3");

        let snap = protector.metrics_snapshot();
        assert!(
            snap.encode_ops >= 3,
            "expected at least 3 encode ops, got {}",
            snap.encode_ops
        );

        let sidecar = FsviProtector::sidecar_path(&path);
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&sidecar);
        let _ = std::fs::remove_file(PathBuf::from(format!("{}.bak", sidecar.display())));
    }

    #[test]
    fn fsvi_protection_result_debug() {
        let result = super::FsviProtectionResult {
            sidecar_path: PathBuf::from("/tmp/t.fec"),
            source_size: 100,
            repair_size: 20,
            overhead_ratio: 0.2,
            k_source: 1,
            r_repair: 1,
            source_hash: 999,
            encode_time: std::time::Duration::from_nanos(500),
        };
        let debug = format!("{result:?}");
        assert!(debug.contains("FsviProtectionResult"));
        assert!(debug.contains("source_size"));
    }

    #[test]
    fn fsvi_repair_result_debug() {
        let result = super::FsviRepairResult {
            bytes_written: 100,
            symbols_used: 2,
            decode_time: std::time::Duration::from_millis(1),
            source_hash_before: 1,
            source_hash_after: 2,
        };
        let debug = format!("{result:?}");
        assert!(debug.contains("FsviRepairResult"));
        assert!(debug.contains("bytes_written"));
    }

    // ─── bd-c2u4 tests end ───
}