polyc-query-model 2026.9.6

DataFusion-free semantic request and result vocabulary shared by Query clients and the Query service.
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
//! The query protocol's own closed source-evidence vocabulary.
//!
//! A terminal frame reports the exact premises a query read. Those premises
//! originate in the state plane's audit types, but a client must not acquire
//! the state plane's component graph to read them. This module owns a
//! wire-neutral mirror instead: plain data, no transport, no engine, and no
//! dependency outside this crate.
//!
//! The inward composition layer converts between these types and the state
//! plane's own. That layer is the only place both vocabularies meet.
//!
//! # Canonical order
//!
//! [`SourceEvidence`] holds strictly ascending, duplicate-free pins under the
//! same identity rule the durable audit applies: a variant tag, then each
//! source's identity as length-prefixed bytes. Reproducing the rule here lets
//! the transport refuse a reordered or duplicated vector on its own, without
//! reaching for the state plane to do it.

use std::fmt;
use std::time::Duration;

use crate::ModelError;

/// Largest number of exact source premises one result may report.
pub const MAX_SOURCE_PINS: usize = 32;
/// Width of a partition incarnation.
pub const INCARNATION_BYTES: usize = 32;
/// Width of a content digest.
pub const DIGEST_BYTES: usize = 32;
/// Width of a journal commit root.
pub const COMMIT_ROOT_BYTES: usize = 32;
/// Width of a journal attestation signature.
pub const ATTESTATION_SIGNATURE_BYTES: usize = 64;
/// Width of a journal attestation signer key.
pub const ATTESTATION_SIGNER_BYTES: usize = 32;

fn push_len_prefixed(buffer: &mut Vec<u8>, bytes: &[u8]) {
    buffer.extend_from_slice(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_be_bytes());
    buffer.extend_from_slice(bytes);
}

const fn non_empty(field: &'static str, value: &str) -> Result<(), ModelError> {
    if value.is_empty() {
        return Err(ModelError::Bounds(field));
    }
    Ok(())
}

/// One physical journal lineage.
#[derive(Clone, PartialEq, Eq)]
pub struct JournalSource {
    partition: String,
    incarnation: [u8; INCARNATION_BYTES],
}

impl JournalSource {
    /// Names one partition incarnation.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for an empty partition.
    pub fn try_new(
        partition: String,
        incarnation: [u8; INCARNATION_BYTES],
    ) -> Result<Self, ModelError> {
        non_empty("partition", &partition)?;
        Ok(Self {
            partition,
            incarnation,
        })
    }

    /// Returns the partition this lineage belongs to.
    #[must_use]
    pub fn partition(&self) -> &str {
        &self.partition
    }

    /// Returns the exact incarnation bytes.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.incarnation
    }
}

/// A signed journal root covering one checkpoint.
#[derive(Clone, PartialEq, Eq)]
pub struct JournalAttestation {
    root: [u8; COMMIT_ROOT_BYTES],
    leaf_count: u64,
    signature: [u8; ATTESTATION_SIGNATURE_BYTES],
    signer: [u8; ATTESTATION_SIGNER_BYTES],
}

impl JournalAttestation {
    /// Records one covering attestation.
    #[must_use]
    pub const fn new(
        root: [u8; COMMIT_ROOT_BYTES],
        leaf_count: u64,
        signature: [u8; ATTESTATION_SIGNATURE_BYTES],
        signer: [u8; ATTESTATION_SIGNER_BYTES],
    ) -> Self {
        Self {
            root,
            leaf_count,
            signature,
            signer,
        }
    }

    /// Returns the attested commit root.
    #[must_use]
    pub const fn root(&self) -> &[u8; COMMIT_ROOT_BYTES] {
        &self.root
    }

    /// Returns how many leaves the root covers.
    #[must_use]
    pub const fn leaf_count(&self) -> u64 {
        self.leaf_count
    }

    /// Returns the signature over the root.
    #[must_use]
    pub const fn signature(&self) -> &[u8; ATTESTATION_SIGNATURE_BYTES] {
        &self.signature
    }

