object-log 0.4.0

A buffered, multiplexing append log over pluggable object storage, with a sequencing seam (opaque payloads, durable-on-return writes, group-commit).
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
//! Captured read authority, sealed writer fencing, and append-only publication.
#[cfg(test)]
use crate::{AppendOwner, BoundedMetadataStore, MetadataLimits, MetadataOwners};
use crate::{MetadataSnapshot, MetadataSwap, ObjectLogError};
#[cfg(test)]
use bytes::Bytes;
use sha2::{Digest, Sha256};
use std::sync::Arc;
#[cfg(test)]
use std::sync::Mutex;
#[cfg(test)]
use tokio::sync::{Notify, Semaphore, oneshot};

const MAGIC: &[u8; 8] = b"ONH2\0\0\0\x02";
pub(super) const HEAD_BYTES: usize = 240;
use crate::native_v2::codec::{Descriptor, Kind};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SemanticCoverage {
    Uninitialized,
    Covered { through: u64, root: [u8; 32] },
}
async fn semantic_manifest(
    pages: &super::page_store::PageStore,
    head: NativeHead,
    work: &mut super::semantic_map::WorkBudget,
) -> Result<Option<([u8; 32], u64)>, ObjectLogError> {
    match head.semantic_anchor {
        SemanticCoverage::Uninitialized => Ok(None),
        SemanticCoverage::Covered { root, through } => {
            if through != head.next_offset {
                return Err(invalid("semantic coverage differs from exact head cut"));
            }
            let index = head
                .index_root
                .ok_or_else(|| invalid("covered head has no append index"))?;
            super::semantic_map::read_seal(pages, root, through, index, work)
                .await
                .map(Some)
        }
    }
}
// At most 63 skip levels exist below the signed log offset bound. This covers
// both manifests/root envelopes and the complete binary ancestry proof.
const SEMANTIC_LINEAGE_PAGES: u64 = 132;
async fn proves_successor(
    pages: Arc<super::page_store::PageStore>,
    before: NativeHead,
    after: NativeHead,
) -> Result<bool, ObjectLogError> {
    if after.epoch < before.epoch
        || after.log_start != before.log_start
        || after.next_offset < before.next_offset
    {
        return Ok(false);
    }
    // Preserve source-integrity errors for an observed higher fence before
    // rejecting a structurally valid but forbidden zero-append root rewrite.
    if let Some(root) = after.index_root {
        drop(pages.read(root).await?);
    }
    if after.next_offset == before.next_offset
        && (after.index_root != before.index_root
            || after.semantic_anchor != before.semantic_anchor)
    {
        return Ok(false);
    }
    if let Some(before_root) = before.index_root {
        let Some(after_root) = after.index_root else {
            return Ok(false);
        };
        if !super::index::Index::new(pages.clone())
            .proves_extension(before_root, after_root)
            .await?
        {
            return Ok(false);
        }
    }
    let mut work = super::semantic_map::WorkBudget::new(SEMANTIC_LINEAGE_PAGES, 0);
    let before_anchor = semantic_manifest(&pages, before, &mut work).await?;
    let after_anchor = semantic_manifest(&pages, after, &mut work).await?;
    super::semantic_map::proves_head_extension(
        &pages,
        before_anchor,
        after_anchor,
        before.next_offset == 0 && before.index_root.is_none(),
        &mut work,
    )
    .await
}
#[cfg(test)]
fn metadata_owners(owner: AppendOwner) -> MetadataOwners {
    MetadataOwners {
        retained: owner.clone(),
        physical: owner,
    }
}
#[cfg(test)]
fn metadata_limits(payload_bytes: usize) -> MetadataLimits {
    MetadataLimits {
        payload_bytes,
        version_bytes: 4096,
    }
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum PublishOutcome {
    Stored(NativeHead),
    Conflict,
}

/// An exact versioned native head, obtained from bounded durable authority.
/// Roots are opaque commitments; this observation grants neither writer
/// exclusivity nor semantic membership/nonmembership proof.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NativeHead {
    namespace: [u8; 32],
    incarnation: [u8; 32],
    epoch: u64,
    log_start: u64,
    next_offset: u64,
    index_root: Option<Descriptor>,
    semantic_anchor: SemanticCoverage,
}
impl NativeHead {
    pub(super) fn empty(scope: super::codec::Scope) -> Self {
        Self {
            namespace: scope.namespace,
            incarnation: scope.incarnation,
            epoch: 0,
            log_start: 0,
            next_offset: 0,
            index_root: None,
            semantic_anchor: SemanticCoverage::Uninitialized,
        }
    }
    /// Durable writer fence, distinct from any historical record epoch.
    pub fn epoch(&self) -> u64 {
        self.epoch
    }
    /// Retained logical bounds from the same exact head.
    pub fn bounds(&self) -> (u64, u64) {
        (self.log_start, self.next_offset)
    }
    /// Complete immutable index descriptor captured with this head.
    #[cfg(test)]
    pub(crate) fn index_root(&self) -> Option<Descriptor> {
        self.index_root
    }
    #[cfg(test)]
    fn semantic_anchor(&self) -> SemanticCoverage {
        self.semantic_anchor
    }
    pub(super) fn encode(&self) -> [u8; HEAD_BYTES] {
        let mut out = [0; HEAD_BYTES];
        out[..8].copy_from_slice(MAGIC);
        out[8..40].copy_from_slice(&self.namespace);
        out[40..72].copy_from_slice(&self.incarnation);
        out[72..80].copy_from_slice(&self.epoch.to_be_bytes());
        out[80..88].copy_from_slice(&self.log_start.to_be_bytes());
        out[88..96].copy_from_slice(&self.next_offset.to_be_bytes());
        if let Some(root) = self.index_root {
            root.encode_into(&mut out[96..160]);
        }
        if let SemanticCoverage::Covered { through, root } = self.semantic_anchor {
            out[160] = 1;
            out[168..176].copy_from_slice(&through.to_be_bytes());
            out[176..208].copy_from_slice(&root);
        }
        let checksum = Sha256::digest(&out[..208]);
        out[208..].copy_from_slice(&checksum);
        out
    }
    fn decode(
        raw: &[u8],
        namespace: &[u8; 32],
        incarnation: &[u8; 32],
    ) -> Result<Self, ObjectLogError> {
        if raw.len() != HEAD_BYTES
            || &raw[..8] != MAGIC
            || Sha256::digest(&raw[..208]).as_slice() != &raw[208..]
        {
            return Err(invalid("invalid native head format, length or checksum"));
        }
        let head = Self {
            namespace: raw[8..40].try_into().expect("fixed range"),
            incarnation: raw[40..72].try_into().expect("fixed range"),
            epoch: u64::from_be_bytes(raw[72..80].try_into().expect("fixed range")),
            log_start: u64::from_be_bytes(raw[80..88].try_into().expect("fixed range")),
            next_offset: u64::from_be_bytes(raw[88..96].try_into().expect("fixed range")),
            index_root: if raw[96..160] == [0; 64] {
                None
            } else {
                Some(Descriptor::decode(&raw[96..160])?)
            },
            semantic_anchor: match raw[160] {
                0 if raw[161..208] == [0; 47] => SemanticCoverage::Uninitialized,
                1 if raw[161..168] == [0; 7] && raw[176..208] != [0; 32] => {
                    SemanticCoverage::Covered {
                        through: u64::from_be_bytes(raw[168..176].try_into().expect("fixed range")),
                        root: raw[176..208].try_into().expect("fixed range"),
                    }
                }
                _ => return Err(invalid("native semantic coverage framing")),
            },
        };
        if head.namespace != *namespace
            || head.incarnation != *incarnation
            || head.log_start != 0
            || head.next_offset > i64::MAX as u64
            || match head.index_root {
                None => head.next_offset != 0,
                Some(root) => {
                    root.kind == Kind::Overflow || root.start != 0 || root.end != head.next_offset
                }
            }
            || matches!(head.semantic_anchor, SemanticCoverage::Covered { through, .. } if through != head.next_offset || through == 0)
        {
            return Err(invalid("native head scope, bounds or roots mismatch"));
        }
        Ok(head)
    }
}
/// Sealed captured authority retains only the durable observation's bytes and
/// immutable binding identity. It cannot retain executor admission.
#[derive(Clone)]
pub(super) struct CapturedHead {
    head: NativeHead,
    observed: MetadataSnapshot,
    identity: Arc<()>,
}
struct LineageState {
    floor: NativeHead,
    highest_epoch: u64,
}
pub(super) struct AuthorityKnowledge {
    gate: Arc<tokio::sync::Mutex<LineageState>>,
    identity: Arc<()>,
    key_owner: MetadataSnapshot,
    _charge: Arc<super::page_store::Charge>,
}
impl AuthorityKnowledge {
    pub fn new(
        captured: &CapturedHead,
        pages: &super::page_store::PageStore,
    ) -> Result<Arc<Self>, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&captured.identity, &pages.binding_identity()) {
            return Err(invalid("knowledge belongs to another store binding"));
        }
        let charge = pages.charge_output(
            std::mem::size_of::<Self>()
                + std::mem::size_of::<tokio::sync::Mutex<LineageState>>()
                + 4 * std::mem::size_of::<usize>(),
        )?;
        Ok(Arc::new(Self {
            gate: Arc::new(tokio::sync::Mutex::new(LineageState {
                floor: captured.head,
                highest_epoch: captured.head.epoch,
            })),
            identity: pages.binding_identity(),
            key_owner: captured.observed.clone(),
            _charge: charge,
        }))
    }
    pub async fn observe(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<Option<CapturedHead>, ObjectLogError> {
        if !Arc::ptr_eq(&self.identity, &pages.binding_identity())
            || self.key_owner.inner.key != key
        {
            return Err(invalid("knowledge belongs to another authority binding"));
        }
        let mut state = self.gate.lock().await;
        let observed = pages.read_head(key, HEAD_BYTES).await?;
        WriterLineage::validate(&mut state, pages, observed).await
    }
}
struct WriterLineage {
    gate: Arc<tokio::sync::Mutex<LineageState>>,
    acquired_epoch: u64,
    _knowledge: Arc<AuthorityKnowledge>,
    _charge: Arc<super::page_store::Charge>,
}
impl WriterLineage {
    async fn observe(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<Option<CapturedHead>, ObjectLogError> {
        let mut state = self.gate.lock().await;
        let observed = pages.read_head(key, HEAD_BYTES).await?;
        Self::validate(&mut state, pages, observed).await
    }
    async fn validate(
        state: &mut LineageState,
        pages: Arc<super::page_store::PageStore>,
        observed: MetadataSnapshot,
    ) -> Result<Option<CapturedHead>, ObjectLogError> {
        let scope = pages.scope();
        let head = NativeHead::decode(
            observed
                .bytes()
                .ok_or_else(|| invalid("known native head is missing"))?,
            &scope.namespace,
            &scope.incarnation,
        )?;
        // Seeing a higher valid fence revokes this lineage even if its root is
        // missing/corrupt or the attempted range cannot subsequently resolve.
        state.highest_epoch = state.highest_epoch.max(head.epoch);
        let floor = state.floor;
        if head.epoch < state.highest_epoch || !proves_successor(pages.clone(), floor, head).await?
        {
            return Ok(None);
        }
        state.floor = head;
        Ok(Some(CapturedHead {
            head,
            observed,
            identity: pages.binding_identity(),
        }))
    }
}

pub(super) struct AppendInput<'a> {
    pub object_id: &'a str,
    pub payload: &'a [u8],
    pub records: u32,
}
pub(super) struct SemanticEdits<'a, 'work> {
    pub edits: &'a [super::semantic_map::Edit<'a>],
    pub max_edits: u64,
    pub max_input_bytes: u64,
    pub work: &'work mut super::semantic_map::WorkBudget,
}
pub(super) struct AppendGroupLimits {
    pub entries: usize,
    pub framed_bytes: usize,
}
pub(super) struct ProofBudget {
    pub entries: usize,
}
struct OwnedCertificates {
    entries: Vec<super::codec::LeafEntry>,
    _charge: Arc<super::page_store::Charge>,
}

