rustfs-common 1.0.1

Common utilities and data structures for RustFS, providing shared functionality across the project.
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
// 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.

//! Mission Repair Feed (MRF) intent channel.
//!
//! Producers on error paths (read decode failure, scanner metadata
//! corruption, partial-write recovery) hand a lightweight [`MrfIntent`] to the
//! heal crate through a global bounded channel. Hint delivery is strictly
//! non-blocking: `try_send_mrf_intent` never awaits and drops the intent
//! (counting it) when the channel is full or uninitialized — losing one heal
//! hint is always preferred over stalling an IO path. Durable replay of
//! unconsumed intents is the consumer's job (see `rustfs-heal`
//! `heal::mrf_queue`), mirroring MinIO's `.heal/mrf/list.bin`. Committed partial
//! writes and committed partial delete-marker purges use a separate bounded
//! channel and await a checkpoint receipt; ordinary complete writes do not use
//! it.

use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
use std::sync::{
    Arc, Mutex, OnceLock,
    atomic::{AtomicBool, Ordering},
};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;

/// Bounded capacity of the global MRF channel. Backpressure is resolved by
/// dropping (and counting) intents, never by blocking the producer.
const MRF_CHANNEL_CAPACITY: usize = 8192;
const MRF_COALESCER_SHARDS: usize = 16;
const MRF_COALESCER_MAX_KEYS: usize = 8192;
const MRF_COALESCER_MAX_BYTES: usize = 16 * 1024 * 1024;
const MRF_COALESCER_TTL: Duration = Duration::from_secs(60);
const MRF_MAX_IDENTITY_COMPONENT: usize = 1024;
pub const MRF_MAX_DELETE_MARKER_BYTES: usize = 1024 * 1024;

/// Why an intent was produced. Drives the heal priority mapping on the
/// consumer side.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MrfKind {
    /// Erasure decode failed while serving a read (read path).
    DecodeFailure,
    /// Scanner classified object metadata as corrupt.
    MetadataCorruption,
    /// A write left the object with fewer committed shards than the set size.
    PartialWrite,
    /// A committed explicit delete-marker purge missed at least one member.
    DeleteMarkerPurge,
}

impl MrfKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            MrfKind::DecodeFailure => "decode-failure",
            MrfKind::MetadataCorruption => "metadata-corruption",
            MrfKind::PartialWrite => "partial-write",
            MrfKind::DeleteMarkerPurge => "delete-marker-purge",
        }
    }

    pub const fn is_durable(self) -> bool {
        matches!(self, Self::PartialWrite | Self::DeleteMarkerPurge)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MrfDeleteMarkerPurgeIdentity {
    pub bucket_incarnation_id: Uuid,
    pub marker_incarnation_id: Uuid,
    pub marker_identity: [u8; 32],
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MrfDeleteMarkerPurge {
    pub bucket_incarnation_id: Uuid,
    pub marker_incarnation_id: Uuid,
    pub marker_identity: [u8; 32],
    pub marker: Arc<[u8]>,
}

impl MrfDeleteMarkerPurge {
    pub fn new(
        bucket_incarnation_id: Uuid,
        marker_incarnation_id: Uuid,
        marker_identity: [u8; 32],
        marker: Vec<u8>,
    ) -> Option<Self> {
        let payload = Self {
            bucket_incarnation_id,
            marker_incarnation_id,
            marker_identity,
            marker: Arc::from(marker),
        };
        payload.is_valid().then_some(payload)
    }

    pub const fn identity(&self) -> MrfDeleteMarkerPurgeIdentity {
        MrfDeleteMarkerPurgeIdentity {
            bucket_incarnation_id: self.bucket_incarnation_id,
            marker_incarnation_id: self.marker_incarnation_id,
            marker_identity: self.marker_identity,
        }
    }

    pub fn is_valid(&self) -> bool {
        !self.bucket_incarnation_id.is_nil()
            && self.marker_incarnation_id == self.bucket_incarnation_id
            && !self.marker.is_empty()
            && self.marker.len() <= MRF_MAX_DELETE_MARKER_BYTES
    }
}

/// One repair intent. Kept deliberately small so the in-memory queue and the
/// journal stay bounded; `bucket`/`object` are `Arc<str>` so re-arming an
/// intent never re-allocates the strings.
#[derive(Clone, Debug)]
pub struct MrfIntent {
    pub bucket: Arc<str>,
    pub object: Arc<str>,
    /// Version the intent targets, as raw UUID bytes.
    pub version_id: Option<[u8; 16]>,
    pub kind: MrfKind,
    /// Present only for [`MrfKind::DeleteMarkerPurge`]. The encoded marker is a
    /// destructive-operation precondition, while `marker_identity` is its
    /// deterministic queue and proof identity.
    pub delete_marker_purge: Option<MrfDeleteMarkerPurge>,
    /// Stable erasure-set scope when the producer has it. Kept optional so
    /// metadata corruption and legacy producers do not invent a scope.
    pub scope: Option<MrfScope>,
    /// Generation of the node-local ingress lease. It is not persisted in
    /// the journal; replayed records acquire a fresh lease when re-enqueued.
    pub lease: Option<MrfIngressLease>,
    pub enqueued_at_ms: u64,
    /// Times this intent has already been offered to the heal manager.
    /// Dropped by the consumer once it reaches `MRF_MAX_ATTEMPTS`.
    pub attempts: u8,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MrfDurableRepairAnchor {
    pub kind: MrfKind,
    pub bucket: Arc<str>,
    pub object: Arc<str>,
    pub version_id: Option<[u8; 16]>,
    pub scope: Option<MrfScope>,
    pub delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
    pub lease: MrfIngressLease,
    pub bucket_incarnation_id: Uuid,
}

/// A completed deep check proved that a legacy object is present and healthy,
/// but the format has no independent identity commitment that can discharge a
/// durable partial-write responsibility. Keep the journal entry and pause
/// automatic retries until an operator has repaired the source of truth.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MrfUnverifiedLegacyEvent {
    pub anchor: MrfDurableRepairAnchor,
}

impl MrfDurableRepairAnchor {
    /// Build a dischargeable anchor only when the caller supplies the storage
    /// incarnation and the original ingress lease. Legacy replay records lack
    /// both pieces and therefore remain fail-closed.
    pub fn from_intent(intent: &MrfIntent, bucket_incarnation_id: Uuid) -> Option<Self> {
        let lease = intent.lease?;
        let (version_id, scope) = canonical_identity(intent.kind, intent.version_id, intent.scope);
        let delete_marker_purge = canonical_delete_marker_purge_identity(intent)?;
        let bucket_incarnation_id = delete_marker_purge
            .map(|identity| identity.bucket_incarnation_id)
            .unwrap_or(bucket_incarnation_id);
        if bucket_incarnation_id.is_nil() {
            return None;
        }
        Some(Self {
            kind: intent.kind,
            bucket: intent.bucket.clone(),
            object: intent.object.clone(),
            version_id,
            scope,
            delete_marker_purge,
            lease,
            bucket_incarnation_id,
        })
    }

    pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
        let Some(lease) = event.lease else {
            return false;
        };
        self.kind == event.kind
            && self.bucket == event.bucket
            && self.object == event.object
            && self.version_id == event.version_id
            && self.scope == event.scope
            && self.delete_marker_purge == event.delete_marker_purge
            && self.lease == lease
            && self.bucket_incarnation_id == event.bucket_incarnation_id
    }
}

/// Consume only anchors proven by a complete verified-repair identity. The
/// caller remains responsible for persisting the resulting anchor set before
/// deleting older replay files.
pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>, events: &[MrfVerifiedRepairEvent]) -> usize {
    let before = anchors.len();
    anchors.retain(|anchor| !events.iter().any(|event| anchor.is_proven_by(event)));
    before.saturating_sub(anchors.len())
}