    /// Returns the signer key that produced the signature.
    #[must_use]
    pub const fn signer(&self) -> &[u8; ATTESTATION_SIGNER_BYTES] {
        &self.signer
    }
}

/// The exact source frontier one projection generation covers.
#[derive(Clone, PartialEq, Eq)]
pub struct SourceCheckpoint {
    source: JournalSource,
    feed_position: u64,
    journal_position: u64,
    evidence_leaf: u64,
    covering_attestation: JournalAttestation,
}

impl SourceCheckpoint {
    /// Records one exact source frontier.
    #[must_use]
    pub const fn new(
        source: JournalSource,
        feed_position: u64,
        journal_position: u64,
        evidence_leaf: u64,
        covering_attestation: JournalAttestation,
    ) -> Self {
        Self {
            source,
            feed_position,
            journal_position,
            evidence_leaf,
            covering_attestation,
        }
    }

    /// Returns the lineage this checkpoint covers.
    #[must_use]
    pub const fn source(&self) -> &JournalSource {
        &self.source
    }

    /// Returns the feed position.
    #[must_use]
    pub const fn feed_position(&self) -> u64 {
        self.feed_position
    }

    /// Returns the journal position.
    #[must_use]
    pub const fn journal_position(&self) -> u64 {
        self.journal_position
    }

    /// Returns the evidence leaf index.
    #[must_use]
    pub const fn evidence_leaf(&self) -> u64 {
        self.evidence_leaf
    }

    /// Returns the attestation covering this checkpoint.
    #[must_use]
    pub const fn covering_attestation(&self) -> &JournalAttestation {
        &self.covering_attestation
    }
}

/// One Versioned State aggregate, bound to the log lineage it lives in.
///
/// The aggregate scope names WHICH aggregate; the incarnation names WHICH log.
/// A change-feed position only means something inside one lineage, because a
/// wiped log numbers positions from 1 again.
#[derive(Clone, PartialEq, Eq)]
pub struct VersionedSource {
    aggregate: String,
    partition: String,
    namespace: String,
    incarnation: [u8; INCARNATION_BYTES],
}

impl VersionedSource {
    /// Names one aggregate in one log lineage.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for an empty scope component.
    pub fn try_new(
        aggregate: String,
        partition: String,
        namespace: String,
        incarnation: [u8; INCARNATION_BYTES],
    ) -> Result<Self, ModelError> {
        non_empty("aggregate", &aggregate)?;
        non_empty("partition", &partition)?;
        non_empty("namespace", &namespace)?;
        Ok(Self {
            aggregate,
            partition,
            namespace,
            incarnation,
        })
    }

    /// Returns the aggregate name.
    #[must_use]
    pub fn aggregate(&self) -> &str {
        &self.aggregate
    }

    /// Returns the partition the aggregate lives in.
    #[must_use]
    pub fn partition(&self) -> &str {
        &self.partition
    }

    /// Returns the namespace the aggregate lives in.
    #[must_use]
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Returns the opaque physical lineage of the log.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.incarnation
    }
}

/// One exact point in the query-audit authority's ordered history.
#[derive(Clone, PartialEq, Eq)]
pub struct AuditCheckpoint {
    partition: String,
    incarnation: [u8; INCARNATION_BYTES],
    ordinal: u64,
    entry_digest: [u8; DIGEST_BYTES],
}

impl AuditCheckpoint {
    /// Records the entry at `ordinal`, whose canonical bytes digest to
    /// `entry_digest`.
    #[must_use]
    pub const fn new(
        partition: String,
        incarnation: [u8; INCARNATION_BYTES],
        ordinal: u64,
        entry_digest: [u8; DIGEST_BYTES],
    ) -> Self {
        Self {
            partition,
            incarnation,
            ordinal,
            entry_digest,
        }
    }

    /// Returns the authority's fixed partition.
    #[must_use]
    pub fn partition(&self) -> &str {
        &self.partition
    }

