polyc-state-connect 2026.9.0

State plane transport adapter: capability-specific Connect clients and server-trait glue mapping the generated wire types onto the polyc-state kernel — typed outcomes, per-call admission, and the conformance surface the authenticated shell proves itself against (docs/proposals/separated-planes.md).
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
//! The mapping between the commit feed's vocabulary and its encoding.
//!
//! Same rules as [`crate::wire`] and [`crate::journal::wire`], and the same
//! helpers: every conversion is an explicit `From` or `TryFrom` naming each
//! field, [`Kernel`] carries the local type the orphan rule needs, kernel to
//! wire is infallible, and wire to kernel returns [`StateError::Malformed`]
//! naming the field it could not interpret.
//!
//! Two things are deliberately not on the wire. A feed command's resource
//! bounds, for the same reason a journal command's are not — they belong to the
//! operation family, and a bound a caller could send is a bound a caller could
//! widen. And the stream contract on a subscription request: the contract is the
//! server's declaration, read through `DescribeFeedStream`, not something a
//! caller proposes.

use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    command::{
        CommandEnvelope, CommandMetadata, CommandScope, FencingToken, Precondition, ResourceBounds,
    },
    digest::ContentDigest,
    error::StateError,
    feed::{
        self, AcknowledgeProjectorCursor, CommitEnvelope, CompactFeedPrefix, ConsumerPolicy,
        CreateSnapshot, FeedAnchor, FeedChunk, FeedCompaction, FeedCursor, FeedReadStart,
        FeedRecord, FeedRetention, FeedSnapshot, ProjectorRegistration, ProjectorStatus,
        RegisterProjector, SourceCheckpoint, SubscribeCommits,
    },
    id::{AggregateId, Audience, CommandId, ConsumerId, NamespaceId, Purpose, SnapshotId},
    journal::JournalAttestation,
    journal::JournalRecord,
    page::Positioned as _,
    receipt::Receipt,
    revision::{JournalPosition, JournalSource},
};

use crate::{
    DeclaredCall,
    wire::{Kernel, fixed_bytes, known, malformed, required},
};

// ---------------------------------------------------------------------------
// Consumer policy
// ---------------------------------------------------------------------------

impl From<Kernel<ConsumerPolicy>> for pb::ConsumerPolicy {
    fn from(value: Kernel<ConsumerPolicy>) -> Self {
        match value.0 {
            ConsumerPolicy::Required => Self::CONSUMER_POLICY_REQUIRED,
            ConsumerPolicy::Optional => Self::CONSUMER_POLICY_OPTIONAL,
        }
    }
}

/// Reads a consumer's retention policy off the wire.
///
/// An unset policy is refused rather than defaulted. Defaulting either way is
/// wrong: to required, and an unregistered peer could pin a partition's storage
/// forever; to optional, and a projector that meant to hold its prefix silently
/// stops holding it.
fn consumer_policy(
    field: &str,
    value: buffa::EnumValue<pb::ConsumerPolicy>,
) -> Result<ConsumerPolicy, StateError> {
    match known(field, value)? {
        pb::ConsumerPolicy::CONSUMER_POLICY_REQUIRED => Ok(ConsumerPolicy::Required),
        pb::ConsumerPolicy::CONSUMER_POLICY_OPTIONAL => Ok(ConsumerPolicy::Optional),
        pb::ConsumerPolicy::CONSUMER_POLICY_UNSPECIFIED => Err(malformed(
            field,
            "a projector declares whether its lag holds the feed prefix",
        )),
    }
}

// ---------------------------------------------------------------------------
// Feed commands
// ---------------------------------------------------------------------------

/// Returns the bounds every feed command declares.
///
/// The family's own, not the caller's. A feed command carries no payload of its
/// own — a snapshot, a registration, an acknowledgement, and a compaction are
/// all a handful of fields — so the byte bound is the one the transport already
/// enforces, and the record bound is one command.
const fn feed_bounds() -> ResourceBounds {
    ResourceBounds::new(crate::MAX_WIRE_MESSAGE_BYTES as u64, 1)
}

