rustfs-ecstore 1.0.1

Erasure coding storage backend for RustFS, providing efficient data storage and retrieval with redundancy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::{Arc, LazyLock};

use rustfs_utils::crypto::{hex_sha256, is_sha256_checksum};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::config::com;
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::{Error, Result as EcstoreResult};
use crate::object_api::{ObjectInfo, ObjectOptions};
use crate::services::tier::tier::TierDestinationId;
use crate::storage_api_contracts::{
    list::{ListOperations, StorageListObjectsV2Info},
    object::{EcstoreObjectIO, EcstoreObjectOperations, HTTPPreconditions},
};

pub(crate) const TIER_MUTATION_INTENT_SCHEMA: &str = "rustfs-tier-mutation-intent-v1";
pub(crate) const MAX_TIER_MUTATION_INTENT_SIZE: usize = rustfs_protos::TIER_MUTATION_RPC_MAX_PREPARE_PAYLOAD_SIZE;
pub(crate) const TIER_MUTATION_INTENT_RECORD_PREFIX: &str = "tier/mutation-intents/records";
pub(crate) const TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX: &str = "tier/mutation-intents/coordinators";
pub(crate) const TIER_MUTATION_MUTEX_SHARDS: usize = 64;
const TIER_MUTATION_INTENT_ADVANCE_CAS_ATTEMPTS: usize = 3;
pub(crate) type TierMutationDigest = [u8; 32];

static TIER_MUTATION_MUTEXES: LazyLock<[tokio::sync::Mutex<()>; TIER_MUTATION_MUTEX_SHARDS]> =
    LazyLock::new(|| std::array::from_fn(|_| tokio::sync::Mutex::new(())));

/// Serializes every local phase and recovery action for one mutation id while
/// retaining bounded parallelism for unrelated mutations.
pub(crate) async fn acquire_tier_mutation_mutex(mutation_id: Uuid) -> tokio::sync::MutexGuard<'static, ()> {
    TIER_MUTATION_MUTEXES[tier_mutation_mutex_shard_index(mutation_id)]
        .lock()
        .await
}

fn tier_mutation_mutex_shard_index(mutation_id: Uuid) -> usize {
    let raw = mutation_id.as_u128();
    let mut mixed = (raw as u64) ^ ((raw >> 64) as u64);
    // MurmurHash3's 64-bit finalizer gives stable diffusion without allocating
    // or relying on RandomState, whose seed differs between processes.
    mixed ^= mixed >> 33;
    mixed = mixed.wrapping_mul(0xff51_afd7_ed55_8ccd);
    mixed ^= mixed >> 33;
    mixed = mixed.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
    mixed ^= mixed >> 33;
    (mixed as usize) & (TIER_MUTATION_MUTEX_SHARDS - 1)
}

pub(crate) type Result<T> = std::result::Result<T, TierMutationIntentError>;

