chorus-client 0.1.0

Quorum write-ahead log for databases over GCS Rapid zonal buckets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
//! The manifest register: the Chorus control plane.
//!
//! The register is one tiny versioned document behind the pluggable
//! [`crate::ManifestStore`] interface. The default backend keeps it as
//! object metadata on one `<prefix>/manifest` object in a **regional** GCS
//! bucket: created once with `if_generation_match=0` and a constant empty
//! body, afterwards mutated only by metageneration-guarded `UpdateObject`. GCS gives every bucket strongly consistent reads and
//! preconditions, and a regional bucket is replicated across zones by the
//! provider, so that single object is a linearizable, zone-fault-tolerant
//! compare-and-swap register. Every control-plane decision the log takes —
//! granting a writer epoch, committing a recovery view, preregistering or
//! folding a pending segment, sealing a segment, and advancing the truncation
//! floor — is one CAS on the register, which makes each decision unique
//! without any client-side quorum or consensus round.
//! A single preregistered successor (`chorus.pending_id`) keeps that CAS out
//! of the append rotation path: rotation consumes the already-created object
//! in memory, then background maintenance folds the sealed tail and refills
//! the pending slot in one off-path CAS.
//!
//! The register is never deleted or recreated, so its history cannot be
//! erased by data repair. The data plane (segment appends, acknowledgments,
//! takeover and finalization fencing) stays entirely on the zonal Rapid
//! buckets; the register sees only rare control transitions where its
//! latency is irrelevant.
//!
//! The register also carries the sealed segment directory
//! (`chorus.segments`): every committed seal joins it in the seal's own CAS,
//! and truncation removes an entry only after the segment's copy is
//! confirmed deleted on every zone. The directory is the chain authority —
//! recovery adopts it without listing buckets or re-reading sealed bytes —
//! and its byte budget caps how many sealed segments the WAL retains.

use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet};
use std::hash::{BuildHasher, Hasher};
use std::sync::Arc;

use crate::manifest_store::{ManifestStore, ManifestStoreError, ManifestVersion};
use crate::metrics::Metrics;
use crate::protocol::{retry_sleep, ClientConfig, ProtocolError, SUPPORTED_REPLICA_COUNTS};

/// Object name of the control register, relative to the WAL prefix.
pub(crate) const MANIFEST_OBJECT: &str = "manifest";

const META_FORMAT: &str = "chorus.format";
/// The one supported register format. Structural validation does the real
/// gating: a register without the authoritative `chorus.segments` directory,
/// a directory entry that lacks its CRC32C, or the ordered `chorus.buckets`
/// replica binding is rejected at decode rather than migrated. Development
/// builds with those older shapes carried this same marker, so old binaries
/// must not share a register with new ones.
const FORMAT_VERSION: &str = "1";
const META_EPOCH: &str = "chorus.epoch";
const META_OWNER: &str = "chorus.owner";
const META_TAIL_BASE: &str = "chorus.tail_base";
const META_TAIL_ID: &str = "chorus.tail_id";
const META_PENDING_ID: &str = "chorus.pending_id";
const META_SEAL_ID: &str = "chorus.seal_id";
const META_SEAL_BASE: &str = "chorus.seal_base";
const META_SEAL_DIGEST: &str = "chorus.seal_digest";
const META_TRUNC: &str = "chorus.trunc";
const META_SEGMENTS: &str = "chorus.segments";
const META_BUCKETS: &str = "chorus.buckets";

const MAX_CAS_ROUNDS: usize = 16;

#[derive(Clone, Debug, Eq, PartialEq)]
/// One sealed chain member recorded in the register's segment directory.
/// Ends derive from contiguity — each entry ends one record before the next
/// entry's base, and the last entry ends at `tail_base - 1` — so the encoding
/// cannot disagree with the chain. Every entry carries the full-object
/// checksum of its exact sealed bytes.
pub(crate) struct DirectoryEntry {
    /// Opaque segment object id under `<prefix>/segments/`.
    pub id: String,
    /// First global record index of the segment.
    pub base: u64,
    /// Full-object CRC32C of the sealed bytes.
    pub crc32c: u32,
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// The manifest register contents.
pub(crate) struct ManifestRecord {
    /// Highest writer epoch granted.
    pub epoch: u64,
    /// Random incarnation id the epoch was granted to.
    pub owner: String,
    /// Base record index of the active appendable segment.
    pub tail_base: u64,
    /// Opaque object id of the active appendable segment. It is absent only in
    /// the uninitialized register; recovery commits a bootstrap id before
    /// conditionally creating the first segment.
    pub tail_id: Option<String>,
    /// One pre-created, stream-open successor authorized for the next
    /// rotation. Legacy registers omit the field and decode as no pending
    /// segment.
    pub pending_id: Option<String>,
    /// Base of the most recently sealed segment, absent until the first seal.
    pub seal_base: Option<u64>,
    /// Opaque object id of the most recently sealed segment.
    pub seal_id: Option<String>,
    /// SHA-256 hex digest of that segment's exact sealed bytes.
    pub seal_digest: Option<String>,
    /// Truncation floor: the first record index the log still retains.
    pub trunc: u64,
    /// The sealed segment directory, ordered by base: every committed seal
    /// that has not yet been deleted from all zones. Entries whose derived
    /// end lies below `trunc` are tombstones — chain history already
    /// truncated, retained only until every zonal copy is confirmed gone, so
    /// startup and periodic maintenance sweep a zone that slept through the
    /// original deletion pass without relisting the bucket.
    pub segments: Vec<DirectoryEntry>,
    /// Ordered zonal bucket names. The list length is the replica count used
    /// for quorum membership, so the field is required and exact identity and
    /// order are checked on every open.
    pub buckets: Vec<String>,
}

fn validate_bucket_names(buckets: &[String]) -> Result<(), ProtocolError> {
    if buckets.is_empty() {
        return Err(ProtocolError::InvalidManifest(
            "chorus.buckets must not be empty".into(),
        ));
    }
    if !SUPPORTED_REPLICA_COUNTS.contains(&buckets.len()) {
        return Err(ProtocolError::InvalidManifest(format!(
            "chorus.buckets has unsupported replica count {}; expected 1, 3, or 5",
            buckets.len()
        )));
    }
    let mut unique = HashSet::new();
    for bucket in buckets {
        if bucket.is_empty() || bucket.contains(',') {
            return Err(ProtocolError::InvalidManifest(format!(
                "invalid bucket name {bucket:?}"
            )));
        }
        if !unique.insert(bucket.as_str()) {
            return Err(ProtocolError::InvalidManifest(format!(
                "chorus.buckets repeats bucket {bucket}"
            )));
        }
    }
    Ok(())
}

impl ManifestRecord {
    fn initial(buckets: Vec<String>) -> Self {
        Self {
            epoch: 0,
            owner: String::new(),
            tail_base: 0,
            tail_id: None,
            pending_id: None,
            seal_base: None,
            seal_id: None,
            seal_digest: None,
            trunc: 0,
            segments: Vec::new(),
            buckets,
        }
    }