/// Consume recorded verified repairs for one bucket without draining
/// unrelated or still-unmatched proofs. If the caller crashes before
/// persisting the retained anchor set, the proof may be replayed by repair
/// instead of silently deleting the old responsibility.
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
    let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
        return 0;
    };
    let Ok(mut events) = registry.lock() else {
        return 0;
    };
    let before = anchors.len();
    let mut retained = std::collections::VecDeque::with_capacity(events.len());
    while let Some(event) = events.pop_front() {
        if event.bucket.as_ref() != bucket {
            retained.push_back(event);
            continue;
        }
        let mut matched = false;
        anchors.retain(|anchor| {
            let proven = anchor.is_proven_by(&event);
            matched |= proven;
            !proven
        });
        if !matched {
            retained.push_back(event);
        }
    }
    *events = retained;
    before.saturating_sub(anchors.len())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MrfScope {
    pub pool_index: u32,
    pub set_index: u32,
}

/// Opaque generation used to release exactly the admission that created an
/// ingress entry. A generation prevents a late terminal callback from
/// deleting a newer retry for the same identity (ABA).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MrfIngressLease(u64);

impl MrfIngressLease {
    const fn new(value: u64) -> Self {
        Self(value)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MrfDropReason {
    Disabled,
    Uninitialized,
    Full,
    OversizedIdentity,
    InvalidPayload,
    CoalescerFull,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MrfIngressResult {
    Enqueued,
    Coalesced,
    Dropped(MrfDropReason),
}

/// Consumer-side retry ceiling before an intent is given up on.
pub const MRF_MAX_ATTEMPTS: u8 = 3;

impl MrfIntent {
    /// Rough in-memory footprint used by the queue's byte budget.
    pub fn estimated_bytes(&self) -> usize {
        // Struct + strings + version bytes; buckets and objects are usually
        // far below this bound, so rounding up keeps the budget conservative.
        64usize
            .saturating_add(self.bucket.len())
            .saturating_add(self.object.len())
            .saturating_add(
                self.delete_marker_purge
                    .as_ref()
                    .map_or(0, |purge| std::mem::size_of::<MrfDeleteMarkerPurge>().saturating_add(purge.marker.len())),
            )
    }
}

static GLOBAL_MRF_SENDER: OnceLock<mpsc::Sender<MrfIntent>> = OnceLock::new();

static GLOBAL_DURABLE_MRF_SENDER: OnceLock<mpsc::Sender<MrfDurableSubmission>> = OnceLock::new();

#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum MrfDurableAdmissionError {
    #[error("MRF delivery is disabled")]
    Disabled,
    #[error("MRF durable consumer is unavailable")]
    Unavailable,
    #[error("MRF responsibility capacity is exhausted")]
    Full,
    #[error("MRF responsibility identity is invalid or oversized")]
    InvalidIdentity,
    #[error("MRF responsibility checkpoint could not be persisted")]
    Persistence,
    #[error("MRF durable admission timed out; responsibility may still be retained")]
    Timeout,
}

/// A committed storage responsibility awaiting a durable checkpoint, separate
/// from the best-effort read/scanner channel. Dropping the reply does not
/// cancel repair.
pub struct MrfDurableSubmission {
    pub intent: MrfIntent,
    /// Bucket incarnation observed by the committed-write caller, when
    /// available. Old journal records and legacy callers remain unbound.
    pub source_bucket_incarnation_id: Option<Uuid>,
    pub response: oneshot::Sender<Result<(), MrfDurableAdmissionError>>,
}

pub fn init_durable_mrf_channel() -> Result<mpsc::Receiver<MrfDurableSubmission>, &'static str> {
    let (sender, receiver) = mpsc::channel(MRF_CHANNEL_CAPACITY);
    GLOBAL_DURABLE_MRF_SENDER
        .set(sender)
        .map_err(|_| "MRF durable channel sender already initialized")?;
    Ok(receiver)
}

/// Wait for checkpoint publication on a committed partial-write path. Every
/// write gets a fresh lease: a previous repair of the same unversioned key
/// cannot discharge a later overwrite. An error is not durable admission.
pub async fn persist_partial_write_intent(
    bucket: &str,
    object: &str,
    version_id: Option<Uuid>,
    scope: MrfScope,
) -> Result<(), MrfDurableAdmissionError> {
    persist_partial_write_intent_with_incarnation(bucket, object, version_id, scope, None).await
}

pub async fn persist_partial_write_intent_with_incarnation(
    bucket: &str,
    object: &str,
    version_id: Option<Uuid>,
    scope: MrfScope,
    source_bucket_incarnation_id: Option<Uuid>,
) -> Result<(), MrfDurableAdmissionError> {
    if source_bucket_incarnation_id.is_some_and(|incarnation| incarnation.is_nil()) {
        return Err(MrfDurableAdmissionError::InvalidIdentity);
    }
    let intent = MrfIntent {
        bucket: Arc::from(bucket),
        object: Arc::from(object),
        version_id: canonical_version(version_id),
        kind: MrfKind::PartialWrite,
        delete_marker_purge: None,
        scope: Some(scope),
        lease: None,
        enqueued_at_ms: unix_now_ms(),
        attempts: 0,
    };
    persist_durable_intent(intent, source_bucket_incarnation_id).await
}

pub async fn persist_delete_marker_purge_intent(
    bucket: &str,
    object: &str,
    version_id: Uuid,
    scope: MrfScope,
    delete_marker_purge: MrfDeleteMarkerPurge,
) -> Result<(), MrfDurableAdmissionError> {
    if version_id.is_nil() {
        return Err(MrfDurableAdmissionError::InvalidIdentity);
    }
    let source_bucket_incarnation_id = delete_marker_purge.bucket_incarnation_id;
    let intent = MrfIntent {
        bucket: Arc::from(bucket),
        object: Arc::from(object),
        version_id: canonical_version(Some(version_id)),
        kind: MrfKind::DeleteMarkerPurge,
        delete_marker_purge: Some(delete_marker_purge),
        scope: Some(scope),
        lease: None,
        enqueued_at_ms: unix_now_ms(),
        attempts: 0,
    };
    persist_durable_intent_unconditionally(intent, Some(source_bucket_incarnation_id)).await
}

async fn persist_durable_intent(
    intent: MrfIntent,
    source_bucket_incarnation_id: Option<Uuid>,
) -> Result<(), MrfDurableAdmissionError> {
    if !mrf_delivery_enabled() {
        return Err(MrfDurableAdmissionError::Disabled);
    }
    persist_durable_intent_unconditionally(intent, source_bucket_incarnation_id).await
}

async fn persist_durable_intent_unconditionally(
    mut intent: MrfIntent,
    source_bucket_incarnation_id: Option<Uuid>,
) -> Result<(), MrfDurableAdmissionError> {
    if intent.bucket.is_empty()
        || intent.object.is_empty()
        || intent.bucket.len() > MRF_MAX_IDENTITY_COMPONENT
        || intent.object.len() > MRF_MAX_IDENTITY_COMPONENT
        || !valid_intent_payload(&intent)
    {
        return Err(MrfDurableAdmissionError::InvalidIdentity);
    }
    let sender = GLOBAL_DURABLE_MRF_SENDER.get().ok_or(MrfDurableAdmissionError::Unavailable)?;
    if try_rearm_mrf_replay_intent(&mut intent) != MrfIngressResult::Enqueued {
        return Err(MrfDurableAdmissionError::InvalidIdentity);
    }
    let (response, receipt) = oneshot::channel();
    sender
        .try_send(MrfDurableSubmission {
            intent,
            source_bucket_incarnation_id,
            response,
        })
        .map_err(|err| match err {
            mpsc::error::TrySendError::Full(_) => MrfDurableAdmissionError::Full,
            mpsc::error::TrySendError::Closed(_) => MrfDurableAdmissionError::Unavailable,
        })?;
    tokio::time::timeout(Duration::from_secs(10), receipt)
        .await
        .map_err(|_| MrfDurableAdmissionError::Timeout)?
        .map_err(|_| MrfDurableAdmissionError::Unavailable)?
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct MrfIdentityKey {
    kind: MrfKind,
    bucket: Arc<str>,
    object: Arc<str>,
    version_id: Option<[u8; 16]>,
    scope: Option<MrfScope>,
}

#[derive(Debug)]
struct IngressEntry {
    lease: MrfIngressLease,
    expires_at: Instant,
    bytes: usize,
}

type MrfCoalescerShard = Mutex<HashMap<MrfIdentityKey, IngressEntry>>;
type MrfCoalescer = Box<[MrfCoalescerShard]>;

static MRF_COALESCER: OnceLock<MrfCoalescer> = OnceLock::new();
static NEXT_MRF_LEASE: AtomicU64 = AtomicU64::new(1);
static MRF_COALESCER_COUNT: AtomicUsize = AtomicUsize::new(0);
static MRF_COALESCER_BYTES: AtomicUsize = AtomicUsize::new(0);
static MRF_HASH_STATE: OnceLock<RandomState> = OnceLock::new();

fn coalescer() -> &'static [MrfCoalescerShard] {
    MRF_COALESCER.get_or_init(|| {
        (0..MRF_COALESCER_SHARDS)
            .map(|_| Mutex::new(HashMap::new()))
            .collect::<Vec<_>>()
            .into_boxed_slice()
    })
}

fn key_shard(key: &MrfIdentityKey) -> usize {
    let hash = MRF_HASH_STATE.get_or_init(RandomState::new).hash_one(key);
    usize::try_from(hash).unwrap_or(0) % MRF_COALESCER_SHARDS
}

fn canonical_version(version_id: Option<Uuid>) -> Option<[u8; 16]> {
    version_id
        .filter(|version| !version.is_nil())
        .map(|version| *version.as_bytes())
}

fn canonical_identity(
    kind: MrfKind,
    version_id: Option<[u8; 16]>,
    scope: Option<MrfScope>,
) -> (Option<[u8; 16]>, Option<MrfScope>) {
    let version_id = version_id.filter(|bytes| *bytes != [0; 16]);
    match kind {
        MrfKind::MetadataCorruption => (None, None),
        MrfKind::DecodeFailure | MrfKind::PartialWrite | MrfKind::DeleteMarkerPurge => (version_id, scope),
    }
}

fn canonical_delete_marker_purge_identity(intent: &MrfIntent) -> Option<Option<MrfDeleteMarkerPurgeIdentity>> {
    match intent.kind {
        MrfKind::DeleteMarkerPurge => intent
            .delete_marker_purge
            .as_ref()
            .filter(|payload| payload.is_valid())
            .map(|payload| Some(payload.identity())),
        _ if intent.delete_marker_purge.is_none() => Some(None),
        _ => None,
    }
}

fn valid_intent_payload(intent: &MrfIntent) -> bool {
    canonical_delete_marker_purge_identity(intent).is_some()
        && (intent.kind != MrfKind::DeleteMarkerPurge || (intent.version_id.is_some() && intent.scope.is_some()))
}

fn identity_estimated_bytes(key: &MrfIdentityKey) -> usize {
    64usize
        .saturating_add(key.bucket.len())
        .saturating_add(key.object.len())
        .saturating_add(key.version_id.map_or(0, |_| 16))
        .saturating_add(key.scope.map_or(0, |_| 8))
}

fn reserve(counter: &AtomicUsize, limit: usize, amount: usize) -> bool {
    let mut current = counter.load(Ordering::Relaxed);
    loop {
        let Some(next) = current.checked_add(amount) else {
            return false;
        };
        if next > limit {
            return false;
        }
        match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
            Ok(_) => return true,
            Err(observed) => current = observed,
        }
    }
}