#[derive(Debug, thiserror::Error)]
pub(crate) enum TierMutationIntentError {
    #[error("tier mutation intent is corrupt: {0}")]
    Corrupt(&'static str),
    #[error("tier mutation intent schema is unsupported: {0}")]
    UnsupportedSchema(String),
    #[error("tier mutation intent checksum mismatch")]
    ChecksumMismatch,
    #[error("invalid tier mutation intent state change from {from:?} to {to:?}")]
    InvalidStateChange {
        from: TierMutationIntentState,
        to: TierMutationIntentState,
    },
    #[error("tier mutation intent json error: {0}")]
    Json(#[from] serde_json::Error),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TierMutationIntentState {
    Prepared,
    Committed,
    Aborted,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TierMutationIntentKind {
    Add,
    Edit,
    Remove,
    Clear,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct TierMutationIntentTarget {
    pub tier_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_backend_identity: Option<TierDestinationId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_backend_identity: Option<TierDestinationId>,
}

impl TierMutationIntentTarget {
    pub(crate) fn validate(&self) -> Result<()> {
        if self.tier_name.is_empty() {
            return Err(TierMutationIntentError::Corrupt("target tier name is empty"));
        }
        if self.old_backend_identity.is_none() && self.new_backend_identity.is_none() {
            return Err(TierMutationIntentError::Corrupt("target has no backend identity"));
        }
        if self.old_backend_identity.as_ref().is_some_and(identity_is_empty) {
            return Err(TierMutationIntentError::Corrupt("target old backend identity is empty"));
        }
        if self.new_backend_identity.as_ref().is_some_and(identity_is_empty) {
            return Err(TierMutationIntentError::Corrupt("target new backend identity is empty"));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct TierMutationIntent {
    pub mutation_id: Uuid,
    pub revision: u64,
    pub kind: TierMutationIntentKind,
    pub state: TierMutationIntentState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_config_etag: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub committed_config_etag: Option<String>,
    pub candidate_digest: TierMutationDigest,
    pub affected_targets: Vec<TierMutationIntentTarget>,
    pub expires_at_unix_nanos: i64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TierMutationIntentRecordScan {
    pub intents: Vec<TierMutationIntent>,
    pub scanned: usize,
    pub failed: usize,
    pub next_marker: Option<String>,
    pub truncated: bool,
}

impl TierMutationIntent {
    pub(crate) fn validate(&self) -> Result<()> {
        if self.mutation_id.is_nil() {
            return Err(TierMutationIntentError::Corrupt("mutation_id is nil"));
        }
        if self.revision == 0 {
            return Err(TierMutationIntentError::Corrupt("revision is zero"));
        }
        if self.old_config_etag.as_deref().is_some_and(str::is_empty) {
            return Err(TierMutationIntentError::Corrupt("old config etag is empty"));
        }
        if self.old_config_etag.is_none() && self.kind != TierMutationIntentKind::Add {
            return Err(TierMutationIntentError::Corrupt("old config etag is required for mutation kind"));
        }
        if self.committed_config_etag.as_deref().is_some_and(str::is_empty) {
            return Err(TierMutationIntentError::Corrupt("committed config etag is empty"));
        }
        if self.state != TierMutationIntentState::Committed && self.committed_config_etag.is_some() {
            return Err(TierMutationIntentError::Corrupt("non-committed intent carries committed config etag"));
        }
        if self.state == TierMutationIntentState::Committed && self.committed_config_etag.is_none() {
            return Err(TierMutationIntentError::Corrupt("committed intent is missing committed config etag"));
        }
        if digest_is_empty(&self.candidate_digest) {
            return Err(TierMutationIntentError::Corrupt("candidate digest is empty"));
        }
        if self.affected_targets.is_empty() {
            return Err(TierMutationIntentError::Corrupt("affected targets are empty"));
        }
        if self.expires_at_unix_nanos <= 0 {
            return Err(TierMutationIntentError::Corrupt("expiry timestamp is not positive"));
        }

        let mut previous: Option<&str> = None;
        for target in &self.affected_targets {
            target.validate()?;
            self.validate_target_shape(target)?;
            if previous.is_some_and(|previous| previous >= target.tier_name.as_str()) {
                return Err(TierMutationIntentError::Corrupt("affected targets are not canonical"));
            }
            previous = Some(&target.tier_name);
        }
        Ok(())
    }

    fn validate_target_shape(&self, target: &TierMutationIntentTarget) -> Result<()> {
        match self.kind {
            TierMutationIntentKind::Add if target.old_backend_identity.is_none() && target.new_backend_identity.is_some() => {
                Ok(())
            }
            TierMutationIntentKind::Edit if target.old_backend_identity.is_some() && target.new_backend_identity.is_some() => {
                Ok(())
            }
            TierMutationIntentKind::Remove | TierMutationIntentKind::Clear
                if target.old_backend_identity.is_some() && target.new_backend_identity.is_none() =>
            {
                Ok(())
            }
            _ => Err(TierMutationIntentError::Corrupt(
                "target backend identity shape does not match mutation kind",
            )),
        }
    }

    pub(crate) fn advance(&mut self, next: TierMutationIntentState, committed_config_etag: Option<String>) -> Result<()> {
        match (self.state, next) {
            (TierMutationIntentState::Prepared, TierMutationIntentState::Committed) => {
                let committed_config_etag =
                    committed_config_etag.ok_or(TierMutationIntentError::Corrupt("commit requires config etag"))?;
                if committed_config_etag.is_empty() {
                    return Err(TierMutationIntentError::Corrupt("commit config etag is empty"));
                }
                self.state = next;
                self.committed_config_etag = Some(committed_config_etag);
            }
            (TierMutationIntentState::Prepared, TierMutationIntentState::Aborted) => {
                if committed_config_etag.is_some() {
                    return Err(TierMutationIntentError::Corrupt("abort must not carry committed config etag"));
                }
                self.state = next;
                self.committed_config_etag = None;
            }
            _ => {
                return Err(TierMutationIntentError::InvalidStateChange {
                    from: self.state,
                    to: next,
                });
            }
        }
        self.revision = self
            .revision
            .checked_add(1)
            .ok_or(TierMutationIntentError::Corrupt("revision overflow"))?;
        self.validate()
    }

    pub(crate) fn advance_idempotent(
        &mut self,
        next: TierMutationIntentState,
        committed_config_etag: Option<String>,
    ) -> Result<bool> {
        match (self.state, next) {
            (TierMutationIntentState::Prepared, TierMutationIntentState::Committed | TierMutationIntentState::Aborted) => {
                self.advance(next, committed_config_etag)?;
                Ok(true)
            }
            (TierMutationIntentState::Committed, TierMutationIntentState::Committed) => {
                let committed_config_etag =
                    committed_config_etag.ok_or(TierMutationIntentError::Corrupt("commit requires config etag"))?;
                if committed_config_etag.is_empty() {
                    return Err(TierMutationIntentError::Corrupt("commit config etag is empty"));
                }
                if self.committed_config_etag.as_deref() != Some(committed_config_etag.as_str()) {
                    return Err(TierMutationIntentError::Corrupt("committed config etag does not match"));
                }
                self.validate()?;
                Ok(false)
            }
            (TierMutationIntentState::Aborted, TierMutationIntentState::Aborted) => {
                if committed_config_etag.is_some() {
                    return Err(TierMutationIntentError::Corrupt("abort must not carry committed config etag"));
                }
                self.validate()?;
                Ok(false)
            }
            _ => Err(TierMutationIntentError::InvalidStateChange {
                from: self.state,
                to: next,
            }),
        }
    }

    pub(crate) fn same_identity_as(&self, other: &Self) -> bool {
        self.mutation_id == other.mutation_id
            && self.kind == other.kind
            && self.old_config_etag == other.old_config_etag
            && self.candidate_digest == other.candidate_digest
            && self.affected_targets == other.affected_targets
            && self.expires_at_unix_nanos == other.expires_at_unix_nanos
    }

    /// Reconstruct the exact Prepared record that originally produced this
    /// intent. Abort RPCs are identity-bound to that payload; serializing an
    /// Aborted terminal record would both violate the wire contract and use a
    /// different revision if a missing peer has to persist a tombstone.
    pub(crate) fn original_prepared(&self) -> Result<Self> {
        if self.state == TierMutationIntentState::Prepared {
            self.validate()?;
            return Ok(self.clone());
        }
        let mut prepared = self.clone();
        prepared.revision =
            prepared
                .revision
                .checked_sub(1)
                .filter(|revision| *revision != 0)
                .ok_or(TierMutationIntentError::Corrupt(
                    "terminal intent cannot reconstruct its prepared revision",
                ))?;
        prepared.state = TierMutationIntentState::Prepared;
        prepared.committed_config_etag = None;
        prepared.validate()?;
        Ok(prepared)
    }

    pub(crate) fn encode(&self) -> Result<Vec<u8>> {
        self.validate()?;
        let intent_bytes = serde_json::to_vec(self)?;
        let content_sha256 = hex_sha256(&intent_bytes, ToOwned::to_owned);
        let persisted = PersistedTierMutationIntent {
            schema: TIER_MUTATION_INTENT_SCHEMA.to_string(),
            content_sha256,
            intent: self.clone(),
        };
        let encoded = serde_json::to_vec(&persisted)?;
        if encoded.len() > MAX_TIER_MUTATION_INTENT_SIZE {
            return Err(TierMutationIntentError::Corrupt("encoded intent exceeds maximum size"));
        }
        Ok(encoded)
    }

    pub(crate) fn decode(expected_mutation_id: Uuid, data: &[u8]) -> Result<Self> {
        if data.len() > MAX_TIER_MUTATION_INTENT_SIZE {
            return Err(TierMutationIntentError::Corrupt("encoded intent exceeds maximum size"));
        }
        let persisted: PersistedTierMutationIntent = serde_json::from_slice(data)?;
        if persisted.schema != TIER_MUTATION_INTENT_SCHEMA {
            return Err(TierMutationIntentError::UnsupportedSchema(persisted.schema));
        }
        if !is_sha256_checksum(&persisted.content_sha256) {
            return Err(TierMutationIntentError::Corrupt("content checksum is not a sha256 checksum"));
        }
        let intent_bytes = serde_json::to_vec(&persisted.intent)?;
        let actual_checksum = hex_sha256(&intent_bytes, ToOwned::to_owned);
        if persisted.content_sha256 != actual_checksum {
            return Err(TierMutationIntentError::ChecksumMismatch);
        }
        if persisted.intent.mutation_id != expected_mutation_id {
            return Err(TierMutationIntentError::Corrupt("mutation_id does not match intent key"));
        }
        persisted.intent.validate()?;
        Ok(persisted.intent)
    }
}

#[allow(
    dead_code,
    reason = "intent-record persistence asserted by store::init tests (backlog#1823)"
)]
pub(crate) fn tier_mutation_intent_record_object_name(mutation_id: Uuid) -> Result<String> {
    tier_mutation_intent_record_object_name_with_prefix(TIER_MUTATION_INTENT_RECORD_PREFIX, mutation_id)
}

fn tier_mutation_intent_record_object_name_with_prefix(prefix: &str, mutation_id: Uuid) -> Result<String> {
    if mutation_id.is_nil() {
        return Err(TierMutationIntentError::Corrupt("mutation_id is nil"));
    }
    let mutation_key = mutation_id.simple().to_string();
    Ok(format!("{}/{}/{}/{}.json", prefix, &mutation_key[..2], &mutation_key[2..4], mutation_key))
}

#[allow(
    dead_code,
    reason = "intent-record persistence asserted by store::init tests (backlog#1823)"
)]
pub(crate) fn tier_mutation_intent_id_from_record_object_name(object: &str) -> Result<Uuid> {
    tier_mutation_intent_id_from_record_object_name_with_prefix(TIER_MUTATION_INTENT_RECORD_PREFIX, object)
}

fn tier_mutation_intent_id_from_record_object_name_with_prefix(prefix: &str, object: &str) -> Result<Uuid> {
    let prefix = format!("{prefix}/");
    let suffix = object
        .strip_prefix(&prefix)
        .ok_or(TierMutationIntentError::Corrupt("intent record path has wrong prefix"))?;
    let mut parts = suffix.split('/');
    let shard_a = parts
        .next()
        .ok_or(TierMutationIntentError::Corrupt("intent record path is incomplete"))?;
    let shard_b = parts
        .next()
        .ok_or(TierMutationIntentError::Corrupt("intent record path is incomplete"))?;
    let file_name = parts
        .next()
        .ok_or(TierMutationIntentError::Corrupt("intent record path is incomplete"))?;
    if parts.next().is_some() {
        return Err(TierMutationIntentError::Corrupt("intent record path is not canonical"));
    }
    let mutation_key = file_name
        .strip_suffix(".json")
        .ok_or(TierMutationIntentError::Corrupt("intent record path has wrong suffix"))?;
    if mutation_key.len() != 32
        || !mutation_key
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
    {
        return Err(TierMutationIntentError::Corrupt("intent record path has invalid mutation id"));
    }
    if shard_a != &mutation_key[..2] || shard_b != &mutation_key[2..4] {
        return Err(TierMutationIntentError::Corrupt("intent record path shard does not match mutation id"));
    }
    Uuid::parse_str(mutation_key).map_err(|_| TierMutationIntentError::Corrupt("intent record path has invalid uuid"))
}

#[allow(
    dead_code,
    reason = "intent-record persistence asserted by store::init tests (backlog#1823)"
)]
pub(crate) async fn save_tier_mutation_intent_record<S>(api: Arc<S>, intent: &TierMutationIntent) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    let object = tier_mutation_intent_record_object_name_with_prefix(TIER_MUTATION_INTENT_RECORD_PREFIX, intent.mutation_id)
        .map_err(tier_mutation_intent_store_error)?;
    let data = intent.encode().map_err(tier_mutation_intent_store_error)?;
    com::save_config(api, &object, data).await
}

pub(crate) async fn save_tier_coordinator_mutation_intent_record_if_absent<S>(
    api: Arc<S>,
    intent: &TierMutationIntent,
) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    save_tier_mutation_intent_record_if_absent_with_prefix(api, TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX, intent).await
}