    /// Returns the opaque physical lineage.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.incarnation
    }

    /// Returns the ordinal in the authority's history.
    #[must_use]
    pub const fn ordinal(&self) -> u64 {
        self.ordinal
    }

    /// Returns the digest of the entry at that ordinal.
    #[must_use]
    pub const fn entry_digest(&self) -> &[u8; DIGEST_BYTES] {
        &self.entry_digest
    }
}

/// One exact point in a Versioned aggregate's ordered change feed.
#[derive(Clone, PartialEq, Eq)]
pub struct VersionedCheckpoint {
    source: VersionedSource,
    position: u64,
    entry_digest: [u8; DIGEST_BYTES],
}

impl VersionedCheckpoint {
    /// Records the change at `position`, whose canonical bytes digest to
    /// `entry_digest`.
    #[must_use]
    pub const fn new(
        source: VersionedSource,
        position: u64,
        entry_digest: [u8; DIGEST_BYTES],
    ) -> Self {
        Self {
            source,
            position,
            entry_digest,
        }
    }

    /// Returns the aggregate and lineage this point belongs to.
    #[must_use]
    pub const fn source(&self) -> &VersionedSource {
        &self.source
    }

    /// Returns the change-feed position.
    #[must_use]
    pub const fn position(&self) -> u64 {
        self.position
    }

    /// Returns the digest of the change record at that position.
    #[must_use]
    pub const fn entry_digest(&self) -> &[u8; DIGEST_BYTES] {
        &self.entry_digest
    }
}

/// One exact point in a persona-memory partition's ordered history.
#[derive(Clone, PartialEq, Eq)]
pub struct PersonaMemoryCheckpoint {
    partition: String,
    incarnation: [u8; INCARNATION_BYTES],
    position: u64,
    record_digest: [u8; DIGEST_BYTES],
}

/// One exact recorded observation of one Kubernetes collection.
#[derive(Clone, PartialEq, Eq)]
pub struct ObservedCheckpoint {
    partition: String,
    collection_kind: String,
    collection_namespace: String,
    incarnation: [u8; INCARNATION_BYTES],
    ordinal: u64,
    payload_digest: [u8; DIGEST_BYTES],
}

impl ObservedCheckpoint {
    /// Records one observation checkpoint.
    ///
    /// # Errors
    ///
    /// Refuses an unsupported collection kind, an empty namespace, or a zero
    /// observation ordinal.
    pub fn try_new(
        collection_kind: String,
        collection_namespace: String,
        incarnation: [u8; INCARNATION_BYTES],
        ordinal: u64,
        payload_digest: [u8; DIGEST_BYTES],
    ) -> Result<Self, ModelError> {
        if collection_kind != "routines" {
            return Err(ModelError::Bounds("collection_kind"));
        }
        non_empty("collection_namespace", &collection_namespace)?;
        if ordinal == 0 {
            return Err(ModelError::Bounds("ordinal"));
        }
        let partition = format!("observed:{collection_kind}:{collection_namespace}");
        Ok(Self {
            partition,
            collection_kind,
            collection_namespace,
            incarnation,
            ordinal,
            payload_digest,
        })
    }

    /// Returns the stable collection kind.
    #[must_use]
    pub fn collection_kind(&self) -> &str {
        &self.collection_kind
    }

    /// Returns the observed cluster namespace.
    #[must_use]
    pub fn collection_namespace(&self) -> &str {
        &self.collection_namespace
    }

    /// Returns the opaque observation-log lineage.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.incarnation
    }

    /// Returns the State-issued observation ordinal.
    #[must_use]
    pub const fn ordinal(&self) -> u64 {
        self.ordinal
    }

    /// Returns the digest of the recorded observation payload.
    #[must_use]
    pub const fn payload_digest(&self) -> &[u8; DIGEST_BYTES] {
        &self.payload_digest
    }

    fn partition(&self) -> &str {
        &self.partition
    }
}