fn coalescer_admit(key: MrfIdentityKey) -> Result<MrfIngressLease, MrfIngressResult> {
    let shard = key_shard(&key);
    let mut entries = coalescer()[shard]
        .lock()
        .map_err(|_| MrfIngressResult::Dropped(MrfDropReason::CoalescerFull))?;
    let now = Instant::now();
    let before = entries.len();
    let mut expired_bytes = 0usize;
    entries.retain(|_, entry| {
        if entry.expires_at > now {
            true
        } else {
            expired_bytes = expired_bytes.saturating_add(entry.bytes);
            false
        }
    });
    let evicted = before.saturating_sub(entries.len());
    if evicted > 0 {
        MRF_COALESCER_COUNT.fetch_sub(evicted, Ordering::Relaxed);
        MRF_COALESCER_BYTES.fetch_sub(expired_bytes, Ordering::Relaxed);
        let evicted = u64::try_from(evicted).unwrap_or(u64::MAX);
        metrics::counter!("rustfs_heal_mrf_coalescer_expired_total").increment(evicted);
        metrics::counter!("rustfs_heal_mrf_coalescer_evictions_total").increment(evicted);
    }
    if entries.contains_key(&key) {
        metrics::counter!("rustfs_heal_mrf_coalesced_total").increment(1);
        return Err(MrfIngressResult::Coalesced);
    }
    let bytes = identity_estimated_bytes(&key);
    let count_reserved = reserve(&MRF_COALESCER_COUNT, MRF_COALESCER_MAX_KEYS, 1);
    let bytes_reserved = count_reserved && reserve(&MRF_COALESCER_BYTES, MRF_COALESCER_MAX_BYTES, bytes);
    if !count_reserved || !bytes_reserved {
        if count_reserved {
            MRF_COALESCER_COUNT.fetch_sub(1, Ordering::Relaxed);
        }
        metrics::counter!("rustfs_heal_mrf_dropped_total", "reason" => "coalescer_full").increment(1);
        return Err(MrfIngressResult::Dropped(MrfDropReason::CoalescerFull));
    }
    let lease = MrfIngressLease::new(NEXT_MRF_LEASE.fetch_add(1, Ordering::Relaxed));
    if entries
        .insert(
            key,
            IngressEntry {
                lease,
                expires_at: now + MRF_COALESCER_TTL,
                bytes,
            },
        )
        .is_some()
    {
        MRF_COALESCER_COUNT.fetch_sub(1, Ordering::Relaxed);
        MRF_COALESCER_BYTES.fetch_sub(bytes, Ordering::Relaxed);
        metrics::counter!("rustfs_heal_mrf_coalesced_total").increment(1);
        return Err(MrfIngressResult::Coalesced);
    }
    Ok(lease)
}