pub(crate) async fn save_tier_mutation_intent_record_if_absent<S>(api: Arc<S>, intent: &TierMutationIntent) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    save_tier_mutation_intent_record_if_absent_with_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, intent).await
}

async fn save_tier_mutation_intent_record_if_absent_with_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    intent: &TierMutationIntent,
) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    let object = tier_mutation_intent_record_object_name_with_prefix(prefix, intent.mutation_id)
        .map_err(tier_mutation_intent_store_error)?;
    let data = intent.encode().map_err(tier_mutation_intent_store_error)?;
    com::save_config_with_opts(
        api,
        &object,
        data,
        &ObjectOptions {
            max_parity: true,
            write_completion: crate::object_api::WriteCompletion::TailDrained,
            http_preconditions: Some(HTTPPreconditions {
                if_none_match: Some("*".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        },
    )
    .await
}

pub(crate) async fn load_tier_mutation_intent_record<S>(api: Arc<S>, mutation_id: Uuid) -> EcstoreResult<TierMutationIntent>
where
    S: EcstoreObjectIO,
{
    let (intent, _) = load_tier_mutation_intent_record_with_etag(api, mutation_id).await?;
    Ok(intent)
}

pub(crate) async fn load_tier_mutation_intent_record_with_etag<S>(
    api: Arc<S>,
    mutation_id: Uuid,
) -> EcstoreResult<(TierMutationIntent, String)>
where
    S: EcstoreObjectIO,
{
    load_tier_mutation_intent_record_with_etag_at_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, mutation_id).await
}

pub(crate) async fn load_tier_coordinator_mutation_intent_record_with_etag<S>(
    api: Arc<S>,
    mutation_id: Uuid,
) -> EcstoreResult<(TierMutationIntent, String)>
where
    S: EcstoreObjectIO,
{
    load_tier_mutation_intent_record_with_etag_at_prefix(api, TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX, mutation_id).await
}

async fn load_tier_mutation_intent_record_with_etag_at_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    mutation_id: Uuid,
) -> EcstoreResult<(TierMutationIntent, String)>
where
    S: EcstoreObjectIO,
{
    let object =
        tier_mutation_intent_record_object_name_with_prefix(prefix, mutation_id).map_err(tier_mutation_intent_store_error)?;
    let (data, object_info) = com::read_config_with_metadata(api, &object, &ObjectOptions::default()).await?;
    let etag = object_info
        .etag
        .filter(|etag| !etag.trim().is_empty())
        .ok_or_else(|| Error::other("tier mutation intent record is missing an ETag"))?;
    let intent = TierMutationIntent::decode(mutation_id, &data).map_err(tier_mutation_intent_store_error)?;
    Ok((intent, etag))
}