/// Private transition: callers cannot replace its original observation or root.
pub(super) struct PreparedAppend {
    original: CapturedHead,
    next: NativeHead,
    attempted: bool,
    /// What the original conditional write stored, once it definitely did.
    stored: Option<MetadataSnapshot>,
    /// The index position that reaches `next`, for the writer that publishes it.
    spine: Option<super::index::Spine>,
    certificates: OwnedCertificates,
    lineage: Arc<WriterLineage>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Resolution {
    DurableContent,
    Rejected,
    Unknown,
}
impl PreparedAppend {
    pub(super) fn validate_binding(
        &self,
        pages: &super::page_store::PageStore,
        key: &str,
    ) -> Result<(), ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.original.identity, &pages.binding_identity())
            || self.original.observed.inner.key != key
        {
            return Err(invalid("append belongs to another authority binding"));
        }
        Ok(())
    }
    #[cfg(test)]
    pub async fn resolve_range(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<Resolution, ObjectLogError> {
        self.resolve_group(pages, key, ProofBudget { entries: 1 })
            .await
    }
    pub async fn resolve_group(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
        budget: ProofBudget,
    ) -> Result<Resolution, ObjectLogError> {
        if budget.entries == 0 {
            return Err(invalid("zero group proof budget"));
        }
        if !self.attempted || self.original.observed.inner.key != key {
            return Err(invalid(
                "append resolution requires original attempted authority",
            ));
        }
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.original.identity, &pages.binding_identity()) {
            return Err(invalid("append belongs to another store binding"));
        }
        let Some(current) = self.lineage.observe(pages.clone(), key).await? else {
            return Ok(Resolution::Unknown);
        };
        if !proves_successor(pages.clone(), self.original.head, current.head).await? {
            return Ok(Resolution::Unknown);
        }
        if current.head.next_offset < self.next.next_offset {
            return Ok(Resolution::Unknown);
        }
        let mut cursor = self.original.head.next_offset;
        let mut ordinal = 0;
        let mut mismatch = false;
        for _ in 0..budget.entries {
            let Some(owned) = current.lookup(pages.clone(), cursor).await? else {
                return Ok(Resolution::Unknown);
            };
            let actual = *owned.entry();
            drop(owned);
            if actual.base != cursor {
                return Ok(Resolution::Unknown);
            }
            let end = actual.end()?;
            if end <= cursor {
                return Ok(Resolution::Unknown);
            }
            mismatch |= self.certificates.entries.get(ordinal) != Some(&actual);
            ordinal += 1;
            cursor = end;
            if cursor >= self.next.next_offset {
                return Ok(
                    if !mismatch
                        && ordinal == self.certificates.entries.len()
                        && cursor == self.next.next_offset
                    {
                        if !proves_successor(pages.clone(), self.next, current.head).await? {
                            return Ok(Resolution::Unknown);
                        }
                        Resolution::DurableContent
                    } else {
                        Resolution::Rejected
                    },
                );
            }
        }
        Ok(Resolution::Unknown)
    }
    pub async fn publish_outcome(
        &mut self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<PublishOutcome, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.original.identity, &pages.binding_identity()) {
            return Err(invalid("append belongs to another store binding"));
        }
        if self.attempted {
            return Err(invalid("append publication already attempted"));
        }
        if self.original.observed.inner.key != key {
            return Err(invalid("append literal key mismatch"));
        }
        // A publication invocation is terminal even when shared knowledge lets
        // us reject it before issuing its original conditional write.
        self.attempted = true;
        let mut lineage = self.lineage.gate.lock().await;
        if lineage.highest_epoch > self.lineage.acquired_epoch
            || lineage.floor != self.original.head
        {
            return Err(invalid(
                "writer original authority is below its shared floor",
            ));
        }
        match pages
            .swap_head(key, self.original.observed.clone(), &self.next.encode())
            .await?
        {
            MetadataSwap::Stored(stored) => {
                self.stored = Some(stored);
                lineage.floor = self.next;
                Ok(PublishOutcome::Stored(self.next))
            }
            MetadataSwap::Conflict(current) => {
                WriterLineage::validate(&mut lineage, pages, current)
                    .await?
                    .ok_or_else(|| invalid("conflicting authority regressed or changed prefix"))?;
                Ok(PublishOutcome::Conflict)
            }
        }
    }
    #[cfg(test)]
    pub async fn publish(
        &mut self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<NativeHead, ObjectLogError> {
        match self.publish_outcome(pages, key).await? {
            PublishOutcome::Stored(head) => Ok(head),
            PublishOutcome::Conflict => Err(invalid("original append authority changed")),
        }
    }
    /// Exact full-head equality proves this complete original transition.
    /// Later/different authority requires resolve_range instead;
    /// numeric head advancement alone never establishes our publication.
    #[cfg(test)]
    pub async fn resolve_exact(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<Option<NativeHead>, ObjectLogError> {
        if !self.attempted {
            return Err(invalid("append publication has not been attempted"));
        }
        if !Arc::ptr_eq(&self.original.identity, &pages.binding_identity()) {
            return Err(invalid("append belongs to another store binding"));
        }
        if self.original.observed.inner.key != key {
            return Err(invalid("append literal key mismatch"));
        }
        let Some(current) = self.lineage.observe(pages, key).await? else {
            return Ok(None);
        };
        Ok((current.head == self.next).then_some(self.next))
    }
}
pub(super) struct OwnedPayload {
    observed: MetadataSnapshot,
    start: usize,
    len: usize,
}
impl OwnedPayload {
    pub fn bytes(&self) -> &[u8] {
        &self.observed.bytes().expect("validated immutable payload")
            [self.start..self.start + self.len]
    }
}
/// Writer authority is constructed only by a successful fence and exact recapture.
pub(super) struct FencedHead {
    captured: CapturedHead,
    lineage: Arc<WriterLineage>,
    /// The writer's position in the index, once an append has built it. It never
    /// outlives an acquisition or refresh and a clone does not share it.
    spine: Option<super::index::Spine>,
}
impl Clone for FencedHead {
    fn clone(&self) -> Self {
        Self {
            captured: self.captured.clone(),
            lineage: self.lineage.clone(),
            spine: None,
        }
    }
}
impl FencedHead {
    /// The writer for one prepare, moving the spine into it. If that prepare
    /// fails the writer has no spine and the next append rebuilds it by reading.
    pub(super) fn take_for_prepare(&mut self) -> Self {
        Self {
            spine: self.spine.take(),
            ..self.clone()
        }
    }
    pub(super) fn knowledge(&self) -> Arc<AuthorityKnowledge> {
        self.lineage._knowledge.clone()
    }
    pub fn snapshot(&self) -> &CapturedHead {
        &self.captured
    }
    /// Adopt, without I/O, the head that `prepared` definitely stored as this
    /// writer's captured head. Only the direct successor of the current captured
    /// head, from this same writer family, in its acquired epoch, can be adopted.
    pub(super) async fn adopt(
        &mut self,
        prepared: &mut PreparedAppend,
    ) -> Result<NativeHead, ObjectLogError> {
        let stored = prepared
            .stored
            .as_ref()
            .ok_or_else(|| invalid("publication was not stored"))?;
        if !Arc::ptr_eq(&prepared.lineage, &self.lineage) {
            return Err(invalid("publication belongs to another writer"));
        }
        if !self.captured.same_cut(&prepared.original) {
            return Err(invalid(
                "publication does not extend the writer's captured head",
            ));
        }
        if !Arc::ptr_eq(&stored.inner.owner, &self.captured.observed.inner.owner)
            || stored.inner.key != self.captured.observed.inner.key
            || stored.bytes() != Some(prepared.next.encode().as_slice())
        {
            return Err(invalid("stored head differs from the prepared transition"));
        }
        let state = self.lineage.gate.lock().await;
        if state.highest_epoch > self.lineage.acquired_epoch || state.floor != prepared.next {
            return Err(invalid("writer authority changed before adoption"));
        }
        self.captured = CapturedHead {
            head: prepared.next,
            observed: stored.clone(),
            identity: self.captured.identity.clone(),
        };
        self.spine = prepared
            .spine
            .take()
            .filter(|spine| Some(spine.root()) == prepared.next.index_root);
        Ok(prepared.next)
    }
    #[cfg(test)]
    pub async fn prepare_append(
        self,
        pages: Arc<super::page_store::PageStore>,
        object_id: &str,
        raw: &[u8],
        records: u32,
    ) -> Result<PreparedAppend, ObjectLogError> {
        let framed_bytes = super::data::DataFrame::encoded_len(object_id, raw.len())?;
        self.prepare_group(
            pages,
            &[AppendInput {
                object_id,
                payload: raw,
                records,
            }],
            AppendGroupLimits {
                entries: 1,
                framed_bytes,
            },
        )
        .await
    }
    pub async fn prepare_group(
        self,
        pages: Arc<super::page_store::PageStore>,
        inputs: &[AppendInput<'_>],
        limits: AppendGroupLimits,
    ) -> Result<PreparedAppend, ObjectLogError> {
        self.prepare_group_inner(pages, inputs, limits, None).await
    }
    pub async fn prepare_semantic_group(
        self,
        pages: Arc<super::page_store::PageStore>,
        inputs: &[AppendInput<'_>],
        limits: AppendGroupLimits,
        semantic: SemanticEdits<'_, '_>,
    ) -> Result<PreparedAppend, ObjectLogError> {
        self.prepare_group_inner(pages, inputs, limits, Some(semantic))
            .await
    }
    async fn prepare_group_inner(
        self,
        pages: Arc<super::page_store::PageStore>,
        inputs: &[AppendInput<'_>],
        limits: AppendGroupLimits,
        mut semantic: Option<SemanticEdits<'_, '_>>,
    ) -> Result<PreparedAppend, ObjectLogError> {
        if inputs.is_empty()
            || limits.entries == 0
            || limits.framed_bytes == 0
            || inputs.len() > limits.entries
        {
            return Err(invalid("append group limits"));
        }
        let captured = self.captured;
        let lineage = self.lineage;
        pages.require_operation()?;
        {
            let state = lineage.gate.lock().await;
            if state.highest_epoch > lineage.acquired_epoch || state.floor != captured.head {
                return Err(invalid(
                    "writer original authority is below its shared floor",
                ));
            }
        }
        if !Arc::ptr_eq(&captured.identity, &pages.binding_identity()) {
            return Err(invalid("captured head belongs to another store binding"));
        }
        if semantic.is_none() && captured.head.semantic_anchor != SemanticCoverage::Uninitialized {
            return Err(invalid(
                "append requires consumer semantic publication for covered heads",
            ));
        }
        if semantic.is_some()
            && captured.head.semantic_anchor == SemanticCoverage::Uninitialized
            && (captured.head.next_offset != 0 || captured.head.index_root.is_some())
        {
            return Err(invalid(
                "semantic bootstrap requires a genuinely empty original head",
            ));
        }
        let coupled = semantic.is_some();
        let frame_len = |input: &AppendInput<'_>| {
            if coupled {
                super::data::DataFrame::coupled_encoded_len(input.object_id, input.payload.len())
            } else {
                super::data::DataFrame::encoded_len(input.object_id, input.payload.len())
            }
        };
        let mut next_offset = captured.head.next_offset;
        let mut framed_bytes = 0usize;
        // Validate the entire group before the first immutable write.
        for (ordinal, input) in inputs.iter().enumerate() {
            if input.records == 0 || input.records > i32::MAX as u32 {
                return Err(invalid("append record count"));
            }
            next_offset = next_offset
                .checked_add(u64::from(input.records))
                .filter(|next| *next <= i64::MAX as u64)
                .ok_or_else(|| invalid("append offset overflow"))?;
            let frame_len = frame_len(input)?;
            pages.validate_data_limit(frame_len)?;
            framed_bytes = framed_bytes
                .checked_add(frame_len)
                .filter(|bytes| *bytes <= limits.framed_bytes)
                .ok_or_else(|| invalid("append group framed byte limit"))?;
            if inputs[..ordinal]
                .iter()
                .any(|prior| prior.object_id == input.object_id)
            {
                return Err(invalid("duplicate logical identity in append group"));
            }
        }
        let retained_bytes = inputs
            .len()
            .checked_mul(std::mem::size_of::<super::codec::LeafEntry>())
            .and_then(|bytes| bytes.checked_add(std::mem::size_of::<OwnedCertificates>()))
            .ok_or_else(|| invalid("append certificate capacity"))?;
        let charge = pages.charge_output(retained_bytes)?;
        let mut certificates = OwnedCertificates {
            entries: Vec::with_capacity(inputs.len()),
            _charge: charge,
        };
        // Resource probes include the permanently retained group certificates.
        // They are capacity checks, not reservations against concurrent work.
        for input in inputs {
            let key = if coupled {
                pages.transition_data_key(&[1; 32])?
            } else {
                pages.data_key(input.object_id)?
            };
            let frame_len = frame_len(input)?;
            let frame_charge = super::data::DataFrame::charge_frame(&pages, frame_len)?;
            pages.preflight_data(key.as_str(), frame_len)?;
            drop(frame_charge);
        }
        let prepared_map = if let Some(semantic) = semantic.as_mut() {
            let original_anchor = semantic_manifest(&pages, captured.head, semantic.work).await?;
            let map = match original_anchor {
                None => super::semantic_map::CapturedMap::empty(&pages)?,
                Some((root, through)) => {
                    super::semantic_map::CapturedMap::capture(&pages, root, through, semantic.work)
                        .await?
                }
            };
            let map = map
                .prepare(
                    &pages,
                    semantic.edits,
                    super::semantic_map::EditBounds {
                        edits: semantic.max_edits,
                        input_bytes: semantic.max_input_bytes,
                    },
                    next_offset,
                    inputs.len() as u64,
                    semantic.work,
                )
                .await?;
            map.validate_binding(&pages)?;
            if map.before_hash() != original_anchor.map_or([0; 32], |(hash, _)| hash)
                || map.through() != next_offset
            {
                return Err(invalid(
                    "prepared semantic map differs from exact original head",
                ));
            }
            Some(map)
        } else {
            None
        };
        let index = super::index::Index::new(pages.clone());
        let mut spine = self.spine;
        let mut uploads = super::page_store::UploadBatch::new();
        let mut root = captured.head.index_root;
        let mut base = captured.head.next_offset;
        for (ordinal, input) in inputs.iter().enumerate() {
            let frame = if let Some(map) = &prepared_map {
                super::data::DataFrame::encode_coupled(
                    &pages,
                    input.object_id,
                    input.payload,
                    super::data::Transition {
                        scope: pages.scope(),
                        before: map.before_hash(),
                        after: map.after_hash(),
                        generation: map.generation(),
                        group_start: captured.head.next_offset,
                        group_end: next_offset,
                        entry_count: inputs.len() as u64,
                        ordinal: ordinal as u64,
                        base,
                        records: input.records,
                    },
                )?
            } else {
                super::data::DataFrame::encode(&pages, input.object_id, input.payload)?
            };
            let view = super::data::DataFrame::decode(frame.bytes())?;
            let physical_key = if coupled {
                pages.transition_data_key(&view.certificate())?
            } else {
                pages.data_key(input.object_id)?
            };
            let logical_id = index
                .stage_literal_id(input.object_id, &mut uploads)
                .await?;
            let identity = index
                .stage_object_id(physical_key.as_str(), &mut uploads)
                .await?;
            let certificate = super::codec::LeafEntry {
                object_id: identity,
                logical_id,
                base,
                record_count: input.records,
                byte_start: view.byte_start(),
                byte_len: u32::try_from(input.payload.len())
                    .map_err(|_| invalid("append physical byte length"))?,
                payload_hash: view.certificate(),
                frame_kind: if coupled {
                    super::codec::FrameKind::Coupled
                } else {
                    super::codec::FrameKind::Legacy
                },
            };
            uploads
                .push(
                    &pages,
                    super::page_store::Upload::Data {
                        key: physical_key,
                        frame,
                    },
                )
                .await?;
            let appended = index.append_spine(root, spine.take(), certificate).await?;
            for page in appended.uploads {
                uploads
                    .push(&pages, super::page_store::Upload::Page(page))
                    .await?;
            }
            root = Some(appended.root);
            spine = Some(appended.spine);
            base = certificate.end()?;
            certificates.entries.push(certificate);
        }
        // Every object this group references is durable before the head can name it.
        uploads.finish(&pages).await?;
        let semantic_anchor = if let Some(map) = &prepared_map {
            let index_root =
                root.ok_or_else(|| invalid("coupled publication has no append index"))?;
            let work = &mut *semantic
                .as_mut()
                .expect("prepared map requires semantic input")
                .work;
            let seal = map.seal(&pages, index_root, work).await?;
            SemanticCoverage::Covered {
                through: map.through(),
                root: seal,
            }
        } else {
            captured.head.semantic_anchor
        };
        let next = NativeHead {
            next_offset,
            index_root: root,
            semantic_anchor,
            ..captured.head
        };
        Ok(PreparedAppend {
            original: captured,
            next,
            attempted: false,
            stored: None,
            spine,
            certificates,
            lineage,
        })
    }
    pub async fn refresh(
        &self,
        pages: Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<Self, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.captured.identity, &pages.binding_identity())
            || self.captured.observed.inner.key != key
        {
            return Err(invalid("writer belongs to another authority binding"));
        }
        let Some(current) = self.lineage.observe(pages, key).await? else {
            return Err(invalid("writer authority regressed during refresh"));
        };
        let state = self.lineage.gate.lock().await;
        if state.highest_epoch > self.lineage.acquired_epoch
            || current.head.epoch != self.lineage.acquired_epoch
            || current.head != state.floor
        {
            return Err(invalid("writer authority changed during refresh"));
        }
        Ok(Self {
            captured: current,
            lineage: self.lineage.clone(),
            spine: None,
        })
    }
}
impl CapturedHead {
    pub(super) fn same_cut(&self, other: &Self) -> bool {
        self.head == other.head
            && Arc::ptr_eq(&self.identity, &other.identity)
            && Arc::ptr_eq(&self.observed.inner.owner, &other.observed.inner.owner)
            && self.observed.inner.key == other.observed.inner.key
            && self.observed.inner.version == other.observed.inner.version
    }

    pub async fn semantic_map(
        &self,
        pages: &super::page_store::PageStore,
        work: &mut super::semantic_map::WorkBudget,
    ) -> Result<super::semantic_map::CapturedMap, ObjectLogError> {
        if !Arc::ptr_eq(&self.identity, &pages.binding_identity()) {
            return Err(invalid("captured head belongs to another store binding"));
        }
        let Some((root, through)) = semantic_manifest(pages, self.head, work).await? else {
            return Err(invalid("captured head has no semantic coverage"));
        };
        super::semantic_map::CapturedMap::capture(pages, root, through, work).await
    }
    pub(super) fn value(&self) -> NativeHead {
        self.head
    }
    pub(super) fn head_bytes(&self) -> [u8; HEAD_BYTES] {
        self.head.encode()
    }

    pub async fn read_record_bounded(
        &self,
        pages: Arc<super::page_store::PageStore>,
        offset: u64,
        max_payload_bytes: usize,
    ) -> Result<Option<(u64, u32, OwnedPayload)>, ObjectLogError> {
        let Some(owned) = self.lookup(pages.clone(), offset).await? else {
            return Ok(None);
        };
        Self::hydrate_record(pages, &owned, max_payload_bytes)
            .await
            .map(Some)
    }
    pub(super) async fn hydrate_record(
        pages: Arc<super::page_store::PageStore>,
        owned: &super::index::OwnedEntry,
        max_payload_bytes: usize,
    ) -> Result<(u64, u32, OwnedPayload), ObjectLogError> {
        let entry = owned.entry();
        if entry.byte_len as usize > max_payload_bytes {
            return Err(ObjectLogError::ReadLimitExceeded {
                actual: entry.byte_len as usize,
                limit: max_payload_bytes,
            });
        }
        let index = super::index::Index::new(pages.clone());
        let logical = index.literal_id(entry.logical_id).await?;
        let physical = index.object_id(entry.object_id).await?;
        let expected = match entry.frame_kind {
            super::codec::FrameKind::Legacy => pages.data_key(logical.as_str())?,
            super::codec::FrameKind::Coupled => pages.transition_data_key(&entry.payload_hash)?,
        };
        if expected.as_str() != physical.as_str() {
            return Err(invalid(
                "indexed physical key differs from full logical identity mapping",
            ));
        }
        let length = u64::from(entry.byte_start)
            .checked_add(u64::from(entry.byte_len))
            .and_then(|n| usize::try_from(n).ok())
            .ok_or_else(|| invalid("indexed data length"))?;
        let observed = pages.read_data(physical.as_str(), length).await?;
        let raw = observed
            .bytes()
            .ok_or_else(|| invalid("indexed immutable data is missing"))?;
        let frame = super::data::DataFrame::decode(raw)?;
        if frame.identity() != logical.as_str()
            || frame.byte_start() != entry.byte_start
            || frame.payload().len() != entry.byte_len as usize
            || frame.certificate() != entry.payload_hash
            || (entry.frame_kind == super::codec::FrameKind::Coupled)
                != frame.transition().is_some()
        {
            return Err(invalid(
                "indexed data identity, range or payload digest differs",
            ));
        }
        if let Some(transition) = frame.transition() {
            if transition.base != entry.base || transition.records != entry.record_count {
                return Err(invalid("indexed transition assigned record range differs"));
            }
            super::semantic_map::validate_transition(
                &pages,
                transition,
                &mut super::semantic_map::WorkBudget::new(1, 0),
            )
            .await?;
        }
        Ok((
            entry.base,
            entry.record_count,
            OwnedPayload {
                observed,
                start: entry.byte_start as usize,
                len: entry.byte_len as usize,
            },
        ))
    }
    #[cfg(test)]
    pub async fn read_payload(
        &self,
        pages: Arc<super::page_store::PageStore>,
        offset: u64,
    ) -> Result<Option<OwnedPayload>, ObjectLogError> {
        Ok(self
            .read_record_bounded(pages, offset, usize::MAX)
            .await?
            .map(|(_, _, payload)| payload))
    }
    pub async fn capture(
        pages: &super::page_store::PageStore,
        key: &str,
    ) -> Result<Self, ObjectLogError> {
        let observed = pages.read_head(key, HEAD_BYTES).await?;
        let scope = pages.scope();
        let head = NativeHead::decode(
            observed
                .bytes()
                .ok_or_else(|| invalid("known native head is missing"))?,
            &scope.namespace,
            &scope.incarnation,
        )?;
        if let Some(root) = head.index_root {
            // Envelope decoding alone does not authorize an index root.
            drop(pages.read(root).await?);
        }
        let mut work = super::semantic_map::WorkBudget::new(SEMANTIC_LINEAGE_PAGES, 0);
        let anchor = semantic_manifest(pages, head, &mut work).await?;
        if !super::semantic_map::proves_head_extension(pages, anchor, anchor, false, &mut work)
            .await?
        {
            return Err(invalid("captured semantic anchor is invalid"));
        }
        Ok(Self {
            head,
            observed,
            identity: pages.binding_identity(),
        })
    }
    /// Fence exactly the captured observation. A conflict does not substitute
    /// a fresh root or silently retry this original transition. The returned
    /// head is a fence result, not a publication token: this cut still owns
    /// the pre-acquisition observation. Publication must recapture authority
    /// and validate its epoch/root before constructing a transition.
    fn fence_transition(
        &self,
        pages: &super::page_store::PageStore,
        key: &str,
    ) -> Result<NativeHead, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.identity, &pages.binding_identity()) {
            return Err(invalid("captured head belongs to another store binding"));
        }
        let fenced = NativeHead {
            epoch: self
                .head
                .epoch
                .checked_add(1)
                .ok_or_else(|| invalid("native epoch exhausted"))?,
            ..self.head
        };
        if self.observed.inner.key != key {
            return Err(invalid("fence literal head key mismatch"));
        }
        Ok(fenced)
    }
    #[cfg(test)]
    pub async fn acquire(
        &self,
        pages: &super::page_store::PageStore,
        key: &str,
    ) -> Result<NativeHead, ObjectLogError> {
        let fenced = self.fence_transition(pages, key)?;
        match pages
            .swap_head(key, self.observed.clone(), &fenced.encode())
            .await?
        {
            MetadataSwap::Stored(_) => Ok(fenced),
            MetadataSwap::Conflict(_) => Err(invalid("captured head changed before acquisition")),
        }
    }
    /// Obtain the post-fence token without relabeling the old observation.
    /// Any intervening change invalidates this writer attempt.
    #[cfg(test)]
    pub async fn acquire_and_recapture(
        &self,
        pages: &Arc<super::page_store::PageStore>,
        key: &str,
    ) -> Result<FencedHead, ObjectLogError> {
        let knowledge = AuthorityKnowledge::new(self, pages)?;
        self.acquire_with_knowledge(pages, key, knowledge).await
    }
    pub(super) async fn acquire_with_knowledge(
        &self,
        pages: &Arc<super::page_store::PageStore>,
        key: &str,
        knowledge: Arc<AuthorityKnowledge>,
    ) -> Result<FencedHead, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&knowledge.identity, &self.identity)
            || knowledge.key_owner.inner.key != key
            || self.observed.inner.key != key
        {
            return Err(invalid("fence belongs to another authority family"));
        }
        let charge = pages.charge_output(
            std::mem::size_of::<WriterLineage>() + 2 * std::mem::size_of::<usize>(),
        )?;
        let mut state = knowledge.gate.lock().await;
        if state.floor != self.head || state.highest_epoch > self.head.epoch {
            return Err(invalid(
                "fence original authority is below shared knowledge",
            ));
        }
        let fenced = self.fence_transition(pages, key)?;
        match pages
            .swap_head(key, self.observed.clone(), &fenced.encode())
            .await?
        {
            MetadataSwap::Stored(_) => {}
            MetadataSwap::Conflict(observed) => {
                WriterLineage::validate(&mut state, pages.clone(), observed).await?;
                return Err(invalid("captured head changed before acquisition"));
            }
        }
        // Stored establishes knowledge, but does not relabel the original token.
        state.floor = fenced;
        state.highest_epoch = state.highest_epoch.max(fenced.epoch);
        let observed = pages.read_head(key, HEAD_BYTES).await?;
        let current = WriterLineage::validate(&mut state, pages.clone(), observed)
            .await?
            .ok_or_else(|| invalid("native authority regressed after acquisition"))?;
        if current.head != fenced {
            return Err(invalid("native authority changed after acquisition"));
        }
        drop(state);
        let lineage = Arc::new(WriterLineage {
            gate: knowledge.gate.clone(),
            acquired_epoch: current.head.epoch,
            _knowledge: knowledge,
            _charge: charge,
        });
        Ok(FencedHead {
            captured: current,
            lineage,
            spine: None,
        })
    }
    pub async fn lookup_run(
        &self,
        pages: Arc<super::page_store::PageStore>,
        offset: u64,
        max_entries: usize,
    ) -> Result<Vec<super::index::OwnedEntry>, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.identity, &pages.binding_identity()) {
            return Err(invalid("captured head belongs to another store binding"));
        }
        super::index::Index::new(pages)
            .lookup_run(self.head.index_root, offset, max_entries)
            .await
    }
    pub async fn lookup(
        &self,
        pages: Arc<super::page_store::PageStore>,
        offset: u64,
    ) -> Result<Option<super::index::OwnedEntry>, ObjectLogError> {
        pages.require_operation()?;
        if !Arc::ptr_eq(&self.identity, &pages.binding_identity()) {
            return Err(invalid("captured head belongs to another store binding"));
        }
        // Retain the original exact metadata token for later conditional
        // publication; no fresh head read can silently replace this cut.
        debug_assert!(self.observed.bytes().is_some());
        super::index::Index::new(pages)
            .lookup(self.head.index_root, offset)
            .await
    }
}