impl PersonaMemoryCheckpoint {
    /// Records the record at `position`, whose canonical bytes digest to
    /// `record_digest`.
    #[must_use]
    pub const fn new(
        partition: String,
        incarnation: [u8; INCARNATION_BYTES],
        position: u64,
        record_digest: [u8; DIGEST_BYTES],
    ) -> Self {
        Self {
            partition,
            incarnation,
            position,
            record_digest,
        }
    }

    /// Returns the addressed partition.
    #[must_use]
    pub fn partition(&self) -> &str {
        &self.partition
    }

    /// Returns the opaque physical lineage.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.incarnation
    }

    /// Returns the history position.
    #[must_use]
    pub const fn position(&self) -> u64 {
        self.position
    }

    /// Returns the digest of the record at that position.
    #[must_use]
    pub const fn record_digest(&self) -> &[u8; DIGEST_BYTES] {
        &self.record_digest
    }
}

/// Which authority a projection generation folded from.
///
/// Each authority proves a point differently: a journal has a signed covering
/// root, a Versioned log has a lineage plus a re-readable entry digest, and the
/// query-audit history has a lineage plus the digest of the entry at an
/// ordinal. One variant each keeps the difference visible instead of flattening
/// them into a shape that fits none of them.
#[derive(Clone, PartialEq, Eq)]
pub enum ProjectionEvidence {
    /// A partition journal's commit feed, at a signed covering root.
    Journal(SourceCheckpoint),
    /// One Versioned aggregate's ordered change feed, at a re-readable entry.
    Versioned(VersionedCheckpoint),
    /// The query-audit authority's ordered history, at a re-readable entry.
    QueryAudit(AuditCheckpoint),
    /// One persona-memory partition's ordered history, at a re-readable
    /// position under a lineage the catalog re-derives.
    PersonaMemory(PersonaMemoryCheckpoint),
    /// One observed collection's recorded relist.
    Observed(ObservedCheckpoint),
}

impl ProjectionEvidence {
    /// Returns the partition the source lives in.
    #[must_use]
    pub fn partition(&self) -> &str {
        match self {
            Self::Journal(checkpoint) => checkpoint.source().partition(),
            Self::Versioned(checkpoint) => checkpoint.source().partition(),
            Self::QueryAudit(checkpoint) => checkpoint.partition(),
            Self::PersonaMemory(checkpoint) => checkpoint.partition(),
            Self::Observed(checkpoint) => checkpoint.partition(),
        }
    }

    /// Returns the opaque physical lineage.
    #[must_use]
    pub const fn incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        match self {
            Self::Journal(checkpoint) => checkpoint.source().incarnation(),
            Self::Versioned(checkpoint) => checkpoint.source().incarnation(),
            Self::QueryAudit(checkpoint) => checkpoint.incarnation(),
            Self::PersonaMemory(checkpoint) => checkpoint.incarnation(),
            Self::Observed(checkpoint) => checkpoint.incarnation(),
        }
    }

    /// Returns the feed position the generation folded through.
    #[must_use]
    pub const fn position(&self) -> u64 {
        match self {
            Self::Journal(checkpoint) => checkpoint.feed_position(),
            Self::Versioned(checkpoint) => checkpoint.position(),
            Self::QueryAudit(checkpoint) => checkpoint.ordinal(),
            Self::PersonaMemory(checkpoint) => checkpoint.position(),
            Self::Observed(checkpoint) => checkpoint.ordinal(),
        }
    }
}

/// How long a stored object is retained.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Retention {
    /// Retained for a fixed duration.
    For(Duration),
    /// Retained until an explicit release.
    UntilReleased,
}

/// What protection a stored object's content requires.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Classification {
    /// Readable without restriction.
    Public,
    /// Internal to the deployment.
    Internal,
    /// Confidential tenant content.
    Confidential,
    /// The most restricted class.
    Restricted,
}