#[allow(
    dead_code,
    reason = "intent-record persistence asserted by store::init tests (backlog#1823)"
)]
pub(crate) async fn save_tier_mutation_intent_record_if_current<S>(
    api: Arc<S>,
    intent: &TierMutationIntent,
    current_etag: &str,
) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    if current_etag.trim().is_empty() {
        return Err(Error::other("tier mutation intent current ETag is empty"));
    }
    save_tier_mutation_intent_record_if_current_with_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, intent, current_etag).await
}

async fn save_tier_mutation_intent_record_if_current_with_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    intent: &TierMutationIntent,
    current_etag: &str,
) -> EcstoreResult<()>
where
    S: EcstoreObjectIO,
{
    if current_etag.trim().is_empty() {
        return Err(Error::other("tier mutation intent current ETag is empty"));
    }
    let object = tier_mutation_intent_record_object_name_with_prefix(prefix, intent.mutation_id)
        .map_err(tier_mutation_intent_store_error)?;
    let data = intent.encode().map_err(tier_mutation_intent_store_error)?;
    com::save_config_with_opts(
        api,
        &object,
        data,
        &ObjectOptions {
            max_parity: true,
            write_completion: crate::object_api::WriteCompletion::TailDrained,
            http_preconditions: Some(HTTPPreconditions {
                if_match: Some(current_etag.to_string()),
                ..Default::default()
            }),
            ..Default::default()
        },
    )
    .await
}

#[cfg(test)]
pub(crate) async fn delete_tier_mutation_intent_record<S>(api: Arc<S>, mutation_id: Uuid) -> EcstoreResult<()>
where
    S: EcstoreObjectOperations,
{
    delete_tier_mutation_intent_record_with_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, mutation_id).await
}

pub(crate) async fn delete_tier_mutation_intent_record_if_current<S>(
    api: Arc<S>,
    mutation_id: Uuid,
    current_etag: &str,
) -> EcstoreResult<()>
where
    S: EcstoreObjectOperations,
{
    delete_tier_mutation_intent_record_if_current_with_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, mutation_id, current_etag)
        .await
}