fn coalescer_release(key: &MrfIdentityKey, lease: Option<MrfIngressLease>) {
    let Some(lease) = lease else {
        return;
    };
    if let Ok(mut entries) = coalescer()[key_shard(key)].lock() {
        let should_remove = entries.get(key).is_some_and(|entry| entry.lease == lease);
        if should_remove {
            let bytes = entries.remove(key).map(|entry| entry.bytes).unwrap_or(0);
            MRF_COALESCER_COUNT.fetch_sub(1, Ordering::Relaxed);
            MRF_COALESCER_BYTES.fetch_sub(bytes, Ordering::Relaxed);
        }
    }
}

/// Delivery kill-switch, set from `RUSTFS_HEAL_MRF_ENABLE`. Producers check
/// this before touching the channel so the disabled path stays allocation- and
/// sync-free.
static MRF_DELIVERY_ENABLED: AtomicBool = AtomicBool::new(true);

/// Override delivery (used at heal-runtime startup from configuration).
pub fn set_mrf_delivery_enabled(enabled: bool) {
    MRF_DELIVERY_ENABLED.store(enabled, Ordering::Relaxed);
}

/// Whether producers currently deliver intents.
pub fn mrf_delivery_enabled() -> bool {
    MRF_DELIVERY_ENABLED.load(Ordering::Relaxed)
}

/// Create the global MRF channel and return the consumer half. Fails if the
/// channel is already initialized (the heal runtime is a singleton).
pub fn init_mrf_channel() -> Result<mpsc::Receiver<MrfIntent>, &'static str> {
    let (sender, receiver) = mpsc::channel(MRF_CHANNEL_CAPACITY);
    GLOBAL_MRF_SENDER
        .set(sender)
        .map_err(|_| "MRF channel sender already initialized")?;
    Ok(receiver)
}

/// Best-effort, non-blocking intent delivery from an error path.
///
/// Returns `true` when the intent was accepted into the channel. `false`
/// means the intent was dropped (feature disabled, channel not yet
/// initialized, or channel full) — callers must not retry or await; the
/// existing read-repair / scanner heal paths remain the safety net.
///
/// This runs on IO error paths, so it stays synchronous and cheap: one
/// bounded allocation for the two `Arc<str>` handles plus the channel slot.
pub fn try_send_mrf_intent(kind: MrfKind, bucket: &str, object: &str, version_id: Option<Uuid>) -> bool {
    matches!(
        try_send_mrf_intent_typed(kind, bucket, object, version_id, None),
        MrfIngressResult::Enqueued
    )
}

/// Typed ingress result. `Coalesced` means an equivalent in-flight channel
/// intent already exists; it is not a second executable or durable admission.
pub fn try_send_mrf_intent_typed(
    kind: MrfKind,
    bucket: &str,
    object: &str,
    version_id: Option<Uuid>,
    scope: Option<MrfScope>,
) -> MrfIngressResult {
    if !mrf_delivery_enabled() {
        return MrfIngressResult::Dropped(MrfDropReason::Disabled);
    }
    if kind == MrfKind::DeleteMarkerPurge {
        return MrfIngressResult::Dropped(MrfDropReason::InvalidPayload);
    }
    let Some(sender) = GLOBAL_MRF_SENDER.get() else {
        return MrfIngressResult::Dropped(MrfDropReason::Uninitialized);
    };
    if bucket.len() > MRF_MAX_IDENTITY_COMPONENT || object.len() > MRF_MAX_IDENTITY_COMPONENT {
        return MrfIngressResult::Dropped(MrfDropReason::OversizedIdentity);
    }
    let (version_id, scope) = canonical_identity(kind, canonical_version(version_id), scope);
    let key = MrfIdentityKey {
        kind,
        bucket: Arc::from(bucket),
        object: Arc::from(object),
        version_id,
        scope,
    };
    let lease = match coalescer_admit(key.clone()) {
        Ok(lease) => lease,
        Err(result) => return result,
    };
    let intent = MrfIntent {
        bucket: key.bucket.clone(),
        object: key.object.clone(),
        version_id: key.version_id,
        kind,
        delete_marker_purge: None,
        scope,
        lease: Some(lease),
        enqueued_at_ms: unix_now_ms(),
        attempts: 0,
    };
    match sender.try_send(intent) {
        Ok(()) => MrfIngressResult::Enqueued,
        Err(mpsc::error::TrySendError::Full(_)) => {
            coalescer_release(&key, Some(lease));
            metrics::counter!("rustfs_heal_mrf_dropped_total", "reason" => "channel_full").increment(1);
            MrfIngressResult::Dropped(MrfDropReason::Full)
        }
        Err(mpsc::error::TrySendError::Closed(_)) => {
            coalescer_release(&key, Some(lease));
            MrfIngressResult::Dropped(MrfDropReason::Uninitialized)
        }
    }
}