/// One immutable stored object generation.
#[derive(Clone, PartialEq, Eq)]
pub struct ObjectDescriptor {
    object: String,
    generation: u64,
    digest: [u8; DIGEST_BYTES],
    owner: String,
    classification: Classification,
    retention: Retention,
    byte_len: u64,
    content_reference: String,
}

impl ObjectDescriptor {
    /// Records one immutable object generation.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for an empty object id, owner, or
    /// content reference.
    #[allow(
        clippy::too_many_arguments,
        reason = "every field of the signed descriptor is named explicitly"
    )]
    pub fn try_new(
        object: String,
        generation: u64,
        digest: [u8; DIGEST_BYTES],
        owner: String,
        classification: Classification,
        retention: Retention,
        byte_len: u64,
        content_reference: String,
    ) -> Result<Self, ModelError> {
        non_empty("object", &object)?;
        non_empty("owner", &owner)?;
        non_empty("content_reference", &content_reference)?;
        Ok(Self {
            object,
            generation,
            digest,
            owner,
            classification,
            retention,
            byte_len,
            content_reference,
        })
    }

    /// Returns the object id.
    #[must_use]
    pub fn object(&self) -> &str {
        &self.object
    }

    /// Returns the object generation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Returns the content digest.
    #[must_use]
    pub const fn digest(&self) -> &[u8; DIGEST_BYTES] {
        &self.digest
    }

    /// Returns the owner.
    #[must_use]
    pub fn owner(&self) -> &str {
        &self.owner
    }

    /// Returns the content classification.
    #[must_use]
    pub const fn classification(&self) -> Classification {
        self.classification
    }

    /// Returns the retention policy.
    #[must_use]
    pub const fn retention(&self) -> Retention {
        self.retention
    }

    /// Returns the stored byte length.
    #[must_use]
    pub const fn byte_len(&self) -> u64 {
        self.byte_len
    }

    /// Returns the content reference.
    #[must_use]
    pub fn content_reference(&self) -> &str {
        &self.content_reference
    }
}

/// One exact stored object in one namespace.
#[derive(Clone, PartialEq, Eq)]
pub struct ExactObjectRef {
    namespace: String,
    key: String,
    backend_generation: u64,
}

impl ExactObjectRef {
    /// Names one exact stored generation.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for an empty namespace or key.
    pub fn try_new(
        namespace: String,
        key: String,
        backend_generation: u64,
    ) -> Result<Self, ModelError> {
        non_empty("namespace", &namespace)?;
        non_empty("key", &key)?;
        Ok(Self {
            namespace,
            key,
            backend_generation,
        })
    }

    /// Returns the object namespace.
    #[must_use]
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Returns the object key.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Returns the backend generation.
    #[must_use]
    pub const fn backend_generation(&self) -> u64 {
        self.backend_generation
    }
}

/// One projection family bound to one source partition.
#[derive(Clone, PartialEq, Eq)]
pub struct ProjectionKey {
    family: String,
    source_partition: String,
}

impl ProjectionKey {
    /// Names one projection key.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for an empty family or partition.
    pub fn try_new(family: String, source_partition: String) -> Result<Self, ModelError> {
        non_empty("family", &family)?;
        non_empty("source_partition", &source_partition)?;
        Ok(Self {
            family,
            source_partition,
        })
    }

    /// Returns the family name.
    #[must_use]
    pub fn family(&self) -> &str {
        &self.family
    }

    /// Returns the source partition.
    #[must_use]
    pub fn source_partition(&self) -> &str {
        &self.source_partition
    }
}

/// The publisher term that produced one generation.
#[derive(Clone, PartialEq, Eq)]
pub struct PublisherFence {
    key: ProjectionKey,
    source_incarnation: [u8; INCARNATION_BYTES],
    term: u64,
}

impl PublisherFence {
    /// Records one publisher term.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for a zero term.
    pub fn try_new(
        key: ProjectionKey,
        source_incarnation: [u8; INCARNATION_BYTES],
        term: u64,
    ) -> Result<Self, ModelError> {
        if term == 0 {
            return Err(ModelError::Bounds("term"));
        }
        Ok(Self {
            key,
            source_incarnation,
            term,
        })
    }