pub(crate) async fn delete_tier_coordinator_mutation_intent_record_if_current<S>(
    api: Arc<S>,
    mutation_id: Uuid,
    current_etag: &str,
) -> EcstoreResult<()>
where
    S: EcstoreObjectOperations,
{
    delete_tier_mutation_intent_record_if_current_with_prefix(
        api,
        TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX,
        mutation_id,
        current_etag,
    )
    .await
}

#[cfg(test)]
async fn delete_tier_mutation_intent_record_with_prefix<S>(api: Arc<S>, prefix: &str, mutation_id: Uuid) -> EcstoreResult<()>
where
    S: EcstoreObjectOperations,
{
    let object =
        tier_mutation_intent_record_object_name_with_prefix(prefix, mutation_id).map_err(tier_mutation_intent_store_error)?;
    match com::delete_config(api, &object).await {
        Ok(()) | Err(Error::ConfigNotFound) => Ok(()),
        Err(err) => Err(err),
    }
}

async fn delete_tier_mutation_intent_record_if_current_with_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    mutation_id: Uuid,
    current_etag: &str,
) -> EcstoreResult<()>
where
    S: EcstoreObjectOperations,
{
    if current_etag.trim().is_empty() {
        return Err(Error::other("tier mutation intent current ETag is empty"));
    }
    let object =
        tier_mutation_intent_record_object_name_with_prefix(prefix, mutation_id).map_err(tier_mutation_intent_store_error)?;
    match api
        .delete_object(
            RUSTFS_META_BUCKET,
            &object,
            ObjectOptions {
                http_preconditions: Some(HTTPPreconditions {
                    if_match: Some(current_etag.to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            },
        )
        .await
    {
        Ok(_) => Ok(()),
        Err(err) if err == Error::FileNotFound || matches!(err, Error::ObjectNotFound(_, _)) => Err(Error::ConfigNotFound),
        Err(err) => Err(err),
    }
}

pub(crate) async fn advance_tier_mutation_intent_record_idempotent<S>(
    api: Arc<S>,
    mutation_id: Uuid,
    next: TierMutationIntentState,
    committed_config_etag: Option<String>,
) -> EcstoreResult<(TierMutationIntent, bool)>
where
    S: EcstoreObjectIO,
{
    advance_tier_mutation_intent_record_idempotent_at_prefix(
        api,
        TIER_MUTATION_INTENT_RECORD_PREFIX,
        mutation_id,
        next,
        committed_config_etag,
    )
    .await
}

pub(crate) async fn advance_tier_coordinator_mutation_intent_record_idempotent<S>(
    api: Arc<S>,
    mutation_id: Uuid,
    next: TierMutationIntentState,
    committed_config_etag: Option<String>,
) -> EcstoreResult<(TierMutationIntent, bool)>
where
    S: EcstoreObjectIO,
{
    advance_tier_mutation_intent_record_idempotent_at_prefix(
        api,
        TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX,
        mutation_id,
        next,
        committed_config_etag,
    )
    .await
}

async fn advance_tier_mutation_intent_record_idempotent_at_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    mutation_id: Uuid,
    next: TierMutationIntentState,
    committed_config_etag: Option<String>,
) -> EcstoreResult<(TierMutationIntent, bool)>
where
    S: EcstoreObjectIO,
{
    for attempt in 0..TIER_MUTATION_INTENT_ADVANCE_CAS_ATTEMPTS {
        let (mut intent, current_etag) =
            load_tier_mutation_intent_record_with_etag_at_prefix(api.clone(), prefix, mutation_id).await?;
        let advanced = intent
            .advance_idempotent(next, committed_config_etag.clone())
            .map_err(tier_mutation_intent_store_error)?;
        if !advanced {
            return Ok((intent, false));
        }
        match save_tier_mutation_intent_record_if_current_with_prefix(api.clone(), prefix, &intent, &current_etag).await {
            Ok(()) => return Ok((intent, true)),
            Err(Error::PreconditionFailed) => {
                let (mut current, _) =
                    load_tier_mutation_intent_record_with_etag_at_prefix(api.clone(), prefix, mutation_id).await?;
                if !current.same_identity_as(&intent) {
                    return Err(Error::PreconditionFailed);
                }
                let replayed = current
                    .advance_idempotent(next, intent.committed_config_etag.clone())
                    .map_err(tier_mutation_intent_store_error)?;
                if replayed {
                    if attempt + 1 < TIER_MUTATION_INTENT_ADVANCE_CAS_ATTEMPTS {
                        continue;
                    }
                    return Err(Error::PreconditionFailed);
                }
                return Ok((current, false));
            }
            Err(err) => return Err(err),
        }
    }
    Err(Error::PreconditionFailed)
}

pub(crate) async fn list_tier_mutation_intent_records<S>(
    api: Arc<S>,
    limit: usize,
    marker: Option<String>,
) -> EcstoreResult<TierMutationIntentRecordScan>
where
    S: EcstoreObjectIO + ListOperations<Error = Error, ListObjectsV2Info = StorageListObjectsV2Info<ObjectInfo>>,
{
    list_tier_mutation_intent_records_at_prefix(api, TIER_MUTATION_INTENT_RECORD_PREFIX, limit, marker).await
}

pub(crate) async fn list_tier_coordinator_mutation_intent_records<S>(
    api: Arc<S>,
    limit: usize,
    marker: Option<String>,
) -> EcstoreResult<TierMutationIntentRecordScan>
where
    S: EcstoreObjectIO + ListOperations<Error = Error, ListObjectsV2Info = StorageListObjectsV2Info<ObjectInfo>>,
{
    list_tier_mutation_intent_records_at_prefix(api, TIER_COORDINATOR_MUTATION_INTENT_RECORD_PREFIX, limit, marker).await
}

async fn list_tier_mutation_intent_records_at_prefix<S>(
    api: Arc<S>,
    prefix: &str,
    limit: usize,
    marker: Option<String>,
) -> EcstoreResult<TierMutationIntentRecordScan>
where
    S: EcstoreObjectIO + ListOperations<Error = Error, ListObjectsV2Info = StorageListObjectsV2Info<ObjectInfo>>,
{
    if limit == 0 {
        return Err(Error::other("tier mutation intent scan limit must be greater than zero"));
    }

    let list = api
        .clone()
        .list_objects_v2(
            RUSTFS_META_BUCKET,
            prefix,
            marker,
            None,
            i32::try_from(limit).unwrap_or(i32::MAX),
            false,
            None,
            false,
        )
        .await?;
    let mut scan = TierMutationIntentRecordScan {
        intents: Vec::with_capacity(list.objects.len()),
        scanned: 0,
        failed: 0,
        next_marker: list.next_continuation_token,
        truncated: list.is_truncated,
    };

    for object in list.objects {
        scan.scanned += 1;
        let mutation_id = match tier_mutation_intent_id_from_record_object_name_with_prefix(prefix, &object.name) {
            Ok(mutation_id) => mutation_id,
            Err(_) => {
                scan.failed += 1;
                continue;
            }
        };
        match load_tier_mutation_intent_record_with_etag_at_prefix(api.clone(), prefix, mutation_id).await {
            Ok((intent, _)) => scan.intents.push(intent),
            Err(Error::ConfigNotFound) => {}
            Err(_) => scan.failed += 1,
        }
    }

    Ok(scan)
}

fn tier_mutation_intent_store_error(err: TierMutationIntentError) -> Error {
    Error::other(err)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PersistedTierMutationIntent {
    schema: String,
    content_sha256: String,
    intent: TierMutationIntent,
}

fn identity_is_empty(identity: &TierDestinationId) -> bool {
    identity.iter().all(|byte| *byte == 0)
}

fn digest_is_empty(digest: &TierMutationDigest) -> bool {
    digest.iter().all(|byte| *byte == 0)
}

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

    const OLD_IDENTITY: TierDestinationId = [1; 32];
    const NEW_IDENTITY: TierDestinationId = [2; 32];
    const CANDIDATE_DIGEST: TierMutationDigest = [3; 32];

    fn prepared_intent() -> TierMutationIntent {
        TierMutationIntent {
            mutation_id: Uuid::new_v4(),
            revision: 1,
            kind: TierMutationIntentKind::Edit,
            state: TierMutationIntentState::Prepared,
            old_config_etag: Some("old-etag".to_string()),
            committed_config_etag: None,
            candidate_digest: CANDIDATE_DIGEST,
            affected_targets: vec![TierMutationIntentTarget {
                tier_name: "COLD-A".to_string(),
                old_backend_identity: Some(OLD_IDENTITY),
                new_backend_identity: Some(NEW_IDENTITY),
            }],
            expires_at_unix_nanos: 1_780_000_000_000_000_000,
        }
    }

    #[test]
    fn mutation_mutex_uses_exactly_64_stable_shards() {
        assert_eq!(TIER_MUTATION_MUTEX_SHARDS, 64);
        assert_eq!(TIER_MUTATION_MUTEXES.len(), TIER_MUTATION_MUTEX_SHARDS);

        let mutation_id = Uuid::parse_str("36e2220e-9ad2-495b-b3bc-c4d2caf70a31").expect("fixture uuid should parse");
        let shard = tier_mutation_mutex_shard_index(mutation_id);
        assert!(shard < TIER_MUTATION_MUTEX_SHARDS);
        assert_eq!(shard, tier_mutation_mutex_shard_index(mutation_id));
    }

    #[tokio::test]
    async fn mutation_mutex_serializes_the_same_id() {
        let mutation_id = Uuid::new_v4();
        let first = acquire_tier_mutation_mutex(mutation_id).await;
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let (acquired_tx, mut acquired_rx) = tokio::sync::oneshot::channel();

        let waiter = tokio::spawn(async move {
            started_tx.send(()).expect("test receiver should remain alive");
            let _second = acquire_tier_mutation_mutex(mutation_id).await;
            acquired_tx.send(()).expect("test receiver should remain alive");
        });
        started_rx.await.expect("waiter should start");
        assert!(
            tokio::time::timeout(Duration::from_millis(25), &mut acquired_rx)
                .await
                .is_err(),
            "the same mutation id must not enter concurrently"
        );

        drop(first);
        tokio::time::timeout(Duration::from_secs(1), &mut acquired_rx)
            .await
            .expect("waiter should acquire after release")
            .expect("waiter should report acquisition");
        waiter.await.expect("waiter task should finish");
    }

    #[tokio::test]
    async fn mutation_mutex_allows_different_shards_to_progress() {
        let first_id = Uuid::new_v4();
        let first_shard = tier_mutation_mutex_shard_index(first_id);
        let second_id = (0..1024)
            .map(|_| Uuid::new_v4())
            .find(|candidate| tier_mutation_mutex_shard_index(*candidate) != first_shard)
            .expect("a distinct shard should be easy to find");
        let first = acquire_tier_mutation_mutex(first_id).await;

        let _second = tokio::time::timeout(Duration::from_secs(1), acquire_tier_mutation_mutex(second_id))
            .await
            .expect("a different shard must not wait for the first mutation");
        drop(first);
    }

    #[test]
    fn intent_round_trip_preserves_committed_state() {
        let mut intent = prepared_intent();
        intent
            .advance(TierMutationIntentState::Committed, Some("new-etag".to_string()))
            .expect("intent should commit");

        let encoded = intent.encode().expect("intent should encode");
        let decoded = TierMutationIntent::decode(intent.mutation_id, &encoded).expect("intent should decode");

        assert_eq!(decoded, intent);
        assert_eq!(decoded.committed_config_etag.as_deref(), Some("new-etag"));
    }

    #[test]
    fn intent_decode_rejects_unknown_fields_and_checksum_mismatch() {
        let intent = prepared_intent();
        let encoded = intent.encode().expect("intent should encode");
        let mut persisted: serde_json::Value = serde_json::from_slice(&encoded).expect("encoded intent should be json");
        persisted["intent"]["unexpected"] = serde_json::Value::Bool(true);
        let unknown = serde_json::to_vec(&persisted).expect("mutated intent should encode");
        assert!(matches!(
            TierMutationIntent::decode(intent.mutation_id, &unknown),
            Err(TierMutationIntentError::Json(_))
        ));

        let mut persisted: serde_json::Value = serde_json::from_slice(&encoded).expect("encoded intent should be json");
        persisted["intent"]["revision"] = serde_json::Value::from(2_u64);
        let mismatched = serde_json::to_vec(&persisted).expect("mutated intent should encode");
        assert!(matches!(
            TierMutationIntent::decode(intent.mutation_id, &mismatched),
            Err(TierMutationIntentError::ChecksumMismatch)
        ));
    }

    #[test]
    fn intent_validation_requires_canonical_targets() {
        let mut duplicate = prepared_intent();
        duplicate.affected_targets.push(TierMutationIntentTarget {
            tier_name: "COLD-A".to_string(),
            old_backend_identity: Some(OLD_IDENTITY),
            new_backend_identity: Some(NEW_IDENTITY),
        });
        assert!(matches!(
            duplicate.validate(),
            Err(TierMutationIntentError::Corrupt("affected targets are not canonical"))
        ));

        let mut unsorted = prepared_intent();
        unsorted.affected_targets.insert(
            0,
            TierMutationIntentTarget {
                tier_name: "COLD-Z".to_string(),
                old_backend_identity: Some(OLD_IDENTITY),
                new_backend_identity: Some(NEW_IDENTITY),
            },
        );
        assert!(matches!(
            unsorted.validate(),
            Err(TierMutationIntentError::Corrupt("affected targets are not canonical"))
        ));
    }

    #[test]
    fn intent_state_machine_rejects_late_abort_after_commit() {
        let mut intent = prepared_intent();
        intent
            .advance(TierMutationIntentState::Committed, Some("new-etag".to_string()))
            .expect("intent should commit");

        assert!(matches!(
            intent.advance(TierMutationIntentState::Aborted, None),
            Err(TierMutationIntentError::InvalidStateChange {
                from: TierMutationIntentState::Committed,
                to: TierMutationIntentState::Aborted,
            })
        ));
    }

    #[test]
    fn intent_idempotent_commit_retry_keeps_revision_and_rejects_conflicts() {
        let mut intent = prepared_intent();

        assert!(
            intent
                .advance_idempotent(TierMutationIntentState::Committed, Some("new-etag".to_string()))
                .expect("initial commit should advance")
        );
        assert_eq!(intent.revision, 2);
        assert!(
            !intent
                .advance_idempotent(TierMutationIntentState::Committed, Some("new-etag".to_string()))
                .expect("same commit retry should be idempotent")
        );
        assert_eq!(intent.revision, 2);
        assert!(matches!(
            intent.advance_idempotent(TierMutationIntentState::Committed, Some("other-etag".to_string())),
            Err(TierMutationIntentError::Corrupt("committed config etag does not match"))
        ));
        assert!(matches!(
            intent.advance_idempotent(TierMutationIntentState::Aborted, None),
            Err(TierMutationIntentError::InvalidStateChange {
                from: TierMutationIntentState::Committed,
                to: TierMutationIntentState::Aborted,
            })
        ));
    }

    #[test]
    fn intent_idempotent_abort_retry_keeps_revision_and_rejects_commit() {
        let mut intent = prepared_intent();

        assert!(
            intent
                .advance_idempotent(TierMutationIntentState::Aborted, None)
                .expect("initial abort should advance")
        );
        assert_eq!(intent.revision, 2);
        assert!(
            !intent
                .advance_idempotent(TierMutationIntentState::Aborted, None)
                .expect("same abort retry should be idempotent")
        );
        assert_eq!(intent.revision, 2);
        assert!(matches!(
            intent.advance_idempotent(TierMutationIntentState::Aborted, Some("unexpected-etag".to_string())),
            Err(TierMutationIntentError::Corrupt("abort must not carry committed config etag"))
        ));
        assert!(matches!(
            intent.advance_idempotent(TierMutationIntentState::Committed, Some("new-etag".to_string())),
            Err(TierMutationIntentError::InvalidStateChange {
                from: TierMutationIntentState::Aborted,
                to: TierMutationIntentState::Committed,
            })
        ));
    }

    #[test]
    fn terminal_intent_reconstructs_original_prepared_abort_payload() {
        for terminal in [TierMutationIntentState::Aborted, TierMutationIntentState::Committed] {
            let original = prepared_intent();
            let mut intent = original.clone();
            let committed_etag = (terminal == TierMutationIntentState::Committed).then(|| "new-etag".to_string());
            intent
                .advance(terminal, committed_etag)
                .expect("terminal transition should succeed");

            let reconstructed = intent
                .original_prepared()
                .expect("terminal record should recover prepared payload");
            assert_eq!(reconstructed, original);
            assert!(intent.same_identity_as(&reconstructed));
        }
    }

    #[test]
    fn terminal_intent_with_initial_revision_fails_prepared_reconstruction() {
        let mut corrupt = prepared_intent();
        corrupt.state = TierMutationIntentState::Aborted;

        assert!(matches!(
            corrupt.original_prepared(),
            Err(TierMutationIntentError::Corrupt(
                "terminal intent cannot reconstruct its prepared revision"
            ))
        ));
    }

    #[test]
    fn intent_validation_rejects_placeholder_identity() {
        let mut intent = prepared_intent();
        intent.affected_targets[0].old_backend_identity = Some([0; 32]);

        assert!(matches!(
            intent.validate(),
            Err(TierMutationIntentError::Corrupt("target old backend identity is empty"))
        ));
    }

    #[test]
    fn intent_allows_initial_config_create_without_old_etag() {
        let mut intent = prepared_intent();
        intent.kind = TierMutationIntentKind::Add;
        intent.old_config_etag = None;
        intent.affected_targets[0].old_backend_identity = None;

        let encoded = intent.encode().expect("initial create intent should encode");
        let decoded = TierMutationIntent::decode(intent.mutation_id, &encoded).expect("initial create intent should decode");

        assert_eq!(decoded.old_config_etag, None);
        assert_eq!(decoded.kind, TierMutationIntentKind::Add);
    }

    #[test]
    fn intent_record_object_name_is_canonical_and_reversible() {
        let mutation_id = Uuid::parse_str("12345678-1234-5678-9abc-def012345678").expect("test uuid should parse");

        let object = tier_mutation_intent_record_object_name(mutation_id).expect("record object should build");
        let parsed = tier_mutation_intent_id_from_record_object_name(&object).expect("record object should parse");

        assert_eq!(object, "tier/mutation-intents/records/12/34/12345678123456789abcdef012345678.json");
        assert_eq!(parsed, mutation_id);
    }

    #[test]
    fn intent_record_object_name_rejects_nil_and_malformed_paths() {
        assert!(matches!(
            tier_mutation_intent_record_object_name(Uuid::nil()),
            Err(TierMutationIntentError::Corrupt("mutation_id is nil"))
        ));
        assert!(matches!(
            tier_mutation_intent_id_from_record_object_name("tier/mutation-intents/records/12/34/not-a-uuid.json"),
            Err(TierMutationIntentError::Corrupt("intent record path has invalid mutation id"))
        ));
        assert!(matches!(
            tier_mutation_intent_id_from_record_object_name(
                "tier/mutation-intents/records/12/34/12345678123456789abcdef012345678"
            ),
            Err(TierMutationIntentError::Corrupt("intent record path has wrong suffix"))
        ));
        assert!(matches!(
            tier_mutation_intent_id_from_record_object_name(
                "tier/mutation-intents/records/12/35/12345678123456789abcdef012345678.json"
            ),
            Err(TierMutationIntentError::Corrupt("intent record path shard does not match mutation id"))
        ));
        assert!(matches!(
            tier_mutation_intent_id_from_record_object_name(
                "tier/mutation-intents/records/12/34/12345678123456789abcdef012345678/extra.json"
            ),
            Err(TierMutationIntentError::Corrupt("intent record path is not canonical"))
        ));
        assert!(matches!(
            tier_mutation_intent_id_from_record_object_name(
                "tier/mutation-intents/records/12/34/12345678123456789ABCDEF012345678.json"
            ),
            Err(TierMutationIntentError::Corrupt("intent record path has invalid mutation id"))
        ));
    }

    #[test]
    fn intent_decode_rejects_record_key_mismatch() {
        let intent = prepared_intent();
        let encoded = intent.encode().expect("intent should encode");
        let wrong_id = Uuid::new_v4();

        assert!(matches!(
            TierMutationIntent::decode(wrong_id, &encoded),
            Err(TierMutationIntentError::Corrupt("mutation_id does not match intent key"))
        ));
    }

    #[test]
    fn intent_validation_rejects_target_shape_mismatch() {
        let mut add = prepared_intent();
        add.kind = TierMutationIntentKind::Add;
        assert!(matches!(
            add.validate(),
            Err(TierMutationIntentError::Corrupt(
                "target backend identity shape does not match mutation kind"
            ))
        ));

        let mut remove = prepared_intent();
        remove.kind = TierMutationIntentKind::Remove;
        assert!(matches!(
            remove.validate(),
            Err(TierMutationIntentError::Corrupt(
                "target backend identity shape does not match mutation kind"
            ))
        ));

        let mut clear_without_etag = prepared_intent();
        clear_without_etag.kind = TierMutationIntentKind::Clear;
        clear_without_etag.old_config_etag = None;
        clear_without_etag.affected_targets[0].new_backend_identity = None;
        assert!(matches!(
            clear_without_etag.validate(),
            Err(TierMutationIntentError::Corrupt("old config etag is required for mutation kind"))
        ));
    }
}