fn invalid(message: &str) -> ObjectLogError {
    ObjectLogError::Sequencer(message.into())
}
#[cfg(test)]
struct Lifecycle {
    closed: bool,
    owned: usize,
}
#[cfg(test)]
struct Owner {
    store: Arc<dyn BoundedMetadataStore>,
    key: String,
    namespace: [u8; 32],
    incarnation: [u8; 32],
    gate: Arc<Semaphore>,
    lifecycle: Mutex<Lifecycle>,
    drained: Notify,
}
#[cfg(test)]
struct PhysicalOwner {
    owner: Arc<Owner>,
    permit: Option<tokio::sync::OwnedSemaphorePermit>,
}
#[cfg(test)]
impl Drop for PhysicalOwner {
    fn drop(&mut self) {
        drop(self.permit.take());
        let mut state = self
            .owner
            .lifecycle
            .lock()
            .expect("head lifecycle poisoned");
        state.owned -= 1;
        if state.owned == 0 {
            self.owner.drained.notify_waiters();
        }
    }
}
/// Storage-internal reader/fencer for an already provisioned native head.
/// It cannot create a missing head, migrate legacy manifests, publish roots or
/// authorize Fireweed to bypass cold recovery. Operations are physically owned
/// after dispatch, serialized, and drained even when the caller drops its reply.
#[derive(Clone)]
#[cfg(test)]
pub struct NativeHeadReader {
    owner: Arc<Owner>,
}
#[cfg(test)]
impl NativeHeadReader {
    /// Bind an existing head's literal storage key and immutable scope. This
    /// performs no I/O. Missing authority always fails closed, including known
    /// catalog membership; provisioning is a separate future publication path.
    pub fn new_known(
        store: Arc<dyn BoundedMetadataStore>,
        key: String,
        namespace: [u8; 32],
        incarnation: [u8; 32],
    ) -> Result<Self, ObjectLogError> {
        if key.is_empty()
            || key.contains('\0')
            || key.split('/').any(|part| part == "..")
            || namespace == [0; 32]
            || incarnation == [0; 32]
        {
            return Err(ObjectLogError::InvalidConfig(
                "invalid native head binding".into(),
            ));
        }
        Ok(Self {
            owner: Arc::new(Owner {
                store,
                key,
                namespace,
                incarnation,
                gate: Arc::new(Semaphore::new(1)),
                lifecycle: Mutex::new(Lifecycle {
                    closed: false,
                    owned: 0,
                }),
                drained: Notify::new(),
            }),
        })
    }
    /// Read the exact durable head. Fresh missing/corrupt authority is unknown.
    pub async fn read(&self) -> Result<NativeHead, ObjectLogError> {
        self.dispatch(false).await
    }
    /// Increment only the durable epoch, preserving bounds and both roots.
    /// Competing CAS retries reread and validate the original namespace and
    /// incarnation. An ambiguous write is returned as an error without retry.
    pub async fn acquire(&self) -> Result<NativeHead, ObjectLogError> {
        self.dispatch(true).await
    }
    async fn dispatch(&self, acquire: bool) -> Result<NativeHead, ObjectLogError> {
        let permit = Arc::clone(&self.owner.gate)
            .acquire_owned()
            .await
            .map_err(|_| invalid("native head is closed"))?;
        {
            let mut state = self
                .owner
                .lifecycle
                .lock()
                .expect("head lifecycle poisoned");
            if state.closed {
                return Err(invalid("native head is closed"));
            }
            state.owned += 1;
        }
        let physical = Arc::new(PhysicalOwner {
            owner: Arc::clone(&self.owner),
            permit: Some(permit),
        });
        let (send, receive) = oneshot::channel();
        tokio::spawn(async move {
            let result = physical
                .owner
                .execute(acquire, Arc::clone(&physical) as AppendOwner)
                .await;
            let _ = send.send(result);
            drop(physical);
        });
        receive
            .await
            .map_err(|_| invalid("native head physical operation panicked"))?
    }
    /// Close admission and await adapter-owned operations and source buffers.
    /// SDK transport internals and ambiguous remote effects are not certified.
    /// Already
    /// queued pre-dispatch callers fail without I/O; all clones share closure.
    pub async fn close_and_drain(&self) {
        self.owner
            .lifecycle
            .lock()
            .expect("head lifecycle poisoned")
            .closed = true;
        self.owner.gate.close();
        loop {
            let notified = self.owner.drained.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            if self
                .owner
                .lifecycle
                .lock()
                .expect("head lifecycle poisoned")
                .owned
                == 0
            {
                return;
            }
            notified.await;
        }
    }
}
#[cfg(test)]
impl Owner {
    fn decode(&self, observed: &MetadataSnapshot) -> Result<NativeHead, ObjectLogError> {
        let bytes = observed
            .bytes()
            .ok_or_else(|| invalid("known native head is missing"))?;
        NativeHead::decode(bytes, &self.namespace, &self.incarnation)
    }
    async fn execute(
        &self,
        acquire: bool,
        physical: AppendOwner,
    ) -> Result<NativeHead, ObjectLogError> {
        let mut previous: Option<NativeHead> = None;
        let mut observed = self
            .store
            .read_metadata(
                &self.key,
                metadata_limits(HEAD_BYTES),
                metadata_owners(Arc::clone(&physical)),
            )
            .await?;
        for _ in 0..8 {
            let mut head = self.decode(&observed)?;
            if previous.is_some_and(|old| {
                head.epoch < old.epoch
                    || head.log_start < old.log_start
                    || head.next_offset < old.next_offset
                    || (head.bounds() == old.bounds()
                        && (head.index_root != old.index_root
                            || head.semantic_anchor != old.semantic_anchor))
            }) {
                return Err(invalid(
                    "native head conflict authority regressed or changed roots",
                ));
            }
            previous = Some(head);
            if !acquire {
                return Ok(head);
            }
            head.epoch = head
                .epoch
                .checked_add(1)
                .ok_or_else(|| invalid("native epoch exhausted"))?;
            match self
                .store
                .swap_metadata(
                    &self.key,
                    observed,
                    Bytes::copy_from_slice(&head.encode()),
                    metadata_limits(HEAD_BYTES),
                    metadata_owners(Arc::clone(&physical)),
                )
                .await?
            {
                MetadataSwap::Stored(_) => return Ok(head),
                MetadataSwap::Conflict(current) => observed = current,
            }
        }
        Err(invalid("native head conditional acquisition exhausted"))
    }
}

#[cfg(test)]
mod tests;