impl From<Kernel<&CommandMetadata>> for pb::FeedCommand {
    /// Encodes the identity, addressing, and preconditions a feed command
    /// carries.
    fn from(value: Kernel<&CommandMetadata>) -> Self {
        let metadata = value.0;
        Self {
            command_id: metadata.command_id().as_str().to_owned(),
            source: buffa::MessageField::default(),
            aggregate: metadata.scope().aggregate().as_str().to_owned(),
            namespace: metadata.scope().namespace().as_str().to_owned(),
            purpose: metadata.envelope().purpose().as_str().to_owned(),
            audience: metadata.envelope().audience().as_str().to_owned(),
            digest: metadata.digest().as_bytes().to_vec(),
            precondition: buffa::MessageField::some(pb::Precondition::from(Kernel(
                metadata.precondition(),
            ))),
            fence: metadata.fence().map(FencingToken::get),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedCommand> for Kernel<CommandMetadata> {
    type Error = StateError;

    /// Reads the metadata a feed command carries.
    ///
    /// The protocol version is deliberately left at the current one rather than
    /// read off the command: it rides on the call's `CallContext` and is checked
    /// at admission, before a handler runs. A second copy inside the command
    /// would be a second place a peer could disagree with itself.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `digest` when the digest is not
    /// [`ContentDigest::LEN`] bytes, and `precondition` when the command names
    /// none.
    fn try_from(value: pb::FeedCommand) -> Result<Self, Self::Error> {
        let pb::FeedCommand {
            command_id,
            source,
            aggregate,
            namespace,
            purpose,
            audience,
            digest,
            precondition,
            fence,
            __buffa_unknown_fields: _,
        } = value;
        let digest =
            ContentDigest::from_bytes(fixed_bytes::<{ ContentDigest::LEN }>("digest", &digest)?);
        let precondition = Kernel::<Precondition>::try_from(required(
            "precondition",
            "a precondition names what durable state the command requires",
            precondition,
        )?)?
        .into_inner();

        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "a feed command names an exact physical source",
            source,
        )?)?
        .into_inner();
        let mut metadata = CommandMetadata::new(
            CommandId::new(command_id),
            feed::family(),
            digest,
            CommandScope::new(
                AggregateId::new(aggregate),
                source.partition().clone(),
                NamespaceId::new(namespace),
            ),
            CommandEnvelope::new(
                Purpose::new(purpose),
                Audience::new(audience),
                feed_bounds(),
            ),
        )
        .with_precondition(precondition);
        if let Some(fence) = fence {
            metadata = metadata.with_fence(FencingToken::new(fence));
        }
        Ok(Self(metadata))
    }
}

impl From<Kernel<&CreateSnapshot>> for pb::FeedCommand {
    fn from(value: Kernel<&CreateSnapshot>) -> Self {
        let mut command = Self::from(Kernel(value.0.metadata()));
        command.source =
            buffa::MessageField::some(pb::JournalSource::from(Kernel(value.0.source())));
        command
    }
}

impl From<Kernel<&RegisterProjector>> for pb::FeedCommand {
    fn from(value: Kernel<&RegisterProjector>) -> Self {
        let mut command = Self::from(Kernel(value.0.metadata()));
        command.source = buffa::MessageField::some(pb::JournalSource::from(Kernel(
            value.0.registration().source(),
        )));
        command
    }
}

impl From<Kernel<&AcknowledgeProjectorCursor>> for pb::FeedCommand {
    fn from(value: Kernel<&AcknowledgeProjectorCursor>) -> Self {
        let mut command = Self::from(Kernel(value.0.metadata()));
        command.source =
            buffa::MessageField::some(pb::JournalSource::from(Kernel(value.0.cursor().source())));
        command
    }
}

impl From<Kernel<&CompactFeedPrefix>> for pb::FeedCommand {
    fn from(value: Kernel<&CompactFeedPrefix>) -> Self {
        let mut command = Self::from(Kernel(value.0.metadata()));
        command.source =
            buffa::MessageField::some(pb::JournalSource::from(Kernel(value.0.source())));
        command
    }
}

// ---------------------------------------------------------------------------
// Exact source checkpoints and cursors
// ---------------------------------------------------------------------------

impl From<Kernel<&SourceCheckpoint>> for pb::SourceCheckpoint {
    fn from(value: Kernel<&SourceCheckpoint>) -> Self {
        let checkpoint = value.0;
        Self {
            source: buffa::MessageField::some(pb::JournalSource::from(Kernel(checkpoint.source()))),
            feed_position: checkpoint.feed_position().get(),
            journal_position: checkpoint.journal_position().get(),
            evidence_leaf: checkpoint.evidence_leaf(),
            covering_attestation: buffa::MessageField::some(pb::JournalAttestation::from(Kernel(
                checkpoint.covering_attestation(),
            ))),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::SourceCheckpoint> for Kernel<SourceCheckpoint> {
    type Error = StateError;

    fn try_from(value: pb::SourceCheckpoint) -> Result<Self, Self::Error> {
        let pb::SourceCheckpoint {
            source,
            feed_position,
            journal_position,
            evidence_leaf,
            covering_attestation,
            __buffa_unknown_fields: _,
        } = value;
        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "a checkpoint names an exact physical source",
            source,
        )?)?
        .into_inner();
        let attestation = Kernel::<JournalAttestation>::try_from(required(
            "covering_attestation",
            "a checkpoint carries the later signed root that covers its journal prefix",
            covering_attestation,
        )?)?
        .into_inner();
        Ok(Self(SourceCheckpoint::try_new(
            source,
            JournalPosition::new(feed_position),
            JournalPosition::new(journal_position),
            evidence_leaf,
            attestation,
        )?))
    }
}

impl From<Kernel<&FeedCursor>> for pb::FeedCursor {
    fn from(value: Kernel<&FeedCursor>) -> Self {
        let cursor = value.0;
        Self {
            source: buffa::MessageField::some(pb::JournalSource::from(Kernel(cursor.source()))),
            checkpoint: cursor.checkpoint().map_or_else(
                buffa::MessageField::default,
                |checkpoint| {
                    buffa::MessageField::some(pb::SourceCheckpoint::from(Kernel(checkpoint)))
                },
            ),
            snapshot: cursor
                .snapshot()
                .map(|snapshot| snapshot.as_str().to_owned()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedCursor> for Kernel<FeedCursor> {
    type Error = StateError;

    fn try_from(value: pb::FeedCursor) -> Result<Self, Self::Error> {
        let pb::FeedCursor {
            source,
            checkpoint,
            snapshot,
            __buffa_unknown_fields: _,
        } = value;
        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "a feed cursor names an exact physical source",
            source,
        )?)?
        .into_inner();
        let checkpoint = checkpoint
            .into_option()
            .map(|checkpoint| {
                Kernel::<SourceCheckpoint>::try_from(checkpoint).map(Kernel::into_inner)
            })
            .transpose()?;
        if checkpoint
            .as_ref()
            .is_some_and(|checkpoint| checkpoint.source() != &source)
        {
            return Err(malformed(
                "checkpoint",
                "a cursor and its checkpoint name the same physical source",
            ));
        }
        let cursor = match (snapshot, checkpoint) {
            (Some(snapshot), Some(checkpoint)) if !snapshot.is_empty() => {
                FeedCursor::in_snapshot(SnapshotId::new(snapshot), checkpoint)
            }
            (Some(_), Some(_)) => {
                return Err(malformed("snapshot", "snapshot provenance is non-empty"));
            }
            (Some(_), None) => {
                return Err(malformed(
                    "checkpoint",
                    "snapshot provenance accompanies an issued checkpoint",
                ));
            }
            (None, Some(checkpoint)) => FeedCursor::at(checkpoint),
            (None, None) => FeedCursor::origin(source),
        };
        Ok(Self(cursor))
    }
}

impl From<Kernel<&FeedReadStart>> for pb::FeedReadStart {
    fn from(value: Kernel<&FeedReadStart>) -> Self {
        use pb::__buffa::oneof::feed_read_start::Start;
        let start = match value.0 {
            FeedReadStart::Snapshot(snapshot) => Start::Snapshot(snapshot.as_str().to_owned()),
            FeedReadStart::Resume(cursor) => {
                Start::from(pb::FeedCursor::from(Kernel(cursor.as_ref())))
            }
        };
        Self {
            start: Some(start),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedReadStart> for Kernel<FeedReadStart> {
    type Error = StateError;

    fn try_from(value: pb::FeedReadStart) -> Result<Self, Self::Error> {
        use pb::__buffa::oneof::feed_read_start::Start;
        let pb::FeedReadStart {
            start,
            __buffa_unknown_fields: _,
        } = value;
        let start = match start {
            Some(Start::Snapshot(snapshot)) if !snapshot.is_empty() => {
                FeedReadStart::Snapshot(SnapshotId::new(snapshot))
            }
            Some(Start::Snapshot(_)) => {
                return Err(malformed(
                    "start",
                    "a snapshot start names a non-empty identity",
                ));
            }
            Some(Start::Resume(cursor)) => FeedReadStart::Resume(Box::new(
                Kernel::<FeedCursor>::try_from(*cursor)?.into_inner(),
            )),
            None => return Err(malformed("start", "a feed read names where it begins")),
        };
        Ok(Self(start))
    }
}

// ---------------------------------------------------------------------------
// Feed entries
// ---------------------------------------------------------------------------

impl From<Kernel<&CommitEnvelope>> for pb::CommitEnvelope {
    fn from(value: Kernel<&CommitEnvelope>) -> Self {
        let envelope = value.0;
        Self {
            checkpoint: buffa::MessageField::some(pb::SourceCheckpoint::from(Kernel(
                envelope.checkpoint(),
            ))),
            command_id: envelope.command_id().as_str().to_owned(),
            digest: envelope.digest().as_bytes().to_vec(),
            fence: envelope.fence().map(FencingToken::get),
            head_before: envelope.head_before().get(),
            head_after: envelope.head_after().get(),
            record_count: envelope.record_count(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::CommitEnvelope> for Kernel<CommitEnvelope> {
    type Error = StateError;

    /// Reads what one commit recorded about itself.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `digest` when the digest is not
    /// [`ContentDigest::LEN`] bytes — a commit whose digest cannot be read is
    /// one a projector could not compare against anything.
    fn try_from(value: pb::CommitEnvelope) -> Result<Self, Self::Error> {
        let pb::CommitEnvelope {
            checkpoint,
            command_id,
            digest,
            fence,
            head_before,
            head_after,
            record_count,
            __buffa_unknown_fields: _,
        } = value;
        let checkpoint = Kernel::<SourceCheckpoint>::try_from(required(
            "checkpoint",
            "a commit envelope carries its exact source evidence point",
            checkpoint,
        )?)?
        .into_inner();
        let digest =
            ContentDigest::from_bytes(fixed_bytes::<{ ContentDigest::LEN }>("digest", &digest)?);
        if command_id.is_empty() {
            return Err(malformed(
                "command_id",
                "a commit envelope names a non-empty command identity",
            ));
        }
        let envelope = CommitEnvelope::new(
            checkpoint,
            CommandId::new(command_id),
            digest,
            JournalPosition::new(head_before),
            JournalPosition::new(head_after),
            record_count,
        );
        Ok(Self(match fence {
            Some(fence) => envelope.with_fence(FencingToken::new(fence)),
            None => envelope,
        }))
    }
}

impl From<Kernel<&FeedRecord>> for pb::FeedRecord {
    fn from(value: Kernel<&FeedRecord>) -> Self {
        let entry = value.0;
        Self {
            position: entry.position().get(),
            envelope: buffa::MessageField::some(pb::CommitEnvelope::from(Kernel(entry.envelope()))),
            records: entry
                .records()
                .iter()
                .map(|record| pb::JournalRecord::from(Kernel(record)))
                .collect(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedRecord> for Kernel<FeedRecord> {
    type Error = StateError;

    /// Reads one entry of the durable feed.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `envelope` when the entry
    /// carries none — an entry with no envelope is a batch of records with
    /// nothing saying which commit produced them — and whatever the envelope and
    /// record conversions themselves report.
    fn try_from(value: pb::FeedRecord) -> Result<Self, Self::Error> {
        let pb::FeedRecord {
            position,
            envelope,
            records,
            __buffa_unknown_fields: _,
        } = value;
        let envelope = Kernel::<CommitEnvelope>::try_from(required(
            "envelope",
            "a feed entry carries the commit it describes",
            envelope,
        )?)?
        .into_inner();
        let records = records
            .into_iter()
            .map(|record| Kernel::<JournalRecord>::try_from(record).map(Kernel::into_inner))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self(FeedRecord::new(
            JournalPosition::new(position),
            envelope,
            records,
        )))
    }
}

impl From<Kernel<&FeedChunk>> for pb::FeedChunk {
    fn from(value: Kernel<&FeedChunk>) -> Self {
        let chunk = value.0;
        Self {
            records: chunk
                .records()
                .iter()
                .map(|record| pb::FeedRecord::from(Kernel(record)))
                .collect(),
            next: buffa::MessageField::some(pb::FeedCursor::from(Kernel(chunk.next_cursor()))),
            end: pb::StreamEnd::from(Kernel(chunk.end())).into(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedChunk> for Kernel<FeedChunk> {
    type Error = StateError;

    /// Reads one bounded chunk of a commit feed.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `end` when the chunk does not
    /// say why it stopped — which is what distinguishes a drain from exhaustion
    /// — and whatever the entry conversions report.
    fn try_from(value: pb::FeedChunk) -> Result<Self, Self::Error> {
        let pb::FeedChunk {
            records,
            next,
            end,
            __buffa_unknown_fields: _,
        } = value;
        let end = crate::wire::stream_end("end", end)?;
        let records = records
            .into_iter()
            .map(|record| Kernel::<FeedRecord>::try_from(record).map(Kernel::into_inner))
            .collect::<Result<Vec<_>, _>>()?;
        let next = Kernel::<FeedCursor>::try_from(required(
            "next",
            "every feed chunk carries the exact cursor to persist",
            next,
        )?)?
        .into_inner();
        Ok(Self(FeedChunk::new(records, next, end)))
    }
}

// ---------------------------------------------------------------------------
// Snapshots
// ---------------------------------------------------------------------------

impl From<Kernel<&FeedSnapshot>> for pb::FeedSnapshot {
    fn from(value: Kernel<&FeedSnapshot>) -> Self {
        let snapshot = value.0;
        Self {
            snapshot: snapshot.id().as_str().to_owned(),
            checkpoint: buffa::MessageField::some(pb::SourceCheckpoint::from(Kernel(
                snapshot.anchor().checkpoint(),
            ))),
            receipt: buffa::MessageField::some(pb::Receipt::from(Kernel(snapshot.receipt()))),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedSnapshot> for Kernel<FeedSnapshot> {
    type Error = StateError;

    /// Reads one immutable snapshot of a partition's feed.
    ///
    /// The anchor is rebuilt from the identity rather than from the loose
    /// partition and position fields, and then checked against them. An identity
    /// that disagreed with the fields beside it would let a consumer bootstrap
    /// from one prefix while believing it bootstrapped from another.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `snapshot` when the identity is
    /// not one the contract could have issued or does not match the partition
    /// and position beside it, and `receipt` when a snapshot arrives without the
    /// durable receipt that recorded it.
    fn try_from(value: pb::FeedSnapshot) -> Result<Self, Self::Error> {
        let pb::FeedSnapshot {
            snapshot,
            checkpoint,
            receipt,
            __buffa_unknown_fields: _,
        } = value;
        let anchor = FeedAnchor::parse(&SnapshotId::new(snapshot))?;
        let checkpoint = Kernel::<SourceCheckpoint>::try_from(required(
            "checkpoint",
            "a feed snapshot carries its exact source evidence point",
            checkpoint,
        )?)?
        .into_inner();
        if anchor.checkpoint() != &checkpoint {
            return Err(malformed(
                "snapshot",
                "a snapshot identity names the exact checkpoint beside it",
            ));
        }
        let receipt = Kernel::<Receipt>::try_from(required(
            "receipt",
            "a recorded snapshot carries the receipt that recorded it",
            receipt,
        )?)?
        .into_inner();
        Ok(Self(FeedSnapshot::new(anchor, receipt)))
    }
}

// ---------------------------------------------------------------------------
// Subscriptions
// ---------------------------------------------------------------------------

impl From<Kernel<(&DeclaredCall, &SubscribeCommits)>> for pb::SubscribeCommitsRequest {
    fn from(value: Kernel<(&DeclaredCall, &SubscribeCommits)>) -> Self {
        let (declared, request) = value.0;
        Self {
            context: buffa::MessageField::some(pb::CallContext::from(Kernel(declared))),
            source: buffa::MessageField::some(pb::JournalSource::from(Kernel(request.source()))),
            start: buffa::MessageField::some(pb::FeedReadStart::from(Kernel(request.start()))),
            max_chunk_commits: request.max_chunk_commits(),
            consumer: request
                .consumer()
                .map(|consumer| consumer.as_str().to_owned()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

/// One decoded subscription request, including its transport admission context.
#[derive(Debug)]
pub struct SubscriptionRequest {
    /// The caller's declared admission and budget context.
    pub context: buffa::MessageField<pb::CallContext, buffa::Inline<pb::CallContext>>,
    /// The exact source, start, bound, and optional registered consumer.
    pub subscription: SubscribeCommits,
}

impl TryFrom<pb::SubscribeCommitsRequest> for Kernel<SubscriptionRequest> {
    type Error = StateError;

    /// Reads one complete subscription request off the wire.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `start` when the request omits
    /// where it begins. The error names `partition` when the request names none.
    /// A subscription without a partition is not a subscription to everything.
    /// This contract cannot serve it (INV-21).
    fn try_from(value: pb::SubscribeCommitsRequest) -> Result<Self, Self::Error> {
        let pb::SubscribeCommitsRequest {
            context,
            source,
            start,
            max_chunk_commits,
            consumer,
            __buffa_unknown_fields: _,
        } = value;
        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "a subscription names exactly one physical source",
            source,
        )?)?
        .into_inner();
        let start = Kernel::<FeedReadStart>::try_from(required(
            "start",
            "a subscription names where it begins",
            start,
        )?)?
        .into_inner();

        if let FeedReadStart::Resume(cursor) = &start
            && cursor.source() != &source
        {
            return Err(malformed(
                "start",
                "a subscription and its resume cursor name the same physical source",
            ));
        }
        let request = SubscribeCommits::new(source, start, max_chunk_commits);
        let subscription = match consumer {
            Some(consumer) if !consumer.is_empty() => {
                request.on_behalf_of(ConsumerId::new(consumer))
            }
            Some(_) => {
                return Err(malformed(
                    "consumer",
                    "a present subscription consumer identity is non-empty",
                ));
            }
            None => request,
        };
        Ok(Self(SubscriptionRequest {
            context,
            subscription,
        }))
    }
}

// ---------------------------------------------------------------------------
// Registration and retention
// ---------------------------------------------------------------------------

impl From<Kernel<&ProjectorRegistration>> for pb::ProjectorRegistration {
    fn from(value: Kernel<&ProjectorRegistration>) -> Self {
        let registration = value.0;
        Self {
            consumer: registration.consumer().as_str().to_owned(),
            source: buffa::MessageField::some(pb::JournalSource::from(Kernel(
                registration.source(),
            ))),
            policy: pb::ConsumerPolicy::from(Kernel(registration.policy())).into(),
            declared_lag_commits: registration.declared_lag_commits(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::ProjectorRegistration> for Kernel<ProjectorRegistration> {
    type Error = StateError;

    /// Reads what one projector declared about itself.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `policy` when the registration
    /// declares no retention policy or one this build does not know.
    fn try_from(value: pb::ProjectorRegistration) -> Result<Self, Self::Error> {
        let pb::ProjectorRegistration {
            consumer,
            source,
            policy,
            declared_lag_commits,
            __buffa_unknown_fields: _,
        } = value;
        let policy = consumer_policy("policy", policy)?;
        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "a projector registration names an exact physical source",
            source,
        )?)?
        .into_inner();
        if consumer.is_empty() {
            return Err(malformed(
                "consumer",
                "a projector names a non-empty consumer",
            ));
        }
        Ok(Self(ProjectorRegistration::new(
            ConsumerId::new(consumer),
            source,
            policy,
            declared_lag_commits,
        )))
    }
}

impl From<Kernel<&ProjectorStatus>> for pb::ProjectorStatus {
    fn from(value: Kernel<&ProjectorStatus>) -> Self {
        let status = value.0;
        Self {
            registration: buffa::MessageField::some(pb::ProjectorRegistration::from(Kernel(
                status.registration(),
            ))),
            acknowledged: buffa::MessageField::some(pb::FeedCursor::from(Kernel(
                status.acknowledged(),
            ))),
            evicted: status.is_evicted(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::ProjectorStatus> for Kernel<ProjectorStatus> {
    type Error = StateError;

    /// Reads what the feed reports about one projector.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `registration` when the status
    /// carries none, and whatever the registration conversion reports.
    fn try_from(value: pb::ProjectorStatus) -> Result<Self, Self::Error> {
        let pb::ProjectorStatus {
            registration,
            acknowledged,
            evicted,
            __buffa_unknown_fields: _,
        } = value;
        let registration = Kernel::<ProjectorRegistration>::try_from(required(
            "registration",
            "a projector status carries what the projector declared",
            registration,
        )?)?
        .into_inner();
        let acknowledged = Kernel::<FeedCursor>::try_from(required(
            "acknowledged",
            "a projector status carries the exact cursor it applied",
            acknowledged,
        )?)?
        .into_inner();
        if registration.source() != acknowledged.source() {
            return Err(malformed(
                "acknowledged",
                "a projector status and cursor name the same physical source",
            ));
        }
        let status = ProjectorStatus::new(registration, acknowledged);
        Ok(Self(if evicted { status.evicted() } else { status }))
    }
}

impl From<Kernel<&FeedRetention>> for pb::FeedRetention {
    fn from(value: Kernel<&FeedRetention>) -> Self {
        let retention = value.0;
        Self {
            source: buffa::MessageField::some(pb::JournalSource::from(Kernel(retention.source()))),
            earliest: retention.earliest().get(),
            head: retention.head().get(),
            held_by: retention
                .held_by_consumer()
                .map(|consumer| consumer.as_str().to_owned()),
            pinned_by: retention
                .pinned_by_snapshot()
                .map(|snapshot| snapshot.as_str().to_owned()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedRetention> for Kernel<FeedRetention> {
    type Error = StateError;

    fn try_from(value: pb::FeedRetention) -> Result<Self, Self::Error> {
        let pb::FeedRetention {
            source,
            earliest,
            head,
            held_by,
            pinned_by,
            __buffa_unknown_fields: _,
        } = value;
        let source = Kernel::<JournalSource>::try_from(required(
            "source",
            "feed retention names an exact physical source",
            source,
        )?)?
        .into_inner();
        let retention = FeedRetention::new(
            source,
            JournalPosition::new(earliest),
            JournalPosition::new(head),
        );
        let retention = match held_by {
            Some(consumer) if !consumer.is_empty() => retention.held_by(ConsumerId::new(consumer)),
            Some(_) => {
                return Err(malformed(
                    "held_by",
                    "a present retention consumer identity is non-empty",
                ));
            }
            None => retention,
        };
        Ok(Self(match pinned_by {
            Some(snapshot) if !snapshot.is_empty() => {
                retention.pinned_by(SnapshotId::new(snapshot))
            }
            Some(_) => {
                return Err(malformed(
                    "pinned_by",
                    "a present retention snapshot identity is non-empty",
                ));
            }
            None => retention,
        }))
    }
}

impl From<Kernel<&FeedCompaction>> for pb::FeedCompaction {
    fn from(value: Kernel<&FeedCompaction>) -> Self {
        let compaction = value.0;
        Self {
            retention: buffa::MessageField::some(pb::FeedRetention::from(Kernel(
                compaction.retention(),
            ))),
            evicted: compaction
                .evicted()
                .iter()
                .map(|consumer| consumer.as_str().to_owned())
                .collect(),
            receipt: buffa::MessageField::some(pb::Receipt::from(Kernel(compaction.receipt()))),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl TryFrom<pb::FeedCompaction> for Kernel<FeedCompaction> {
    type Error = StateError;

    /// Reads what one compaction did.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `retention` when the result
    /// carries none, or naming `receipt` when the exact result has no durable
    /// settlement a retry could recover.
    fn try_from(value: pb::FeedCompaction) -> Result<Self, Self::Error> {
        let pb::FeedCompaction {
            retention,
            evicted,
            receipt,
            __buffa_unknown_fields: _,
        } = value;
        let retention = Kernel::<FeedRetention>::try_from(required(
            "retention",
            "a compaction reports what the partition now retains",
            retention,
        )?)?
        .into_inner();
        if evicted.iter().any(String::is_empty) {
            return Err(malformed(
                "evicted",
                "every evicted consumer identity is non-empty",
            ));
        }
        let evicted = evicted.into_iter().map(ConsumerId::new).collect();
        let receipt = Kernel::<Receipt>::try_from(required(
            "receipt",
            "a compaction result carries its durable settlement",
            receipt,
        )?)?
        .into_inner();
        Ok(Self(FeedCompaction::new(retention, evicted, receipt)))
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use super::*;
    use polyc_state::{
        consistency::Consistency,
        feed::{ATTESTATION_SIGNATURE_BYTES, ATTESTATION_SIGNER_BYTES},
        id::PartitionId,
        journal::{JournalAttestation, RecordKind, RecordTrust},
        receipt::CommitEvidence,
        revision::{CommitRoot, PartitionIncarnation},
    };

    fn metadata() -> CommandMetadata {
        CommandMetadata::new(
            CommandId::new("cmd-1"),
            feed::family(),
            ContentDigest::from_bytes([3; ContentDigest::LEN]),
            CommandScope::new(
                AggregateId::new("conv-1"),
                PartitionId::new("conv-1"),
                NamespaceId::new("default"),
            ),
            CommandEnvelope::new(
                Purpose::new("projection"),
                crate::state_audience(),
                feed_bounds(),
            ),
        )
        .with_fence(FencingToken::new(4))
    }

    fn receipt() -> Receipt {
        Receipt::committed(
            &metadata(),
            CommitEvidence::new()
                .with_snapshot(SnapshotId::new("feed:conv-1@3"))
                .with_position(JournalPosition::new(3)),
            Consistency::OrderedPerAggregate,
        )
    }

    fn source() -> JournalSource {
        JournalSource::new(
            PartitionId::new("conv-1"),
            PartitionIncarnation::from_bytes([7; PartitionIncarnation::LEN]),
        )
    }

    fn checkpoint(feed_position: u64, journal_position: u64) -> SourceCheckpoint {
        SourceCheckpoint::try_new(
            source(),
            JournalPosition::new(feed_position),
            JournalPosition::new(journal_position),
            journal_position,
            JournalAttestation::new(
                CommitRoot::from_bytes([journal_position as u8; CommitRoot::LEN]),
                journal_position + 1,
                vec![3; ATTESTATION_SIGNATURE_BYTES],
                vec![4; ATTESTATION_SIGNER_BYTES],
            ),
        )
        .expect("a complete test checkpoint")
    }

    fn cursor(position: u64) -> FeedCursor {
        if position == 0 {
            FeedCursor::origin(source())
        } else {
            FeedCursor::at(checkpoint(position, position + 4))
        }
    }

    fn entry() -> FeedRecord {
        FeedRecord::new(
            JournalPosition::new(3),
            CommitEnvelope::new(
                checkpoint(3, 7),
                CommandId::new("cmd-9"),
                ContentDigest::from_bytes([8; ContentDigest::LEN]),
                JournalPosition::new(5),
                JournalPosition::new(7),
                2,
            )
            .with_fence(FencingToken::new(2)),
            vec![
                JournalRecord::new(
                    JournalPosition::new(6),
                    RecordKind::new("turn_input"),
                    RecordTrust::TrustedUser,
                    b"one".to_vec(),
                ),
                JournalRecord::new(
                    JournalPosition::new(7),
                    RecordKind::new("turn_output"),
                    RecordTrust::QuarantinedContent,
                    b"two".to_vec(),
                ),
            ],
        )
    }

    #[test]
    fn a_feed_command_round_trips_every_field_it_carries() {
        let encoded = pb::FeedCommand::from(Kernel(&CreateSnapshot::new(metadata(), source())));
        let back = Kernel::<CommandMetadata>::try_from(encoded).unwrap().0;
        assert_eq!(back, metadata());
    }

    #[test]
    fn every_command_shape_encodes_through_the_same_metadata() {
        let expected = pb::FeedCommand::from(Kernel(&metadata()));
        let mut expected = expected;
        expected.source = buffa::MessageField::some(pb::JournalSource::from(Kernel(&source())));
        assert_eq!(
            pb::FeedCommand::from(Kernel(&CreateSnapshot::new(metadata(), source()))),
            expected
        );
        assert_eq!(
            pb::FeedCommand::from(Kernel(&CompactFeedPrefix::new(
                metadata(),
                source(),
                JournalPosition::new(4)
            ))),
            expected
        );
        assert_eq!(
            pb::FeedCommand::from(Kernel(&AcknowledgeProjectorCursor::new(
                metadata(),
                ConsumerId::new("search"),
                cursor(2)
            ))),
            expected
        );
        assert_eq!(
            pb::FeedCommand::from(Kernel(&RegisterProjector::new(
                metadata(),
                ProjectorRegistration::new(
                    ConsumerId::new("search"),
                    source(),
                    ConsumerPolicy::Required,
                    4,
                )
            ))),
            expected
        );
    }

    #[test]
    fn a_feed_entry_round_trips_its_envelope_and_every_record() {
        let encoded = pb::FeedRecord::from(Kernel(&entry()));
        let back = Kernel::<FeedRecord>::try_from(encoded).unwrap().0;
        assert_eq!(back, entry());
        assert!(back.is_self_consistent());
    }

    #[test]
    fn a_chunk_round_trips_its_records_cursor_and_reason_for_stopping() {
        for end in [
            polyc_state::stream::StreamEnd::More,
            polyc_state::stream::StreamEnd::Exhausted,
            polyc_state::stream::StreamEnd::Drained,
        ] {
            let cursor =
                FeedCursor::in_snapshot(SnapshotId::new("feed:test-snapshot"), checkpoint(3, 7));
            let chunk = FeedChunk::new(vec![entry()], cursor, end);
            let back = Kernel::<FeedChunk>::try_from(pb::FeedChunk::from(Kernel(&chunk)))
                .unwrap()
                .0;
            assert_eq!(back, chunk);
        }

        let origin = FeedChunk::new(
            Vec::new(),
            cursor(0),
            polyc_state::stream::StreamEnd::Exhausted,
        );
        let back = Kernel::<FeedChunk>::try_from(pb::FeedChunk::from(Kernel(&origin)))
            .unwrap()
            .0;
        assert_eq!(back, origin);
    }

    #[test]
    fn a_chunk_that_does_not_say_why_it_stopped_is_malformed() {
        let mut encoded = pb::FeedChunk::from(Kernel(&FeedChunk::new(
            Vec::new(),
            cursor(0),
            polyc_state::stream::StreamEnd::Exhausted,
        )));
        encoded.end = pb::StreamEnd::STREAM_END_UNSPECIFIED.into();
        assert!(matches!(
            Kernel::<FeedChunk>::try_from(encoded).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "end"
        ));
    }

    #[test]
    fn a_snapshot_round_trips_and_refuses_an_identity_that_contradicts_itself() {
        let snapshot = FeedSnapshot::new(FeedAnchor::new(checkpoint(3, 9)), receipt());
        let encoded = pb::FeedSnapshot::from(Kernel(&snapshot));
        assert_eq!(encoded.snapshot, snapshot.id().as_str());
        let back = Kernel::<FeedSnapshot>::try_from(encoded.clone()).unwrap().0;
        assert_eq!(back, snapshot);

        let mut lying = encoded.clone();
        lying
            .checkpoint
            .as_option_mut()
            .expect("checkpoint")
            .feed_position = 4;
        assert!(matches!(
            Kernel::<FeedSnapshot>::try_from(lying).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "snapshot"
        ));

        let mut renamed = encoded;
        renamed
            .checkpoint
            .as_option_mut()
            .expect("checkpoint")
            .source
            .as_option_mut()
            .expect("source")
            .partition = "conv-2".to_owned();
        assert!(matches!(
            Kernel::<FeedSnapshot>::try_from(renamed).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "snapshot"
        ));
    }

    #[test]
    fn a_subscription_round_trips_its_partition_start_bound_and_consumer() {
        let declared = crate::DeclaredCall::bounded(
            crate::state_audience(),
            std::time::Duration::from_secs(1),
        );
        let request =
            SubscribeCommits::new(source(), FeedReadStart::Resume(Box::new(cursor(4))), 8)
                .on_behalf_of(ConsumerId::new("search"));
        let back = Kernel::<SubscriptionRequest>::try_from(pb::SubscribeCommitsRequest::from(
            Kernel((&declared, &request)),
        ))
        .unwrap()
        .into_inner();
        assert_eq!(back.subscription, request);
        assert!(back.context.as_option().is_some());

        let anonymous = SubscribeCommits::new(
            source(),
            FeedReadStart::Snapshot(SnapshotId::new("feed:test-snapshot")),
            8,
        );
        let encoded = pb::SubscribeCommitsRequest::from(Kernel((&declared, &anonymous)));
        assert!(encoded.consumer.is_none());
        let back = Kernel::<SubscriptionRequest>::try_from(encoded)
            .unwrap()
            .into_inner();
        assert_eq!(back.subscription, anonymous);
    }

    /// A subscription with no partition is not a subscription to everything.
    #[test]
    fn a_subscription_without_a_partition_or_a_start_is_malformed() {
        assert!(matches!(
            Kernel::<SubscriptionRequest>::try_from(pb::SubscribeCommitsRequest {
                context: buffa::MessageField::default(),
                source: buffa::MessageField::default(),
                start: buffa::MessageField::some(pb::FeedReadStart::from(Kernel(
                    &FeedReadStart::Resume(Box::new(cursor(0))),
                ))),
                max_chunk_commits: 4,
                consumer: None,
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            })
            .unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "source"
        ));
        assert!(matches!(
            Kernel::<SubscriptionRequest>::try_from(pb::SubscribeCommitsRequest {
                context: buffa::MessageField::default(),
                source: buffa::MessageField::some(pb::JournalSource::from(Kernel(&source()))),
                start: buffa::MessageField::default(),
                max_chunk_commits: 4,
                consumer: None,
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            })
            .unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "start"
        ));
    }

    #[test]
    fn a_projector_status_round_trips_including_its_eviction() {
        for policy in [ConsumerPolicy::Required, ConsumerPolicy::Optional] {
            let registration =
                ProjectorRegistration::new(ConsumerId::new("search"), source(), policy, 6);
            let live = ProjectorStatus::new(registration, cursor(2));
            for status in [live.clone(), live.evicted()] {
                let back =
                    Kernel::<ProjectorStatus>::try_from(pb::ProjectorStatus::from(Kernel(&status)))
                        .unwrap()
                        .0;
                assert_eq!(back, status);
            }
        }
    }

    /// An unset policy is refused. Defaulting either way is wrong, and both
    /// wrong answers are silent.
    #[test]
    fn a_registration_that_declares_no_policy_is_malformed() {
        let mut encoded = pb::ProjectorRegistration::from(Kernel(&ProjectorRegistration::new(
            ConsumerId::new("search"),
            source(),
            ConsumerPolicy::Required,
            6,
        )));
        encoded.policy = pb::ConsumerPolicy::CONSUMER_POLICY_UNSPECIFIED.into();
        assert!(matches!(
            Kernel::<ProjectorRegistration>::try_from(encoded).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "policy"
        ));
    }

    #[test]
    fn retention_round_trips_with_and_without_the_consumer_holding_it() {
        let bare = FeedRetention::new(source(), JournalPosition::new(2), JournalPosition::new(9));
        for retention in [
            bare.clone(),
            bare.clone().held_by(ConsumerId::new("search")),
            bare.clone().pinned_by(SnapshotId::new("feed:conv-1@2")),
            bare.held_by(ConsumerId::new("search"))
                .pinned_by(SnapshotId::new("feed:conv-1@2")),
        ] {
            let back =
                Kernel::<FeedRetention>::try_from(pb::FeedRetention::from(Kernel(&retention)))
                    .unwrap()
                    .0;
            assert_eq!(back, retention);
        }
    }

    /// Every compaction result carries the settlement a retry recovers.
    #[test]
    fn a_compaction_round_trips_with_its_required_receipt() {
        let retention =
            FeedRetention::new(source(), JournalPosition::new(4), JournalPosition::new(9));
        let held_back = FeedCompaction::new(retention.clone(), Vec::new(), receipt());
        let back = Kernel::<FeedCompaction>::try_from(pb::FeedCompaction::from(Kernel(&held_back)))
            .unwrap()
            .0;
        assert_eq!(back, held_back);

        let recorded = FeedCompaction::new(
            retention,
            vec![ConsumerId::new("search"), ConsumerId::new("audit")],
            receipt(),
        );
        let back = Kernel::<FeedCompaction>::try_from(pb::FeedCompaction::from(Kernel(&recorded)))
            .unwrap()
            .0;
        assert_eq!(back.evicted().len(), 2);
        assert_eq!(back.retention(), recorded.retention());

        let mut missing = pb::FeedCompaction::from(Kernel(&recorded));
        missing.receipt = buffa::MessageField::default();
        assert!(matches!(
            Kernel::<FeedCompaction>::try_from(missing).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "receipt"
        ));
    }
}