    /// Encoded `chorus.segments` value: `id:base:crc32c` entries joined by
    /// commas, in base order. CRC32C is exactly eight lowercase hexadecimal
    /// characters.
    fn encode_segments(segments: &[DirectoryEntry]) -> String {
        segments
            .iter()
            .map(|entry| format!("{}:{}:{:08x}", entry.id, entry.base, entry.crc32c))
            .collect::<Vec<_>>()
            .join(",")
    }

    fn decode_segments(value: &str) -> Result<Vec<DirectoryEntry>, ProtocolError> {
        let mut segments = Vec::new();
        if value.is_empty() {
            return Ok(segments);
        }
        for part in value.split(',') {
            let invalid =
                || ProtocolError::InvalidManifest(format!("invalid chorus.segments entry {part}"));
            let mut fields = part.split(':');
            let id = fields.next().ok_or_else(invalid)?;
            let base = fields.next().ok_or_else(invalid)?;
            let crc = fields.next().ok_or_else(invalid)?;
            if crc.len() != 8
                || !crc
                    .bytes()
                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
            {
                return Err(invalid());
            }
            let crc32c = u32::from_str_radix(crc, 16).map_err(|_| invalid())?;
            if fields.next().is_some() {
                return Err(invalid());
            }
            if id.is_empty() {
                return Err(invalid());
            }
            let base: u64 = base.parse().map_err(|_| invalid())?;
            if segments
                .last()
                .is_some_and(|previous: &DirectoryEntry| previous.base >= base)
            {
                return Err(ProtocolError::InvalidManifest(
                    "chorus.segments bases must be strictly increasing".into(),
                ));
            }
            segments.push(DirectoryEntry {
                id: id.to_string(),
                base,
                crc32c,
            });
        }
        Ok(segments)
    }

    fn decode_buckets(value: &str) -> Result<Vec<String>, ProtocolError> {
        if value.is_empty() {
            return Err(ProtocolError::InvalidManifest(
                "chorus.buckets must not be empty".into(),
            ));
        }
        Ok(value.split(',').map(str::to_string).collect())
    }

    fn encode(&self) -> HashMap<String, String> {
        let mut metadata = HashMap::from([
            (META_FORMAT.to_string(), FORMAT_VERSION.to_string()),
            (META_EPOCH.to_string(), self.epoch.to_string()),
            (META_OWNER.to_string(), self.owner.clone()),
            (META_TAIL_BASE.to_string(), self.tail_base.to_string()),
            (META_TRUNC.to_string(), self.trunc.to_string()),
            (
                META_SEGMENTS.to_string(),
                Self::encode_segments(&self.segments),
            ),
            (META_BUCKETS.to_string(), self.buckets.join(",")),
        ]);
        if let Some(tail_id) = &self.tail_id {
            metadata.insert(META_TAIL_ID.to_string(), tail_id.clone());
        }
        if let Some(pending_id) = &self.pending_id {
            metadata.insert(META_PENDING_ID.to_string(), pending_id.clone());
        }
        if let Some(seal_base) = self.seal_base {
            metadata.insert(META_SEAL_BASE.to_string(), seal_base.to_string());
        }
        if let Some(seal_id) = &self.seal_id {
            metadata.insert(META_SEAL_ID.to_string(), seal_id.clone());
        }
        if let Some(digest) = &self.seal_digest {
            metadata.insert(META_SEAL_DIGEST.to_string(), digest.clone());
        }
        metadata
    }

    fn decode(metadata: &HashMap<String, String>) -> Result<Self, ProtocolError> {
        if metadata.get(META_FORMAT).map(String::as_str) != Some(FORMAT_VERSION) {
            return Err(ProtocolError::InvalidManifest(
                "manifest does not use chorus.format=1".into(),
            ));
        }
        let segments = Self::decode_segments(metadata.get(META_SEGMENTS).ok_or_else(|| {
            ProtocolError::InvalidManifest("manifest lacks chorus.segments".into())
        })?)?;
        let field = |key: &str| -> Result<u64, ProtocolError> {
            metadata
                .get(key)
                .ok_or_else(|| ProtocolError::InvalidManifest(format!("manifest lacks {key}")))?
                .parse()
                .map_err(|_| ProtocolError::InvalidManifest(format!("invalid {key}")))
        };
        let seal_base = metadata
            .get(META_SEAL_BASE)
            .map(|value| {
                value
                    .parse()
                    .map_err(|_| ProtocolError::InvalidManifest("invalid chorus.seal_base".into()))
            })
            .transpose()?;
        let seal_digest = metadata.get(META_SEAL_DIGEST).cloned();
        let buckets = Self::decode_buckets(metadata.get(META_BUCKETS).ok_or_else(|| {
            ProtocolError::InvalidManifest("manifest lacks chorus.buckets".into())
        })?)?;
        let record = Self {
            epoch: field(META_EPOCH)?,
            owner: metadata.get(META_OWNER).cloned().unwrap_or_default(),
            tail_base: field(META_TAIL_BASE)?,
            tail_id: metadata.get(META_TAIL_ID).cloned(),
            pending_id: metadata.get(META_PENDING_ID).cloned(),
            seal_base,
            seal_id: metadata.get(META_SEAL_ID).cloned(),
            seal_digest,
            trunc: field(META_TRUNC)?,
            segments,
            buckets,
        };
        record.validate()?;
        Ok(record)
    }