    /// Returns the fenced projection key.
    #[must_use]
    pub const fn key(&self) -> &ProjectionKey {
        &self.key
    }

    /// Returns the fenced source incarnation.
    #[must_use]
    pub const fn source_incarnation(&self) -> &[u8; INCARNATION_BYTES] {
        &self.source_incarnation
    }

    /// Returns the publisher term.
    #[must_use]
    pub const fn term(&self) -> u64 {
        self.term
    }
}

/// One published projection generation, described exactly.
#[derive(Clone, PartialEq, Eq)]
pub struct ProjectionManifest {
    key: ProjectionKey,
    generation: u64,
    evidence: ProjectionEvidence,
    schema_version: u32,
    fact_version: u32,
    object: ObjectDescriptor,
    artifact_object: ExactObjectRef,
    publisher: String,
    fence: PublisherFence,
}

impl ProjectionManifest {
    /// Records one exact published generation.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] for a zero generation, a zero schema or
    /// fact version, or an empty publisher.
    #[allow(
        clippy::too_many_arguments,
        reason = "every field of the signed manifest is named explicitly"
    )]
    pub fn try_new(
        key: ProjectionKey,
        generation: u64,
        evidence: ProjectionEvidence,
        schema_version: u32,
        fact_version: u32,
        object: ObjectDescriptor,
        artifact_object: ExactObjectRef,
        publisher: String,
        fence: PublisherFence,
    ) -> Result<Self, ModelError> {
        if generation == 0 {
            return Err(ModelError::Bounds("generation"));
        }
        if schema_version == 0 {
            return Err(ModelError::Bounds("schema_version"));
        }
        if fact_version == 0 {
            return Err(ModelError::Bounds("fact_version"));
        }
        non_empty("publisher", &publisher)?;
        Ok(Self {
            key,
            generation,
            evidence,
            schema_version,
            fact_version,
            object,
            artifact_object,
            publisher,
            fence,
        })
    }

    /// Returns the projection key.
    #[must_use]
    pub const fn key(&self) -> &ProjectionKey {
        &self.key
    }

    /// Returns the projection generation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Returns the source evidence.
    #[must_use]
    pub const fn evidence(&self) -> &ProjectionEvidence {
        &self.evidence
    }

    /// Returns the schema version.
    #[must_use]
    pub const fn schema_version(&self) -> u32 {
        self.schema_version
    }

    /// Returns the fact version.
    #[must_use]
    pub const fn fact_version(&self) -> u32 {
        self.fact_version
    }

    /// Returns the manifest's own object descriptor.
    #[must_use]
    pub const fn object(&self) -> &ObjectDescriptor {
        &self.object
    }

    /// Returns the exact artifact object reference.
    #[must_use]
    pub const fn artifact_object(&self) -> &ExactObjectRef {
        &self.artifact_object
    }

    /// Returns the publisher identity.
    #[must_use]
    pub fn publisher(&self) -> &str {
        &self.publisher
    }

    /// Returns the publisher fence.
    #[must_use]
    pub const fn fence(&self) -> &PublisherFence {
        &self.fence
    }
}

/// One anchored journal prefix.
#[derive(Clone, PartialEq, Eq)]
pub struct JournalAnchor {
    source: JournalSource,
    head: u64,
}

impl JournalAnchor {
    /// Records one anchored journal prefix.
    #[must_use]
    pub const fn new(source: JournalSource, head: u64) -> Self {
        Self { source, head }
    }

    /// Returns the anchored lineage.
    #[must_use]
    pub const fn source(&self) -> &JournalSource {
        &self.source
    }

    /// Returns the anchored head position.
    #[must_use]
    pub const fn head(&self) -> u64 {
        self.head
    }
}