/// Acquire a fresh process-local lease for one durable replay record.
///
/// Journal records deliberately do not persist leases. A replay consumer must
/// call this before submitting the record so a later verified repair event can
/// identify the exact replay admission. Replay does not reserve the live
/// producer coalescer key: the replay queue first deduplicates legacy records,
/// then manager admission owns task-level deduplication with live producers.
pub fn try_rearm_mrf_replay_intent(intent: &mut MrfIntent) -> MrfIngressResult {
    if intent.bucket.len() > MRF_MAX_IDENTITY_COMPONENT || intent.object.len() > MRF_MAX_IDENTITY_COMPONENT {
        return MrfIngressResult::Dropped(MrfDropReason::OversizedIdentity);
    }
    let (version_id, scope) = canonical_identity(intent.kind, intent.version_id, intent.scope);
    intent.version_id = version_id;
    intent.scope = scope;
    if !valid_intent_payload(intent) {
        return MrfIngressResult::Dropped(MrfDropReason::InvalidPayload);
    }
    if intent.lease.is_some() {
        return MrfIngressResult::Enqueued;
    }
    intent.lease = Some(MrfIngressLease::new(NEXT_MRF_LEASE.fetch_add(1, Ordering::Relaxed)));
    MrfIngressResult::Enqueued
}

/// Release the ingress key once the consumer owns the intent.
pub fn release_mrf_intent(intent: &MrfIntent) {
    release_mrf_identity(intent.kind, &intent.bucket, &intent.object, intent.version_id, intent.scope, intent.lease);
}

pub fn release_mrf_identity(
    kind: MrfKind,
    bucket: &str,
    object: &str,
    version_id: Option<[u8; 16]>,
    scope: Option<MrfScope>,
    lease: Option<MrfIngressLease>,
) {
    let (version_id, scope) = canonical_identity(kind, version_id, scope);
    coalescer_release(
        &MrfIdentityKey {
            kind,
            bucket: Arc::from(bucket),
            object: Arc::from(object),
            version_id,
            scope,
        },
        lease,
    );
}

fn unix_now_ms() -> u64 {
    // Kept trivial: the timestamp is diagnostic metadata only; wall-clock
    // failure would be a bug rather than something to handle here.
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .and_then(|d| u64::try_from(d.as_millis()).ok())
        .unwrap_or(0)
}

/// Legacy, unverified repair notice. Its identity lacks kind, set scope,
/// bucket incarnation and responsibility generation. Consumers must not use
/// it to discharge persisted repair responsibility.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MrfRepairedEvent {
    pub bucket: Arc<str>,
    pub object: Arc<str>,
    pub version_id: Option<[u8; 16]>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MrfVerifiedRepairDisposition {
    Repaired,
    VerifiedHealthy,
    AuthoritativelyAbsent,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MrfVerifiedRepairEvent {
    pub kind: MrfKind,
    pub bucket: Arc<str>,
    pub object: Arc<str>,
    pub version_id: Option<[u8; 16]>,
    pub scope: Option<MrfScope>,
    pub delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
    pub lease: Option<MrfIngressLease>,
    pub bucket_incarnation_id: Uuid,
    pub disposition: MrfVerifiedRepairDisposition,
}

/// Bound on the repaired-event backlog. Notices are best-effort hints; when
/// the ring is full the oldest are dropped and the affected ledger entries
/// simply expire through their own attempts/age limits.
const MRF_REPAIRED_EVENT_CAP: usize = 4096;

static MRF_REPAIRED_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfRepairedEvent>>> = OnceLock::new();
static MRF_VERIFIED_REPAIR_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfVerifiedRepairEvent>>> =
    OnceLock::new();
static MRF_UNVERIFIED_LEGACY_EVENTS: OnceLock<std::sync::Mutex<std::collections::VecDeque<MrfUnverifiedLegacyEvent>>> =
    OnceLock::new();

/// Record a legacy notification for compatibility. This is not an
/// acknowledgement of storage verification or durable repair completion.
pub fn note_mrf_repaired(bucket: &str, object: &str, version_id: Option<[u8; 16]>) {
    let registry = MRF_REPAIRED_EVENTS.get_or_init(|| std::sync::Mutex::new(std::collections::VecDeque::new()));
    let Ok(mut events) = registry.lock() else {
        return;
    };
    if events.len() >= MRF_REPAIRED_EVENT_CAP {
        events.pop_front();
    }
    events.push_back(MrfRepairedEvent {
        bucket: Arc::from(bucket),
        object: Arc::from(object),
        version_id,
    });
}

/// Take the repair notices recorded for `bucket`, leaving other buckets'
/// notices in place for their own scanners.
pub fn take_mrf_repaired_events_for(bucket: &str) -> Vec<MrfRepairedEvent> {
    let Some(registry) = MRF_REPAIRED_EVENTS.get() else {
        return Vec::new();
    };
    let Ok(mut events) = registry.lock() else {
        return Vec::new();
    };
    let mut taken = Vec::new();
    let mut retained = std::collections::VecDeque::with_capacity(events.len());
    while let Some(event) = events.pop_front() {
        if event.bucket.as_ref() == bucket {
            taken.push(event);
        } else {
            retained.push_back(event);
        }
    }
    *events = retained;
    taken
}

/// Record a storage-owned MRF completion proof. Unlike the legacy repaired
/// event, this identity is complete enough for future durable ledgers to make
/// an exact responsibility decision.
pub fn note_mrf_verified_repair(event: MrfVerifiedRepairEvent) {
    let registry = MRF_VERIFIED_REPAIR_EVENTS.get_or_init(|| std::sync::Mutex::new(std::collections::VecDeque::new()));
    let Ok(mut events) = registry.lock() else {
        return;
    };
    if events.len() >= MRF_REPAIRED_EVENT_CAP {
        events.pop_front();
    }
    events.push_back(event);
}

/// Take verified repair events recorded for `bucket`, leaving other buckets'
/// proofs in place. Consumers still have to match kind, object, version, scope
/// lease and incarnation before discharging durable responsibility.
pub fn take_mrf_verified_repair_events_for(bucket: &str) -> Vec<MrfVerifiedRepairEvent> {
    let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
        return Vec::new();
    };
    let Ok(mut events) = registry.lock() else {
        return Vec::new();
    };
    let mut taken = Vec::new();
    let mut retained = std::collections::VecDeque::with_capacity(events.len());
    while let Some(event) = events.pop_front() {
        if event.bucket.as_ref() == bucket {
            taken.push(event);
        } else {
            retained.push_back(event);
        }
    }
    *events = retained;
    taken
}