    fn validate(&self) -> Result<(), ProtocolError> {
        let invalid = |message: String| ProtocolError::InvalidManifest(message);
        if self.seal_base.is_some() != self.seal_digest.is_some() {
            return Err(invalid(
                "seal_base and seal_digest must appear together".into(),
            ));
        }
        // Truncation may advance past tail_base while the active segment remains unrotated.
        if self.epoch > 0 && self.tail_id.is_none() {
            return Err(invalid(
                "chorus.tail_id must be present once chorus.epoch is nonzero".into(),
            ));
        }
        let mut ids = HashSet::new();
        let mut previous_base = None;
        for entry in &self.segments {
            if previous_base.is_some_and(|base| base >= entry.base) {
                return Err(invalid(
                    "chorus.segments bases must be strictly increasing".into(),
                ));
            }
            if entry.base >= self.tail_base {
                return Err(invalid(format!(
                    "chorus.segments entry {} has base {} at or past chorus.tail_base {}",
                    entry.id, entry.base, self.tail_base
                )));
            }
            if !ids.insert(entry.id.as_str()) {
                return Err(invalid(format!(
                    "chorus.segments repeats segment id {}",
                    entry.id
                )));
            }
            previous_base = Some(entry.base);
        }
        if self
            .tail_id
            .as_deref()
            .is_some_and(|tail_id| ids.contains(tail_id))
        {
            return Err(invalid(
                "chorus.tail_id collides with a sealed segment id".into(),
            ));
        }
        if let Some(pending_id) = self.pending_id.as_deref() {
            if pending_id.is_empty() || pending_id.contains(':') || pending_id.contains(',') {
                return Err(invalid(format!("invalid chorus.pending_id {pending_id:?}")));
            }
            if self.tail_id.as_deref() == Some(pending_id) {
                return Err(invalid(
                    "chorus.pending_id collides with chorus.tail_id".into(),
                ));
            }
            if ids.contains(pending_id) {
                return Err(invalid(
                    "chorus.pending_id collides with a sealed segment id".into(),
                ));
            }
        }
        if self.tail_base > self.trunc {
            if let Some(last) = self.segments.last() {
                if self.seal_id.as_deref() != Some(last.id.as_str())
                    || self.seal_base != Some(last.base)
                {
                    return Err(invalid(format!(
                        "chorus.segments ends with {}:{} but the seal record names {:?}:{:?}",
                        last.id, last.base, self.seal_id, self.seal_base
                    )));
                }
            }
        }
        validate_bucket_names(&self.buckets)?;
        Ok(())
    }

    fn validate_removals(
        &self,
        ids: &HashSet<String>,
        witnessed_floor: u64,
    ) -> Result<(), ProtocolError> {
        if witnessed_floor > self.trunc {
            return Err(ProtocolError::InvalidManifest(format!(
                "segment removal floor {witnessed_floor} exceeds committed truncation floor {}",
                self.trunc
            )));
        }
        for (index, entry) in self.segments.iter().enumerate() {
            if !ids.contains(&entry.id) {
                continue;
            }
            let next_base = self
                .segments
                .get(index + 1)
                .map_or(self.tail_base, |next| next.base);
            let end = next_base.checked_sub(1).ok_or_else(|| {
                ProtocolError::InvalidManifest(format!(
                    "cannot derive an end for segment {} at base {}",
                    entry.id, entry.base
                ))
            })?;
            if end >= witnessed_floor {
                return Err(ProtocolError::InvalidManifest(format!(
                    "cannot remove segment {} ending at {end} at truncation floor {witnessed_floor}",
                    entry.id
                )));
            }
        }
        Ok(())
    }

    /// Whether the directory can take `additional` more entries within the
    /// backend-provided byte budget. Sized against the worst case (a
    /// full-width id and base) so the answer cannot flip between the check and
    /// the fold CAS that relies on it.
    fn directory_has_room(&self, additional: usize, max_directory_bytes: usize) -> bool {
        directory_has_room_for(
            Self::encode_segments(&self.segments).len(),
            additional,
            max_directory_bytes,
        )
    }
}

/// A random 128-bit incarnation id. Uniqueness is the only requirement; the
/// entropy comes from the OS through `RandomState`'s per-instance seeding, so
/// no clock enters protocol logic.
pub(crate) fn incarnation_id() -> String {
    let mut id = String::with_capacity(32);
    for word in 0..2u64 {
        let mut hasher = RandomState::new().build_hasher();
        hasher.write_u64(word);
        id.push_str(&format!("{:016x}", hasher.finish()));
    }
    id
}

/// Whether a directory whose entries currently encode to `current_encoded_len`
/// bytes can take `additional` more entries within `max_directory_bytes`. Sized
/// against the worst case (a full-width id and base) so the answer cannot flip
/// between a capacity check and the fold CAS that relies on it.
pub(crate) fn directory_has_room_for(
    current_encoded_len: usize,
    additional: usize,
    max_directory_bytes: usize,
) -> bool {
    // `{epoch:016x}-{seq:08x}` id (the seq pads to 8 hex digits but is only
    // debug-asserted below u32::MAX, so budget a full u64), a u64 base in
    // decimal, an eight-digit CRC32C, and separators
    const WORST_CASE_ENTRY_BYTES: usize = 16 + 1 + 16 + 1 + 20 + 1 + 8 + 1;
    additional
        .checked_mul(WORST_CASE_ENTRY_BYTES)
        .and_then(|reserved| current_encoded_len.checked_add(reserved))
        .is_some_and(|required| required <= max_directory_bytes)
}

/// A fresh segment id under one claimed epoch.
pub(crate) fn segment_id(epoch: u64, seq: u64) -> String {
    debug_assert!(seq <= u64::from(u32::MAX));
    format!("{epoch:016x}-{seq:08x}")
}

/// The manifest register plus this process's claim state.
pub(crate) struct Manifest {
    store: Arc<dyn ManifestStore>,
    config: ClientConfig,
    owner: String,
    epoch: u64,
    bucket_names: Vec<String>,
    max_directory_bytes: usize,
    cache: (ManifestVersion, ManifestRecord),
    metrics: Arc<Metrics>,
}

#[derive(Clone)]
/// Claim-bound capability used by background provisioning and fold work.
///
/// Each operation opens a fresh register view and rechecks `(epoch, owner)`
/// inside its CAS transform. A stale worker therefore fences instead of
/// publishing state for a later incarnation.
pub(crate) struct ManifestAccess {
    store: Arc<dyn ManifestStore>,
    config: ClientConfig,
    owner: String,
    epoch: u64,
    bucket_names: Vec<String>,
    max_directory_bytes: usize,
    cache: (ManifestVersion, ManifestRecord),
    metrics: Arc<Metrics>,
}

#[derive(Clone, Debug)]
/// A register state returned by an off-path manifest mutation.
pub(crate) struct ManifestUpdate {
    version: ManifestVersion,
    record: ManifestRecord,
}

#[derive(Clone)]
/// Inputs to the atomic fold/refill transition after a pending segment is
/// consumed by rotation.
pub(crate) struct PendingFold {
    pub old_tail_id: String,
    pub old_tail_base: u64,
    pub old_tail_end: u64,
    pub old_tail_digest: String,
    pub old_tail_crc32c: u32,
    pub consumed_pending_id: String,
    /// Tail id installed by the fold. Live rotation uses the consumed pending
    /// id; recovery may install a fresh id when a quorum-only empty pending
    /// observation cannot safely reuse the old name.
    pub successor_tail_id: String,
    pub refill_pending_id: String,
}

enum CasTransform<T> {
    Done(T),
    Update {
        record: Box<ManifestRecord>,
        value: T,
    },
}

impl Manifest {
    /// Read the register, conditionally creating it with the constant
    /// initial record when missing. `replica_count` is the configured number
    /// of zonal data factories; it must equal the required `chorus.buckets`
    /// length because every quorum decision in the WAL's history is taken
    /// against that ordered membership.
    pub async fn open(
        store: Arc<dyn ManifestStore>,
        config: ClientConfig,
        metrics: Arc<Metrics>,
        replica_count: usize,
        bucket_names: Vec<String>,
    ) -> Result<Self, ProtocolError> {
        validate_bucket_names(&bucket_names)?;
        if replica_count != bucket_names.len() {
            return Err(ProtocolError::InvalidManifest(format!(
                "volume has {replica_count} replica factories but {} bucket identities",
                bucket_names.len()
            )));
        }
        let max_directory_bytes = store.max_directory_bytes();
        let initial = ManifestRecord::initial(bucket_names.clone());
        initial.validate()?;
        let mut manifest = Self {
            store,
            config,
            owner: incarnation_id(),
            epoch: 0,
            bucket_names,
            max_directory_bytes,
            // `refresh` replaces this before `open` returns. Keeping a
            // structurally valid cache makes the post-open invariant
            // type-enforced instead of relying on `expect` in protocol paths.
            cache: (ManifestVersion(0), initial),
            metrics,
        };
        manifest.refresh().await?;
        Ok(manifest)
    }