/// One exact source premise a result read.
#[derive(Clone, PartialEq, Eq)]
pub enum SourcePin {
    /// An exact published projection generation.
    ///
    /// Boxed: a manifest is far larger than the other two premises, and an
    /// unboxed variant would make every pin in a thirty-two-pin vector that
    /// size.
    Projected(Box<ProjectionManifest>),
    /// An exact anchored journal prefix.
    Journal(JournalAnchor),
    /// An authoritative revision.
    Authoritative(u64),
}

impl SourcePin {
    /// Returns the canonical identity this pin sorts by.
    ///
    /// The rule matches the durable audit's own: a variant tag, then each
    /// source's identity as length-prefixed bytes. Two projected descriptors
    /// for one key, two anchors for one partition, and two authoritative
    /// revisions therefore compare equal and are refused rather than
    /// collapsed.
    #[must_use]
    pub fn identity_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        match self {
            Self::Projected(manifest) => {
                bytes.push(0);
                push_len_prefixed(&mut bytes, manifest.key().family().as_bytes());
                push_len_prefixed(&mut bytes, manifest.key().source_partition().as_bytes());
            }
            Self::Journal(anchor) => {
                bytes.push(1);
                push_len_prefixed(&mut bytes, anchor.source().partition().as_bytes());
            }
            Self::Authoritative(_) => bytes.push(2),
        }
        bytes
    }
}

/// The bounded, canonical source premises one result reports.
#[derive(Clone, PartialEq, Eq)]
pub struct SourceEvidence {
    pins: Vec<SourcePin>,
}

impl SourceEvidence {
    /// Bounds and canonicalizes one complete source vector.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError::Bounds`] past [`MAX_SOURCE_PINS`], and
    /// [`ModelError::Order`] when the pins are not strictly ascending by
    /// identity. A duplicate source is an out-of-order pin, never a silent
    /// collapse.
    pub fn try_new(pins: Vec<SourcePin>) -> Result<Self, ModelError> {
        if pins.len() > MAX_SOURCE_PINS {
            return Err(ModelError::Bounds("source_pins"));
        }
        for pair in pins.windows(2) {
            if pair[0].identity_bytes() >= pair[1].identity_bytes() {
                return Err(ModelError::Order("source_pins"));
            }
        }
        Ok(Self { pins })
    }

    /// Returns every exact source premise in canonical order.
    #[must_use]
    pub fn pins(&self) -> &[SourcePin] {
        &self.pins
    }
}

// ---------------------------------------------------------------------------
// Shape-only formatting
// ---------------------------------------------------------------------------
//
// Source evidence names partitions, object keys, namespaces, publishers,
// signer keys, and signatures. `Debug` is what a `tracing` field and an
// `#[instrument]` attribute render, so every type here formats its shape and
// nothing that addresses tenant content. The typed getters above remain the
// way a mechanism reads the values it genuinely needs.

impl fmt::Debug for JournalSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("JournalSource")
    }
}

impl fmt::Debug for JournalAttestation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JournalAttestation")
            .field("leaf_count", &self.leaf_count)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for VersionedSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("VersionedSource")
    }
}

impl fmt::Debug for VersionedCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("VersionedCheckpoint")
            .field("position", &self.position)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for AuditCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The ordinal is shape. The lineage and the entry digest are content,
        // so neither is printed.
        formatter
            .debug_struct("AuditCheckpoint")
            .field("ordinal", &self.ordinal)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for PersonaMemoryCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The position is shape. The partition, the lineage, and the record
        // digest are content, so none of them is printed.
        formatter
            .debug_struct("PersonaMemoryCheckpoint")
            .field("position", &self.position)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ObservedCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The ordinal is shape. The collection namespace, lineage, and
        // payload digest are content, so none of them is printed.
        formatter
            .debug_struct("ObservedCheckpoint")
            .field("collection_kind", &self.collection_kind)
            .field("ordinal", &self.ordinal)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ProjectionEvidence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The variant is shape, not content: a reader needs to know WHICH
        // authority a generation folded from, and that names no tenant.
        match self {
            Self::Journal(checkpoint) => formatter
                .debug_tuple("ProjectionEvidence::Journal")
                .field(checkpoint)
                .finish(),
            Self::Versioned(checkpoint) => formatter
                .debug_tuple("ProjectionEvidence::Versioned")
                .field(checkpoint)
                .finish(),
            Self::QueryAudit(checkpoint) => formatter
                .debug_tuple("ProjectionEvidence::QueryAudit")
                .field(checkpoint)
                .finish(),
            Self::PersonaMemory(checkpoint) => formatter
                .debug_tuple("ProjectionEvidence::PersonaMemory")
                .field(checkpoint)
                .finish(),
            Self::Observed(checkpoint) => formatter
                .debug_tuple("ProjectionEvidence::Observed")
                .field(checkpoint)
                .finish(),
        }
    }
}