/// Record a bounded, exact-identity notice that a legacy durable partial-write
/// was checked but cannot be proven from its on-disk format. This is not a
/// repair proof and must never release the durable responsibility.
pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
    let registry = MRF_UNVERIFIED_LEGACY_EVENTS.get_or_init(|| std::sync::Mutex::new(std::collections::VecDeque::new()));
    let Ok(mut events) = registry.lock() else {
        return;
    };
    if events.contains(&event) {
        return;
    }
    if events.len() >= MRF_REPAIRED_EVENT_CAP {
        events.pop_front();
    }
    events.push_back(event);
}

/// Take held-legacy notices for one bucket. The durable ledger still verifies
/// the full anchor before changing the journal entry to its held state.
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
    let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
        return Vec::new();
    };
    let Ok(mut events) = registry.lock() else {
        return Vec::new();
    };
    let mut taken = Vec::new();
    events.retain(|event| {
        if event.anchor.bucket.as_ref() == bucket {
            taken.push(event.clone());
            false
        } else {
            true
        }
    });
    taken
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn intents_estimate_is_conservative() {
        let intent = MrfIntent {
            bucket: Arc::from("bucket"),
            object: Arc::from("object"),
            version_id: Some([0u8; 16]),
            kind: MrfKind::DecodeFailure,
            delete_marker_purge: None,
            scope: None,
            lease: None,
            enqueued_at_ms: 0,
            attempts: 0,
        };
        assert!(intent.estimated_bytes() >= intent.bucket.len() + intent.object.len());
    }

    #[test]
    fn ingress_duplicate_identity_coalesces_and_releases_for_retry() {
        let key = MrfIdentityKey {
            kind: MrfKind::DecodeFailure,
            bucket: Arc::from("ingress-test-bucket"),
            object: Arc::from("ingress-test-object"),
            version_id: Some([9; 16]),
            scope: Some(MrfScope {
                pool_index: 3,
                set_index: 4,
            }),
        };
        let lease = coalescer_admit(key.clone()).expect("first identity should be admitted");
        for _ in 0..999 {
            assert_eq!(coalescer_admit(key.clone()), Err(MrfIngressResult::Coalesced));
        }
        coalescer_release(&key, Some(lease));
        let retry_lease = coalescer_admit(key.clone()).expect("released identity must admit a retry");
        assert_ne!(lease, retry_lease);
        coalescer_release(&key, Some(lease));
        assert_eq!(coalescer_admit(key.clone()), Err(MrfIngressResult::Coalesced));
        coalescer_release(&key, Some(retry_lease));
    }

    #[test]
    fn ingress_identity_preserves_kind_scope_and_version_boundaries() {
        let (nil_version, nil_scope) = canonical_identity(
            MrfKind::DecodeFailure,
            Some([0; 16]),
            Some(MrfScope {
                pool_index: 1,
                set_index: 2,
            }),
        );
        assert_eq!(nil_version, None, "nil UUID is the unversioned identity");
        assert!(nil_scope.is_some());

        let (metadata_version, metadata_scope) = canonical_identity(
            MrfKind::MetadataCorruption,
            Some([7; 16]),
            Some(MrfScope {
                pool_index: 1,
                set_index: 2,
            }),
        );
        assert_eq!(metadata_version, None);
        assert_eq!(metadata_scope, None);
    }

    #[test]
    fn durable_repair_anchor_requires_lease_and_bucket_incarnation() {
        let mut intent = MrfIntent {
            bucket: Arc::from("durable-anchor-bucket"),
            object: Arc::from("object"),
            version_id: Some([0; 16]),
            kind: MrfKind::PartialWrite,
            delete_marker_purge: None,
            scope: Some(MrfScope {
                pool_index: 1,
                set_index: 2,
            }),
            lease: None,
            enqueued_at_ms: 0,
            attempts: 0,
        };
        assert!(
            MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4()).is_none(),
            "legacy replay records without the ingress lease must remain anchored"
        );

        intent.lease = Some(MrfIngressLease::new(7));
        assert!(
            MrfDurableRepairAnchor::from_intent(&intent, Uuid::nil()).is_none(),
            "nil bucket incarnation cannot prove durable successor ownership"
        );

        let anchor = MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4())
            .expect("complete identity should create a durable repair anchor");
        assert_eq!(anchor.version_id, None, "nil UUID is canonicalized before matching");
        assert_eq!(
            anchor.scope,
            Some(MrfScope {
                pool_index: 1,
                set_index: 2
            })
        );
    }

    #[test]
    fn durable_replay_rearm_assigns_a_fresh_dischargeable_lease() {
        let unique = Uuid::new_v4();
        let mut intent = MrfIntent {
            bucket: Arc::from(format!("replay-{unique}")),
            object: Arc::from("object"),
            version_id: Some([0; 16]),
            kind: MrfKind::PartialWrite,
            delete_marker_purge: None,
            scope: Some(MrfScope {
                pool_index: 2,
                set_index: 3,
            }),
            lease: None,
            enqueued_at_ms: 1,
            attempts: 0,
        };

        assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
        assert_eq!(intent.version_id, None, "nil versions remain canonical during replay");
        assert!(intent.lease.is_some(), "replay admission must carry a fresh lease");
        assert!(
            MrfDurableRepairAnchor::from_intent(&intent, Uuid::new_v4()).is_some(),
            "a rearmed replay record can participate in exact durable proof matching"
        );
        release_mrf_intent(&intent);
    }

    #[test]
    fn verified_repair_events_consume_only_exact_durable_anchors() {
        let bucket = Arc::<str>::from("proof-bucket");
        let object = Arc::<str>::from("object");
        let incarnation = Uuid::new_v4();
        let lease = MrfIngressLease::new(11);
        let anchor = MrfDurableRepairAnchor {
            kind: MrfKind::PartialWrite,
            bucket: bucket.clone(),
            object: object.clone(),
            version_id: Some([3; 16]),
            scope: Some(MrfScope {
                pool_index: 4,
                set_index: 5,
            }),
            delete_marker_purge: None,
            lease,
            bucket_incarnation_id: incarnation,
        };
        let event = MrfVerifiedRepairEvent {
            kind: anchor.kind,
            bucket,
            object,
            version_id: anchor.version_id,
            scope: anchor.scope,
            delete_marker_purge: None,
            lease: Some(lease),
            bucket_incarnation_id: incarnation,
            disposition: MrfVerifiedRepairDisposition::Repaired,
        };

        for rejected in [
            MrfVerifiedRepairEvent {
                lease: None,
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                lease: Some(MrfIngressLease::new(12)),
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                bucket_incarnation_id: Uuid::new_v4(),
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                version_id: Some([4; 16]),
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                scope: Some(MrfScope {
                    pool_index: 4,
                    set_index: 6,
                }),
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                kind: MrfKind::DecodeFailure,
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                bucket: Arc::from("other-bucket"),
                ..event.clone()
            },
            MrfVerifiedRepairEvent {
                object: Arc::from("other"),
                ..event.clone()
            },
        ] {
            let mut retained = vec![anchor.clone()];
            assert_eq!(consume_verified_mrf_repair_events(&mut retained, &[rejected]), 0);
            assert_eq!(retained, vec![anchor.clone()]);
        }

        let mut retained = vec![anchor];
        assert_eq!(consume_verified_mrf_repair_events(&mut retained, &[event]), 1);
        assert!(retained.is_empty());
    }

    #[test]
    fn recorded_verified_repair_consumer_retains_unmatched_proofs() {
        let bucket = Arc::<str>::from(format!("recorded-proof-{}", Uuid::new_v4()));
        let other_bucket = Arc::<str>::from(format!("recorded-proof-other-{}", Uuid::new_v4()));
        let incarnation = Uuid::new_v4();
        let lease = MrfIngressLease::new(21);
        let retained_anchor = MrfDurableRepairAnchor {
            kind: MrfKind::PartialWrite,
            bucket: bucket.clone(),
            object: Arc::from("retained"),
            version_id: Some([7; 16]),
            scope: Some(MrfScope {
                pool_index: 1,
                set_index: 2,
            }),
            delete_marker_purge: None,
            lease,
            bucket_incarnation_id: incarnation,
        };
        let waiting_anchor = MrfDurableRepairAnchor {
            object: Arc::from("waiting"),
            lease: MrfIngressLease::new(22),
            ..retained_anchor.clone()
        };
        let matched_event = MrfVerifiedRepairEvent {
            kind: retained_anchor.kind,
            bucket: bucket.clone(),
            object: retained_anchor.object.clone(),
            version_id: retained_anchor.version_id,
            scope: retained_anchor.scope,
            delete_marker_purge: None,
            lease: Some(retained_anchor.lease),
            bucket_incarnation_id: retained_anchor.bucket_incarnation_id,
            disposition: MrfVerifiedRepairDisposition::Repaired,
        };
        let same_bucket_unmatched = MrfVerifiedRepairEvent {
            object: Arc::from("future"),
            lease: Some(MrfIngressLease::new(23)),
            ..matched_event.clone()
        };
        let other_bucket_event = MrfVerifiedRepairEvent {
            bucket: other_bucket.clone(),
            ..matched_event.clone()
        };

        note_mrf_verified_repair(matched_event);
        note_mrf_verified_repair(same_bucket_unmatched.clone());
        note_mrf_verified_repair(other_bucket_event.clone());

        let mut anchors = vec![retained_anchor, waiting_anchor.clone()];
        assert_eq!(consume_recorded_verified_mrf_repair_events_for(&bucket, &mut anchors), 1);
        assert_eq!(anchors, vec![waiting_anchor]);

        let remaining_bucket_events = take_mrf_verified_repair_events_for(&bucket);
        assert_eq!(
            remaining_bucket_events,
            vec![same_bucket_unmatched],
            "same-bucket proofs without a retained anchor must remain available"
        );
        let remaining_other_events = take_mrf_verified_repair_events_for(&other_bucket);
        assert_eq!(
            remaining_other_events,
            vec![other_bucket_event],
            "proofs for other buckets must not be drained by this consumer"
        );
    }

    #[tokio::test]
    async fn try_send_delivers_and_respects_capacity() {
        let mut receiver = init_mrf_channel().expect("first initialization should succeed");
        assert!(init_mrf_channel().is_err(), "double initialization must fail");

        assert!(try_send_mrf_intent(MrfKind::DecodeFailure, "b", "o", Some(Uuid::nil())));
        let intent = receiver.recv().await.expect("intent should arrive");
        assert_eq!(intent.kind, MrfKind::DecodeFailure);
        assert_eq!(intent.bucket.as_ref(), "b");
        release_mrf_intent(&intent);

        // Disable delivery: producers become no-ops.
        set_mrf_delivery_enabled(false);
        assert!(!try_send_mrf_intent(MrfKind::PartialWrite, "b", "o", None));
        set_mrf_delivery_enabled(true);

        // Fill the bounded channel past capacity: excess intents are dropped,
        // never blocking.
        let mut accepted = 0;
        for index in 0..(MRF_CHANNEL_CAPACITY + 64) {
            if try_send_mrf_intent(MrfKind::PartialWrite, "b", &format!("o-{index}"), None) {
                accepted += 1;
            }
        }
        assert_eq!(accepted, MRF_CHANNEL_CAPACITY);
    }

    #[test]
    fn try_send_without_channel_is_false() {
        // This test may run after the tokio test above in the same process;
        // the singleton semantics make a clean "uninitialized" case hard, so
        // assert the flag-off behavior only.
        set_mrf_delivery_enabled(false);
        assert!(!try_send_mrf_intent(MrfKind::MetadataCorruption, "b", "o", None));
        set_mrf_delivery_enabled(true);
    }

    #[test]
    fn repaired_events_take_is_bucket_scoped_and_cap_bounded() {
        // Distinct buckets keep their notices until their own scanner takes
        // them; a take for one bucket leaves the others' notices in place.
        note_mrf_repaired("bucket-a", "object-1", None);
        note_mrf_repaired("bucket-b", "object-2", None);
        note_mrf_repaired("bucket-a", "object-3", None);

        let taken_a = take_mrf_repaired_events_for("bucket-a");
        assert_eq!(taken_a.len(), 2);
        assert_eq!(taken_a[0].object.as_ref(), "object-1");
        assert_eq!(taken_a[1].object.as_ref(), "object-3");
        assert!(take_mrf_repaired_events_for("bucket-a").is_empty(), "take is destructive per bucket");

        let taken_b = take_mrf_repaired_events_for("bucket-b");
        assert_eq!(taken_b.len(), 1);
        assert_eq!(taken_b[0].object.as_ref(), "object-2");

        // Cap bound: flooding the ring drops the oldest notices rather than
        // growing unbounded.
        for i in 0..=(MRF_REPAIRED_EVENT_CAP + 8) {
            note_mrf_repaired("flood-bucket", &format!("object-{i}"), None);
        }
        let flooded = take_mrf_repaired_events_for("flood-bucket");
        assert_eq!(flooded.len(), MRF_REPAIRED_EVENT_CAP);
        assert_eq!(flooded[0].object.as_ref(), "object-9", "the oldest notices past the cap are dropped");
    }

    #[test]
    fn verified_repair_events_preserve_full_identity_and_bucket_scope() {
        let bucket_incarnation_id = Uuid::new_v4();
        let event = MrfVerifiedRepairEvent {
            kind: MrfKind::PartialWrite,
            bucket: Arc::from("verified-bucket-a"),
            object: Arc::from("object-a"),
            version_id: Some([4u8; 16]),
            scope: Some(MrfScope {
                pool_index: 2,
                set_index: 3,
            }),
            delete_marker_purge: None,
            lease: Some(MrfIngressLease::new(42)),
            bucket_incarnation_id,
            disposition: MrfVerifiedRepairDisposition::Repaired,
        };
        note_mrf_verified_repair(event.clone());
        note_mrf_verified_repair(MrfVerifiedRepairEvent {
            bucket: Arc::from("verified-bucket-b"),
            ..event.clone()
        });

        let taken = take_mrf_verified_repair_events_for("verified-bucket-a");
        assert_eq!(taken, vec![event]);
        assert!(take_mrf_verified_repair_events_for("verified-bucket-a").is_empty());
        assert_eq!(take_mrf_verified_repair_events_for("verified-bucket-b").len(), 1);
    }

    #[test]
    fn unverified_legacy_events_are_bucket_scoped_and_bounded() {
        let bucket = Arc::<str>::from("unverified-legacy-event-bucket");
        let _ = take_mrf_unverified_legacy_events_for(bucket.as_ref());
        let event = MrfUnverifiedLegacyEvent {
            anchor: MrfDurableRepairAnchor {
                kind: MrfKind::PartialWrite,
                bucket: bucket.clone(),
                object: Arc::from("unverified-object"),
                version_id: None,
                scope: Some(MrfScope {
                    pool_index: 1,
                    set_index: 2,
                }),
                delete_marker_purge: None,
                lease: MrfIngressLease::new(912),
                bucket_incarnation_id: Uuid::new_v4(),
            },
        };
        note_mrf_unverified_legacy(event.clone());
        note_mrf_unverified_legacy(event.clone());
        assert_eq!(take_mrf_unverified_legacy_events_for(bucket.as_ref()), vec![event]);
        assert!(take_mrf_unverified_legacy_events_for(bucket.as_ref()).is_empty());

        let cap_bucket = Arc::<str>::from("unverified-legacy-event-cap-bucket");
        for index in 0..MRF_REPAIRED_EVENT_CAP + 4 {
            note_mrf_unverified_legacy(MrfUnverifiedLegacyEvent {
                anchor: MrfDurableRepairAnchor {
                    kind: MrfKind::PartialWrite,
                    bucket: cap_bucket.clone(),
                    object: Arc::from(format!("object-{index}")),
                    version_id: None,
                    scope: Some(MrfScope {
                        pool_index: 1,
                        set_index: 2,
                    }),
                    delete_marker_purge: None,
                    lease: MrfIngressLease::new(u64::try_from(index).expect("test index fits")),
                    bucket_incarnation_id: Uuid::new_v4(),
                },
            });
        }
        let events = take_mrf_unverified_legacy_events_for(cap_bucket.as_ref());
        assert_eq!(events.len(), MRF_REPAIRED_EVENT_CAP);
        assert_eq!(events.first().expect("bounded ring is non-empty").anchor.object.as_ref(), "object-4");
    }
}
#[tokio::test]
async fn partial_write_durable_admission_waits_for_persistence_and_renews_lease() {
    let mut receiver = init_durable_mrf_channel().expect("isolated test should initialize durable channel");
    let scope = MrfScope {
        pool_index: 2,
        set_index: 3,
    };
    let first = tokio::spawn(async move { persist_partial_write_intent("bucket", "object", None, scope).await });
    let submission = receiver.recv().await.expect("first submission should arrive");
    let first_lease = submission.intent.lease;
    assert!(!first.is_finished(), "channel delivery alone must not acknowledge durable ownership");
    submission
        .response
        .send(Err(MrfDurableAdmissionError::Persistence))
        .expect("producer should await receipt");
    assert_eq!(first.await.expect("producer should complete"), Err(MrfDurableAdmissionError::Persistence));
    let second = tokio::spawn(async move { persist_partial_write_intent("bucket", "object", None, scope).await });
    let submission = receiver.recv().await.expect("replacement submission should arrive");
    assert_ne!(
        first_lease, submission.intent.lease,
        "an overwrite must not reuse the previous proof identity"
    );
    assert_eq!(submission.intent.scope, Some(scope));
    submission
        .response
        .send(Ok(()))
        .expect("second producer should await receipt");
    assert_eq!(second.await.expect("second producer should complete"), Ok(()));

    let bucket_incarnation_id = Uuid::new_v4();
    let marker_identity = [7; 32];
    let purge = MrfDeleteMarkerPurge::new(bucket_incarnation_id, bucket_incarnation_id, marker_identity, vec![1, 2, 3])
        .expect("valid purge payload");
    let version_id = Uuid::new_v4();
    let purge_submit =
        tokio::spawn(async move { persist_delete_marker_purge_intent("bucket", "marker", version_id, scope, purge).await });
    let submission = receiver.recv().await.expect("purge submission should arrive");
    assert_eq!(submission.intent.kind, MrfKind::DeleteMarkerPurge);
    assert_eq!(submission.intent.version_id, Some(*version_id.as_bytes()));
    assert_eq!(submission.intent.scope, Some(scope));
    assert_eq!(
        submission
            .intent
            .delete_marker_purge
            .as_ref()
            .map(MrfDeleteMarkerPurge::identity),
        Some(MrfDeleteMarkerPurgeIdentity {
            bucket_incarnation_id,
            marker_incarnation_id: bucket_incarnation_id,
            marker_identity,
        })
    );
    assert!(submission.intent.lease.is_some());
    submission.response.send(Ok(())).expect("purge producer should await receipt");
    assert_eq!(purge_submit.await.expect("purge producer should complete"), Ok(()));

    let invalid = MrfDeleteMarkerPurge {
        bucket_incarnation_id,
        marker_incarnation_id: Uuid::new_v4(),
        marker_identity,
        marker: Arc::from([1u8]),
    };
    assert_eq!(
        persist_delete_marker_purge_intent("bucket", "marker", version_id, scope, invalid).await,
        Err(MrfDurableAdmissionError::InvalidIdentity)
    );
}