    fn validate_configuration(&self, record: &ManifestRecord) -> Result<(), ProtocolError> {
        if record.buckets.len() != self.bucket_names.len() {
            return Err(ProtocolError::InvalidManifest(format!(
                "manifest records {} zonal buckets but the volume is configured with {} replicas",
                record.buckets.len(),
                self.bucket_names.len()
            )));
        }
        if record.buckets != self.bucket_names {
            return Err(ProtocolError::InvalidManifest(format!(
                "manifest records buckets {:?} but the volume is configured with {:?}",
                record.buckets, self.bucket_names
            )));
        }
        Ok(())
    }

    async fn refresh(&mut self) -> Result<(), ProtocolError> {
        for attempt in 0..=self.config.max_retries {
            match self.store.read().await {
                Ok(Some(state)) => {
                    let record = ManifestRecord::decode(&state.fields)?;
                    self.validate_configuration(&record)?;
                    self.install_cache(state.version, record);
                    return Ok(());
                }
                Ok(None) => {
                    let initial = ManifestRecord::initial(self.bucket_names.clone());
                    initial.validate()?;
                    match self.store.create(initial.encode()).await {
                        Ok(state) => {
                            self.install_cache(state.version, initial);
                            return Ok(());
                        }
                        Err(ManifestStoreError::AlreadyExists | ManifestStoreError::Conflict) => {
                            continue
                        }
                        Err(ManifestStoreError::Unavailable(_)) => {}
                        Err(error) => return Err(error.into()),
                    }
                }
                Err(ManifestStoreError::Unavailable(_)) => {}
                Err(error) => return Err(error.into()),
            }
            retry_sleep(&self.config, attempt).await;
        }
        Err(ProtocolError::ManifestUnavailable)
    }

    /// The current register contents.
    pub fn record(&self) -> &ManifestRecord {
        &self.cache.1
    }

    /// A cloneable, claim-bound handle for work that must not block the
    /// append engine.
    pub(crate) fn off_path_access(&self) -> Result<ManifestAccess, ProtocolError> {
        if self.epoch == 0 {
            return Err(ProtocolError::Fenced(
                "manifest background access without a claim".into(),
            ));
        }
        Ok(ManifestAccess {
            store: Arc::clone(&self.store),
            config: self.config.clone(),
            owner: self.owner.clone(),
            epoch: self.epoch,
            bucket_names: self.bucket_names.clone(),
            max_directory_bytes: self.max_directory_bytes,
            cache: self.cache.clone(),
            metrics: Arc::clone(&self.metrics),
        })
    }

    /// Adopt a state returned by an off-path mutation without allowing a
    /// delayed worker result to regress the local cache.
    pub(crate) fn install_update(&mut self, update: ManifestUpdate) {
        if update.version.0 >= self.cache.0 .0 {
            self.install_cache(update.version, update.record);
        }
    }

    fn install_cache(&mut self, version: ManifestVersion, record: ManifestRecord) {
        self.metrics
            .manifest_directory_bytes
            .set_usize(ManifestRecord::encode_segments(&record.segments).len());
        self.cache = (version, record);
    }

    /// One guarded CAS request, timed for the latency histogram.
    async fn timed_update(
        &self,
        version: ManifestVersion,
        fields: HashMap<String, String>,
    ) -> Result<ManifestVersion, ManifestStoreError> {
        let started = tokio::time::Instant::now();
        let result = self.store.update(version, fields).await;
        self.metrics
            .manifest_cas_latency
            .record_duration(started.elapsed());
        result.map(|state| state.version)
    }

    /// Apply one typed record transform through the manifest CAS register.
    ///
    /// Every mutator shares the same conflict refresh, retry exhaustion, metric
    /// accounting, validation, and cache installation. The closure contains
    /// only operation-specific protocol checks and the candidate mutation.
    async fn cas_transform<T>(
        &mut self,
        exhausted: ProtocolError,
        mut transform: impl FnMut(&ManifestRecord) -> Result<CasTransform<T>, ProtocolError>,
    ) -> Result<T, ProtocolError> {
        for _ in 0..MAX_CAS_ROUNDS {
            let (version, record) = self.cache.clone();
            let (next, value) = match transform(&record)? {
                CasTransform::Done(value) => return Ok(value),
                CasTransform::Update { record, value } => (*record, value),
            };
            next.validate()?;
            self.metrics.manifest_cas_attempts.increment();
            match self.timed_update(version, next.encode()).await {
                Ok(updated) => {
                    self.install_cache(updated, next);
                    return Ok(value);
                }
                Err(
                    error @ (ManifestStoreError::Conflict | ManifestStoreError::Unavailable(_)),
                ) => {
                    if matches!(error, ManifestStoreError::Conflict) {
                        self.metrics.manifest_cas_conflicts.increment();
                    }
                    self.refresh().await?;
                }
                Err(error) => return Err(error.into()),
            }
        }
        Err(exhausted)
    }

    /// Claim a fresh epoch: one CAS raising `epoch` to a value the register
    /// has never granted. The register linearizes claims, so at most one
    /// incarnation ever owns an epoch.
    pub async fn claim(&mut self) -> Result<(), ProtocolError> {
        let owner = self.owner.clone();
        let candidate = self
            .cas_transform(
                ProtocolError::Fenced(
                    "manifest epoch claim did not converge under contention".into(),
                ),
                |record| {
                    let candidate = record.epoch.checked_add(1).ok_or_else(|| {
                        ProtocolError::InvalidManifest("epoch overflowed u64".into())
                    })?;
                    let mut claimed = record.clone();
                    claimed.epoch = candidate;
                    claimed.owner = owner.clone();
                    if claimed.tail_id.is_none() {
                        claimed.tail_id = Some(segment_id(candidate, 0));
                    }
                    Ok(CasTransform::Update {
                        record: Box::new(claimed),
                        value: candidate,
                    })
                },
            )
            .await?;
        self.epoch = candidate;
        Ok(())
    }