impl fmt::Debug for SourceCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SourceCheckpoint")
            .field("feed_position", &self.feed_position)
            .field("journal_position", &self.journal_position)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ObjectDescriptor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ObjectDescriptor")
            .field("generation", &self.generation)
            .field("classification", &self.classification)
            .field("byte_len", &self.byte_len)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ExactObjectRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExactObjectRef")
            .field("backend_generation", &self.backend_generation)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ProjectionKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ProjectionKey")
    }
}

impl fmt::Debug for PublisherFence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PublisherFence")
            .field("term", &self.term)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ProjectionManifest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProjectionManifest")
            .field("generation", &self.generation)
            .field("schema_version", &self.schema_version)
            .field("fact_version", &self.fact_version)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for JournalAnchor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JournalAnchor")
            .field("head", &self.head)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for SourcePin {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Projected(_) => "projected",
            Self::Journal(_) => "journal",
            Self::Authoritative(_) => "authoritative",
        })
    }
}

impl fmt::Debug for SourceEvidence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SourceEvidence")
            .field("pins", &self.pins.len())
            .finish()
    }
}

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

    fn journal(partition: &str) -> SourcePin {
        SourcePin::Journal(JournalAnchor::new(
            JournalSource::try_new(partition.to_owned(), [7; INCARNATION_BYTES]).unwrap(),
            4,
        ))
    }

    #[test]
    fn pins_must_be_strictly_ascending_and_bounded() {
        assert!(SourceEvidence::try_new(vec![journal("a"), journal("b")]).is_ok());
        assert_eq!(
            SourceEvidence::try_new(vec![journal("b"), journal("a")]),
            Err(ModelError::Order("source_pins"))
        );
        assert_eq!(
            SourceEvidence::try_new(vec![journal("a"), journal("a")]),
            Err(ModelError::Order("source_pins")),
            "one partition may be anchored once"
        );

        let overflowing = (0..=MAX_SOURCE_PINS)
            .map(|index| journal(&format!("p{index:04}")))
            .collect();
        assert_eq!(
            SourceEvidence::try_new(overflowing),
            Err(ModelError::Bounds("source_pins"))
        );
    }

    #[test]
    fn identity_ignores_everything_except_the_source_it_names() {
        let first = SourcePin::Journal(JournalAnchor::new(
            JournalSource::try_new("a".to_owned(), [1; INCARNATION_BYTES]).unwrap(),
            1,
        ));
        let second = SourcePin::Journal(JournalAnchor::new(
            JournalSource::try_new("a".to_owned(), [2; INCARNATION_BYTES]).unwrap(),
            9,
        ));
        assert_eq!(first.identity_bytes(), second.identity_bytes());
    }

    #[test]
    fn structural_bounds_refuse_empty_identifiers() {
        assert_eq!(
            JournalSource::try_new(String::new(), [0; INCARNATION_BYTES]),
            Err(ModelError::Bounds("partition"))
        );
        assert_eq!(
            ProjectionKey::try_new(String::new(), "p".to_owned()),
            Err(ModelError::Bounds("family"))
        );
        assert_eq!(
            ExactObjectRef::try_new("ns".to_owned(), String::new(), 1),
            Err(ModelError::Bounds("key"))
        );
    }
}