    /// Commit a view: `tail_base` and the most recent seal, in one CAS that
    /// re-validates `(epoch, owner)` under the metageneration guard. Fails
    /// with [`ProtocolError::Fenced`] once a higher epoch has been granted.
    ///
    /// The same CAS maintains the segment directory: a commit that moves
    /// `seal_id` to a new id is a seal decision, and the sealed segment's
    /// `(id, base, crc32c)` joins `chorus.segments` in that single write — the
    /// directory is exactly the set of committed seals not yet deleted from
    /// every zone, at no additional RPC. A full directory fails the seal
    /// with [`ProtocolError::SegmentDirectoryFull`]; the engine defers
    /// rotation before reaching that state, and truncation frees entries.
    #[cfg(test)]
    pub async fn commit_view(
        &mut self,
        tail_base: u64,
        tail_id: Option<String>,
        seal_base: Option<u64>,
        seal_id: Option<String>,
        seal_digest: Option<String>,
        new_seal_crc32c: Option<u32>,
    ) -> Result<(), ProtocolError> {
        if self.epoch == 0 {
            return Err(ProtocolError::Fenced("view commit without a claim".into()));
        }
        let epoch = self.epoch;
        let owner = self.owner.clone();
        let max_directory_bytes = self.max_directory_bytes;
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            if record.epoch != epoch || record.owner != owner {
                return Err(ProtocolError::Fenced(
                    "a higher epoch claimed the manifest".into(),
                ));
            }
            if record.tail_base == tail_base
                && record.tail_id == tail_id
                && record.seal_base == seal_base
                && record.seal_id == seal_id
                && record.seal_digest == seal_digest
            {
                if let Some(expected_crc32c) = new_seal_crc32c {
                    let committed_crc32c = record
                        .segments
                        .last()
                        .filter(|entry| {
                            Some(entry.id.as_str()) == seal_id.as_deref()
                                && Some(entry.base) == seal_base
                        })
                        .map(|entry| entry.crc32c);
                    if committed_crc32c != Some(expected_crc32c) {
                        return Err(ProtocolError::InvalidManifest(format!(
                            "committed seal checksum {committed_crc32c:?} differs from retry {expected_crc32c:08x}"
                        )));
                    }
                }
                return Ok(CasTransform::Done(()));
            }
            let mut next = record.clone();
            next.tail_base = tail_base;
            next.tail_id = tail_id.clone();
            next.seal_base = seal_base;
            next.seal_id = seal_id.clone();
            next.seal_digest = seal_digest.clone();
            if let Some(new_seal_id) = seal_id
                .clone()
                .filter(|new_seal_id| Some(new_seal_id) != record.seal_id.as_ref())
            {
                if !next.directory_has_room(1, max_directory_bytes) {
                    return Err(ProtocolError::SegmentDirectoryFull);
                }
                let entry = DirectoryEntry {
                    id: new_seal_id,
                    base: seal_base.ok_or_else(|| {
                        ProtocolError::InvalidManifest("seal commit without a seal_base".into())
                    })?,
                    crc32c: new_seal_crc32c.ok_or_else(|| {
                        ProtocolError::InvalidManifest("new seal commit without a CRC32C".into())
                    })?,
                };
                if next
                    .segments
                    .last()
                    .is_some_and(|previous| previous.base >= entry.base)
                {
                    return Err(ProtocolError::InvalidManifest(
                        "sealed segment base regresses the directory".into(),
                    ));
                }
                next.segments.push(entry);
            } else if new_seal_crc32c.is_some() {
                return Err(ProtocolError::InvalidManifest(
                    "CRC32C supplied without a new seal".into(),
                ));
            }
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    /// Authorize one already-created successor. The segment is not eligible
    /// for rotation until this CAS succeeds or a retry re-reads the same id.
    pub(crate) async fn register_pending(
        &mut self,
        pending_id: String,
    ) -> Result<(), ProtocolError> {
        self.require_claim()?;
        let epoch = self.epoch;
        let owner = self.owner.clone();
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            Self::check_claim(record, epoch, &owner)?;
            match record.pending_id.as_deref() {
                Some(committed) if committed == pending_id => {
                    return Ok(CasTransform::Done(()));
                }
                Some(committed) => {
                    return Err(ProtocolError::Fenced(format!(
                        "pending segment slot already contains {committed}"
                    )));
                }
                None => {}
            }
            let mut next = record.clone();
            next.pending_id = Some(pending_id.clone());
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    /// Replace an absent or otherwise unusable empty frontier with two newly
    /// created objects. No seal is recorded because no committed record is
    /// skipped.
    pub(crate) async fn replace_empty_frontier(
        &mut self,
        expected_tail_id: Option<&str>,
        expected_pending_id: Option<&str>,
        tail_base: u64,
        active_id: String,
        pending_id: String,
    ) -> Result<(), ProtocolError> {
        self.require_claim()?;
        let epoch = self.epoch;
        let owner = self.owner.clone();
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            Self::check_claim(record, epoch, &owner)?;
            if record.tail_id.as_deref() == Some(active_id.as_str())
                && record.pending_id.as_deref() == Some(pending_id.as_str())
                && record.tail_base == tail_base
            {
                return Ok(CasTransform::Done(()));
            }
            if record.tail_id.as_deref() != expected_tail_id
                || record.pending_id.as_deref() != expected_pending_id
                || record.tail_base != tail_base
            {
                return Err(ProtocolError::Fenced(
                    "manifest no longer matches the empty frontier".into(),
                ));
            }
            let mut next = record.clone();
            next.tail_id = Some(active_id.clone());
            next.pending_id = Some(pending_id.clone());
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    /// Atomically fold the consumed tail into the sealed directory, advance
    /// the active tail, and refill the single pending slot.
    pub(crate) async fn fold_pending(&mut self, fold: &PendingFold) -> Result<(), ProtocolError> {
        self.require_claim()?;
        let epoch = self.epoch;
        let owner = self.owner.clone();
        let max_directory_bytes = self.max_directory_bytes;
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            Self::check_claim(record, epoch, &owner)?;
            if record.tail_id.as_deref() == Some(fold.successor_tail_id.as_str())
                && record.tail_base == fold.old_tail_end.saturating_add(1)
                && record.pending_id.as_deref() == Some(fold.refill_pending_id.as_str())
                && record.seal_id.as_deref() == Some(fold.old_tail_id.as_str())
                && record.seal_base == Some(fold.old_tail_base)
                && record.seal_digest.as_deref() == Some(fold.old_tail_digest.as_str())
            {
                let committed_crc32c = record
                    .segments
                    .last()
                    .filter(|entry| {
                        entry.id == fold.old_tail_id && entry.base == fold.old_tail_base
                    })
                    .map(|entry| entry.crc32c);
                if committed_crc32c != Some(fold.old_tail_crc32c) {
                    return Err(ProtocolError::InvalidManifest(format!(
                        "committed fold checksum {committed_crc32c:?} differs from retry {:08x}",
                        fold.old_tail_crc32c
                    )));
                }
                return Ok(CasTransform::Done(()));
            }
            if record.tail_id.as_deref() != Some(fold.old_tail_id.as_str())
                || record.tail_base != fold.old_tail_base
                || record.pending_id.as_deref() != Some(fold.consumed_pending_id.as_str())
            {
                return Err(ProtocolError::Fenced(
                    "manifest no longer matches the pending fold".into(),
                ));
            }
            if fold.old_tail_end.checked_add(1).is_none() {
                return Err(ProtocolError::InvalidManifest(
                    "pending fold tail end overflowed u64".into(),
                ));
            }
            if !record.directory_has_room(1, max_directory_bytes) {
                return Err(ProtocolError::SegmentDirectoryFull);
            }
            let mut next = record.clone();
            next.segments.push(DirectoryEntry {
                id: fold.old_tail_id.clone(),
                base: fold.old_tail_base,
                crc32c: fold.old_tail_crc32c,
            });
            next.tail_base = fold.old_tail_end + 1;
            next.tail_id = Some(fold.successor_tail_id.clone());
            next.pending_id = Some(fold.refill_pending_id.clone());
            next.seal_base = Some(fold.old_tail_base);
            next.seal_id = Some(fold.old_tail_id.clone());
            next.seal_digest = Some(fold.old_tail_digest.clone());
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    fn require_claim(&self) -> Result<(), ProtocolError> {
        if self.epoch == 0 {
            return Err(ProtocolError::Fenced(
                "manifest mutation without a claim".into(),
            ));
        }
        Ok(())
    }

    fn check_claim(record: &ManifestRecord, epoch: u64, owner: &str) -> Result<(), ProtocolError> {
        if record.epoch != epoch || record.owner != owner {
            return Err(ProtocolError::Fenced(
                "a higher epoch claimed the manifest".into(),
            ));
        }
        Ok(())
    }

    /// Raise the truncation floor monotonically. Any role may do this; the
    /// CAS preserves every other field.
    pub async fn raise_trunc(&mut self, floor: u64) -> Result<(), ProtocolError> {
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            if record.trunc >= floor {
                return Ok(CasTransform::Done(()));
            }
            let mut next = record.clone();
            next.trunc = floor;
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    /// Drop directory entries whose every zonal copy is confirmed deleted.
    /// Epoch-free like [`Self::raise_trunc`] — the truncator discipline only
    /// removes entries wholly below `witnessed_floor`, which must itself be no
    /// higher than the current committed floor. The caller must also have
    /// confirmed every zonal copy absent. Rechecking derived ends against each
    /// CAS retry prevents a future caller from dropping reachable history. Ids
    /// already absent are fine: a racing pass removed them first.
    pub async fn remove_segments(
        &mut self,
        ids: &HashSet<String>,
        witnessed_floor: u64,
    ) -> Result<(), ProtocolError> {
        if ids.is_empty() {
            return Ok(());
        }
        self.cas_transform(ProtocolError::ManifestUnavailable, |record| {
            record.validate_removals(ids, witnessed_floor)?;
            if !record.segments.iter().any(|entry| ids.contains(&entry.id)) {
                return Ok(CasTransform::Done(()));
            }
            let mut next = record.clone();
            next.segments.retain(|entry| !ids.contains(&entry.id));
            Ok(CasTransform::Update {
                record: Box::new(next),
                value: (),
            })
        })
        .await
    }

    /// The register's store handle (for epoch-free readers like the
    /// maintenance task to open their own register view).
    pub(crate) fn store(&self) -> Arc<dyn ManifestStore> {
        Arc::clone(&self.store)
    }

    pub(crate) fn bucket_names(&self) -> &[String] {
        &self.bucket_names
    }

    /// Whether the current directory can reserve entries within this
    /// manifest store's captured capacity.
    pub(crate) fn directory_has_room(&self, additional: usize) -> bool {
        self.record()
            .directory_has_room(additional, self.max_directory_bytes)
    }

    /// Re-read the register and return its current contents.
    pub async fn refreshed_record(&mut self) -> Result<ManifestRecord, ProtocolError> {
        self.refresh().await?;
        Ok(self.record().clone())
    }

    /// Re-read the register and confirm this process still holds the epoch.
    pub async fn validate_owner(&mut self) -> Result<(), ProtocolError> {
        self.refresh().await?;
        let record = self.record();
        if record.epoch != self.epoch || record.owner != self.owner {
            return Err(ProtocolError::Fenced(
                "a higher epoch claimed the manifest".into(),
            ));
        }
        Ok(())
    }
}

impl ManifestAccess {
    async fn open_claimed(&self) -> Result<Manifest, ProtocolError> {
        let manifest = Manifest {
            store: Arc::clone(&self.store),
            config: self.config.clone(),
            owner: self.owner.clone(),
            epoch: self.epoch,
            bucket_names: self.bucket_names.clone(),
            max_directory_bytes: self.max_directory_bytes,
            cache: self.cache.clone(),
            metrics: Arc::clone(&self.metrics),
        };
        Ok(manifest)
    }

    pub(crate) async fn register_pending(
        &self,
        pending_id: String,
    ) -> Result<ManifestUpdate, ProtocolError> {
        let mut manifest = self.open_claimed().await?;
        manifest.register_pending(pending_id).await?;
        Ok(ManifestUpdate {
            version: manifest.cache.0,
            record: manifest.cache.1,
        })
    }

    pub(crate) async fn fold_pending(
        &self,
        fold: PendingFold,
    ) -> Result<ManifestUpdate, ProtocolError> {
        let mut manifest = self.open_claimed().await?;
        manifest.fold_pending(&fold).await?;
        Ok(ManifestUpdate {
            version: manifest.cache.0,
            record: manifest.cache.1,
        })
    }
}

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

    use super::*;
    use crate::manifest_store::{test_support::InMemoryManifestStore, GCS_MAX_DIRECTORY_BYTES};
    use crate::metrics::NoopMetricsRecorder;

    fn test_buckets(replicas: u64) -> Vec<String> {
        (0..replicas).map(|zone| format!("zone-{zone}")).collect()
    }

    fn initial_record(replicas: u64) -> ManifestRecord {
        ManifestRecord::initial(test_buckets(replicas))
    }

    fn valid_record() -> ManifestRecord {
        ManifestRecord {
            epoch: 7,
            owner: "abc".into(),
            tail_base: 10,
            tail_id: Some("tail".into()),
            pending_id: Some("pending".into()),
            seal_base: Some(5),
            seal_id: Some("sealed-b".into()),
            seal_digest: Some("d".repeat(64)),
            trunc: 0,
            segments: vec![
                DirectoryEntry {
                    id: "sealed-a".into(),
                    base: 0,
                    crc32c: 0x0123_4567,
                },
                DirectoryEntry {
                    id: "sealed-b".into(),
                    base: 5,
                    crc32c: 0x1234_abcd,
                },
            ],
            buckets: test_buckets(3),
        }
    }

    #[test]
    fn record_roundtrip() {
        let record = valid_record();
        assert_eq!(
            ManifestRecord::decode(&record.encode()).expect("roundtrip"),
            record
        );
    }

    #[test]
    fn manifest_without_a_segment_directory_is_rejected() {
        let mut metadata = initial_record(3).encode();
        metadata.remove("chorus.segments");
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn directory_decode_rejects_unordered_and_malformed_entries() {
        assert!(ManifestRecord::decode_segments("a:5:00000001,b:5:00000002").is_err());
        assert!(ManifestRecord::decode_segments("a:5:00000001,b:4:00000002").is_err());
        assert!(ManifestRecord::decode_segments(":5:00000000").is_err());
        assert!(ManifestRecord::decode_segments("a").is_err());
        assert!(ManifestRecord::decode_segments("a:x:00000000").is_err());
        assert!(matches!(
            ManifestRecord::decode_segments("a:0"),
            Err(ProtocolError::InvalidManifest(_))
        ));
        assert!(ManifestRecord::decode_segments("a:0:123").is_err());
        assert!(ManifestRecord::decode_segments("a:0:1234ABCD").is_err());
        assert!(ManifestRecord::decode_segments("a:0:1234abcg").is_err());
        assert!(ManifestRecord::decode_segments("a:0:1234abcd:extra").is_err());
        assert_eq!(
            ManifestRecord::decode_segments("").expect("empty"),
            Vec::new()
        );
    }

    #[test]
    fn directory_encoding_roundtrips_checksummed_entries() {
        let entries = vec![
            DirectoryEntry {
                id: "sealed-a".into(),
                base: 0,
                crc32c: 0x0123_4567,
            },
            DirectoryEntry {
                id: "sealed-b".into(),
                base: 5,
                crc32c: 0x1234_abcd,
            },
        ];
        let encoded = ManifestRecord::encode_segments(&entries);
        assert_eq!(encoded, "sealed-a:0:01234567,sealed-b:5:1234abcd");
        assert_eq!(
            ManifestRecord::decode_segments(&encoded).expect("checksummed directory"),
            entries
        );
    }

    #[test]
    fn manifest_decode_accepts_truncation_past_tail() {
        let mut record = valid_record();
        record.trunc = 11;
        assert_eq!(
            ManifestRecord::decode(&record.encode()).expect("truncation past active tail"),
            record
        );
    }

    #[test]
    fn manifest_decode_rejects_directory_base_at_tail() {
        let mut metadata = valid_record().encode();
        metadata.insert(
            META_SEGMENTS.into(),
            "sealed-a:0:01234567,sealed-b:10:1234abcd".into(),
        );
        metadata.insert(META_SEAL_BASE.into(), "10".into());
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn manifest_decode_rejects_duplicate_directory_ids() {
        let mut metadata = valid_record().encode();
        metadata.insert(
            META_SEGMENTS.into(),
            "sealed-a:0:01234567,sealed-a:5:1234abcd".into(),
        );
        metadata.insert(META_SEAL_ID.into(), "sealed-a".into());
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn manifest_decode_rejects_tail_id_in_directory() {
        let mut metadata = valid_record().encode();
        metadata.insert(META_TAIL_ID.into(), "sealed-b".into());
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn legacy_manifest_without_pending_id_decodes_as_none() {
        let mut metadata = valid_record().encode();
        metadata.remove(META_PENDING_ID);
        assert!(ManifestRecord::decode(&metadata)
            .expect("legacy manifest")
            .pending_id
            .is_none());
    }

    #[test]
    fn manifest_decode_rejects_pending_collisions_and_malformed_ids() {
        let mut metadata = valid_record().encode();
        metadata.insert(META_PENDING_ID.into(), "tail".into());
        assert!(ManifestRecord::decode(&metadata).is_err());

        let mut metadata = valid_record().encode();
        metadata.insert(META_PENDING_ID.into(), "sealed-a".into());
        assert!(ManifestRecord::decode(&metadata).is_err());

        let mut metadata = valid_record().encode();
        metadata.insert(META_PENDING_ID.into(), String::new());
        assert!(ManifestRecord::decode(&metadata).is_err());

        let mut metadata = valid_record().encode();
        metadata.insert(META_PENDING_ID.into(), "bad,id".into());
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn manifest_decode_rejects_seal_not_matching_last_directory_entry() {
        let mut metadata = valid_record().encode();
        metadata.insert(META_SEAL_ID.into(), "sealed-a".into());
        metadata.insert(META_SEAL_BASE.into(), "0".into());
        assert!(ManifestRecord::decode(&metadata).is_err());

        let mut metadata = valid_record().encode();
        metadata.insert(META_SEAL_BASE.into(), "4".into());
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn manifest_decode_rejects_nonzero_epoch_without_tail_id() {
        let mut metadata = valid_record().encode();
        metadata.remove(META_TAIL_ID);
        assert!(ManifestRecord::decode(&metadata).is_err());
    }

    #[test]
    fn all_truncated_directory_may_not_end_at_current_seal() {
        let mut record = valid_record();
        record.trunc = record.tail_base;
        record.seal_base = Some(9);
        record.seal_id = Some("already-removed".into());
        assert_eq!(
            ManifestRecord::decode(&record.encode()).expect("all-truncated manifest"),
            record
        );
    }

    #[test]
    fn directory_room_tracks_the_byte_budget() {
        let mut record = initial_record(3);
        let max_directory_bytes = InMemoryManifestStore::default().max_directory_bytes();
        assert!(record.directory_has_room(1, max_directory_bytes));
        let mut segments = Vec::new();
        let mut base = 0;
        while ManifestRecord::encode_segments(&segments).len() <= max_directory_bytes {
            segments.push(DirectoryEntry {
                id: format!("{:016x}-{:08x}", 1, segments.len()),
                base,
                crc32c: base as u32,
            });
            base += 1;
        }
        record.segments = segments;
        assert!(!record.directory_has_room(1, max_directory_bytes));
    }

    #[tokio::test]
    async fn higher_capacity_store_admits_more_directory_entries() {
        let store = Arc::new(InMemoryManifestStore::default());
        let larger_budget = store.max_directory_bytes();
        assert!(larger_budget > GCS_MAX_DIRECTORY_BYTES);

        let mut record = initial_record(3);
        record.tail_id = Some("tail".into());
        while record.directory_has_room(1, GCS_MAX_DIRECTORY_BYTES) {
            let base = record.segments.len() as u64;
            let id = format!("{:016x}-{base:08x}", 1);
            record.segments.push(DirectoryEntry {
                id: id.clone(),
                base,
                crc32c: base as u32,
            });
            record.tail_base = base + 1;
            record.seal_base = Some(base);
            record.seal_id = Some(id);
            record.seal_digest = Some("d".repeat(64));
        }
        assert!(!record.directory_has_room(1, GCS_MAX_DIRECTORY_BYTES));
        assert!(record.directory_has_room(1, larger_budget));

        store
            .create(record.encode())
            .await
            .expect("seed higher-capacity manifest");
        let store: Arc<dyn ManifestStore> = store;
        let metrics = Arc::new(Metrics::new(&NoopMetricsRecorder, 3));
        let manifest = Manifest::open(
            store,
            ClientConfig {
                max_retries: 0,
                retry_base: Duration::ZERO,
            },
            metrics,
            3,
            test_buckets(3),
        )
        .await
        .expect("open higher-capacity manifest");

        assert!(manifest.directory_has_room(1));
    }

    #[test]
    fn initial_record_roundtrip_has_no_seal() {
        let initial = initial_record(3);
        let encoded = initial.encode();
        // the on-wire marker is part of the format contract; pin the
        // literal so a constant edit cannot drift silently
        assert_eq!(encoded.get("chorus.format").map(String::as_str), Some("1"));
        assert_eq!(
            encoded.get(META_BUCKETS).map(String::as_str),
            Some("zone-0,zone-1,zone-2")
        );
        let decoded = ManifestRecord::decode(&encoded).expect("roundtrip");
        assert_eq!(decoded, initial);
        assert!(decoded.seal_base.is_none());
        assert!(decoded.pending_id.is_none());
    }

    #[test]
    fn replica_count_derives_from_required_bucket_binding() {
        let metadata = initial_record(5).encode();
        assert!(!metadata.contains_key("chorus.replicas"));
        let decoded = ManifestRecord::decode(&metadata).expect("five-replica manifest");
        assert_eq!(decoded.buckets.len(), 5);
    }

    #[test]
    fn manifest_without_bucket_binding_is_rejected() {
        let mut metadata = initial_record(3).encode();
        metadata.remove(META_BUCKETS);
        assert!(matches!(
            ManifestRecord::decode(&metadata),
            Err(ProtocolError::InvalidManifest(_))
        ));
    }

    #[test]
    fn manifest_rejects_empty_or_unsupported_bucket_counts() {
        let mut metadata = initial_record(3).encode();
        metadata.insert(META_BUCKETS.into(), String::new());
        assert!(matches!(
            ManifestRecord::decode(&metadata),
            Err(ProtocolError::InvalidManifest(_))
        ));

        metadata.insert(META_BUCKETS.into(), "zone-0,zone-1".into());
        assert!(matches!(
            ManifestRecord::decode(&metadata),
            Err(ProtocolError::InvalidManifest(_))
        ));
    }

    #[tokio::test]
    async fn remove_segments_rejects_entry_not_below_witnessed_floor() {
        let mut record = valid_record();
        record.trunc = 4;
        let buckets = record.buckets.clone();
        let store = Arc::new(InMemoryManifestStore::default());
        store
            .create(record.encode())
            .await
            .expect("seed manifest store");
        let store: Arc<dyn ManifestStore> = store;
        let metrics = Arc::new(Metrics::new(&NoopMetricsRecorder, 3));
        let mut manifest = Manifest::open(
            store,
            ClientConfig {
                max_retries: 0,
                retry_base: Duration::ZERO,
            },
            metrics,
            3,
            buckets,
        )
        .await
        .expect("open seeded manifest");
        let ids = HashSet::from(["sealed-a".to_string()]);

        assert!(matches!(
            manifest.remove_segments(&ids, 4).await,
            Err(ProtocolError::InvalidManifest(_))
        ));
        assert_eq!(manifest.record().segments, record.segments);
    }

    #[tokio::test]
    async fn new_seal_commit_requires_and_persists_crc32c() {
        let store = Arc::new(InMemoryManifestStore::default());
        let store: Arc<dyn ManifestStore> = store;
        let metrics = Arc::new(Metrics::new(&NoopMetricsRecorder, 3));
        let mut manifest = Manifest::open(
            store,
            ClientConfig {
                max_retries: 0,
                retry_base: Duration::ZERO,
            },
            metrics,
            3,
            test_buckets(3),
        )
        .await
        .expect("open manifest");
        manifest.claim().await.expect("claim manifest");
        let sealed_id = manifest
            .record()
            .tail_id
            .clone()
            .expect("claim names a tail");
        let successor = segment_id(manifest.epoch, 1);
        let digest = "d".repeat(64);

        assert!(matches!(
            manifest
                .commit_view(
                    1,
                    Some(successor.clone()),
                    Some(0),
                    Some(sealed_id.clone()),
                    Some(digest.clone()),
                    None,
                )
                .await,
            Err(ProtocolError::InvalidManifest(_))
        ));

        manifest
            .commit_view(
                1,
                Some(successor.clone()),
                Some(0),
                Some(sealed_id.clone()),
                Some(digest.clone()),
                Some(0x1234_abcd),
            )
            .await
            .expect("commit checksummed seal");
        assert_eq!(
            manifest.record().segments,
            vec![DirectoryEntry {
                id: sealed_id.clone(),
                base: 0,
                crc32c: 0x1234_abcd,
            }]
        );
        manifest
            .commit_view(
                1,
                Some(successor.clone()),
                Some(0),
                Some(sealed_id.clone()),
                Some(digest.clone()),
                Some(0x1234_abcd),
            )
            .await
            .expect("identical seal retry");
        assert!(matches!(
            manifest
                .commit_view(
                    1,
                    Some(successor),
                    Some(0),
                    Some(sealed_id),
                    Some(digest),
                    Some(0xfeed_beef),
                )
                .await,
            Err(ProtocolError::InvalidManifest(_))
        ));
    }

    #[test]
    fn incarnation_ids_are_unique_enough() {
        assert_ne!(incarnation_id(), incarnation_id());
        assert_eq!(incarnation_id().len(), 32);
    }
}