polyc-state-connect 2026.8.3

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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
//! The mapping between the kernel's vocabulary and its wire encoding.
//!
//! Every conversion here is an explicit `From` or `TryFrom` that names each
//! field. A struct-update spread would silently zero a field one side gained
//! instead of failing to compile, which is exactly the defect class the
//! control-plane wire hit before this rule existed.
//!
//! Both sides of every conversion are foreign to this crate — the kernel types
//! belong to `polyc_state`, the generated types to `polyc_proto` — so the
//! orphan rule forbids writing the impls directly. [`Kernel`] is the local
//! wrapper that makes them legal. It adds nothing but permission: the
//! conversions are the same exhaustive, field-by-field ones the convention
//! calls for.
//!
//! Direction decides fallibility. Kernel to wire is infallible: the kernel's
//! types are already valid. Wire to kernel is not — a peer may send a digest
//! of the wrong length, an enum this build does not know, or a `oneof` with
//! nothing set — so every reverse conversion returns
//! [`StateError::Malformed`] naming the field it could not interpret.

use std::time::Duration;

use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    cancel::CancellationToken,
    command::{
        CommandEnvelope, CommandMetadata, CommandScope, FencingToken, ObservedState, Precondition,
        ResourceBounds,
    },
    conformance::{SyntheticCommand, SyntheticOp, SyntheticRecord, family},
    consistency::{Consistency, Watermark},
    context::CallContext,
    digest::ContentDigest,
    error::StateError,
    id::{
        AggregateId, Audience, CommandId, NamespaceId, OperationFamily, PartitionId, Purpose,
        SnapshotId,
    },
    page::{Cursor, Page, PageCompleteness, PageRequest, Positioned, ReadStart},
    receipt::{CommitDisposition, CommitEvidence, Receipt},
    revision::{CommitRoot, JournalPosition, Revision},
    stream::{
        Backpressure, CompactedRange, Delivery, StreamChunk, StreamContract, StreamEnd,
        StreamRequest,
    },
};

/// A kernel value on one side of a wire conversion.
///
/// A wrapper with no behavior of its own. It exists because the orphan rule
/// needs a type local to this crate to appear in every `impl`, and neither the
/// kernel's types nor the generated ones are. Read `Kernel(x)` as "x, about to
/// cross the wire" or "x, just arrived".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Kernel<T>(pub T);

impl<T> Kernel<T> {
    /// Returns the value the wrapper carries.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

/// Returns a cancellation signal already raised when `withdrawn`.
///
/// The kernel models withdrawal as a signal a caller raises, so a call that
/// arrives declaring the caller has already withdrawn is given a token in
/// exactly that state rather than a fresh, live one.
fn cancelled_token(withdrawn: bool) -> CancellationToken {
    let token = CancellationToken::new();
    if withdrawn {
        token.cancel();
    }
    token
}

/// Builds the malformed outcome for a field this side could not interpret.
pub(crate) fn malformed(field: &str, reason: impl Into<String>) -> StateError {
    StateError::Malformed {
        field: field.to_owned(),
        reason: reason.into(),
    }
}

/// Reads a fixed-width digest or root out of the bytes a peer sent.
pub(crate) fn fixed_bytes<const N: usize>(
    field: &str,
    bytes: &[u8],
) -> Result<[u8; N], StateError> {
    <[u8; N]>::try_from(bytes).map_err(|_| {
        malformed(
            field,
            format!("expected {N} bytes, received {}", bytes.len()),
        )
    })
}

/// Reads a message field a peer was required to set.
///
/// Named over `P: buffa::ProtoBox<T>` rather than the simpler-looking
/// `impl Into<Option<T>>` on purpose: `T` is itself generic here (every
/// caller instantiates it differently), and rustc's inference cannot carry
/// an `impl Into<Option<T>>` bound backward through the `?` in
/// `Kernel::<X>::try_from(required(...)?)` call sites to pin `T` — it falls
/// back to `!` and the call fails to type-check. Naming the concrete
/// `MessageField<T, P>` parameter type sidesteps that: `T` is then read
/// directly off the argument, not inferred through a trait bound. Functions
/// where `T` is fixed by the signature (`admit`, `receipt`, `declared_call`,
/// and friends) don't hit this and use `impl Into<Option<T>>` instead.
pub(crate) fn required<T: Default, P: buffa::ProtoBox<T>>(
    field: &str,
    reason: &str,
    value: buffa::MessageField<T, P>,
) -> Result<T, StateError> {
    value
        .into_option()
        .ok_or_else(|| malformed(field, reason.to_owned()))
}

// ---------------------------------------------------------------------------
// Enumerations
// ---------------------------------------------------------------------------

/// Reads a known enum value, refusing one this build does not recognize.
///
/// A peer that sends a value from a newer protocol is an incompatible peer,
/// and the design has it refuse the operation rather than guess at a shape it
/// does not know.
pub(crate) fn known<E: buffa::Enumeration>(
    field: &str,
    value: buffa::EnumValue<E>,
) -> Result<E, StateError> {
    value.as_known().ok_or_else(|| {
        malformed(
            field,
            format!("this build does not know value {}", value.to_i32()),
        )
    })
}

impl From<Kernel<Consistency>> for pb::Consistency {
    fn from(value: Kernel<Consistency>) -> Self {
        match value.0 {
            Consistency::LinearizableCurrent => Self::CONSISTENCY_LINEARIZABLE_CURRENT,
            Consistency::RevisionBound => Self::CONSISTENCY_REVISION_BOUND,
            Consistency::SnapshotConsistent => Self::CONSISTENCY_SNAPSHOT_CONSISTENT,
            Consistency::OrderedPerAggregate => Self::CONSISTENCY_ORDERED_PER_AGGREGATE,
            Consistency::EventualWithWatermark => Self::CONSISTENCY_EVENTUAL_WITH_WATERMARK,
            Consistency::ExplicitlyEphemeral => Self::CONSISTENCY_EXPLICITLY_EPHEMERAL,
        }
    }
}

/// Reads a consistency class off the wire.
pub(crate) fn consistency(
    field: &str,
    value: buffa::EnumValue<pb::Consistency>,
) -> Result<Consistency, StateError> {
    match known(field, value)? {
        pb::Consistency::CONSISTENCY_LINEARIZABLE_CURRENT => Ok(Consistency::LinearizableCurrent),
        pb::Consistency::CONSISTENCY_REVISION_BOUND => Ok(Consistency::RevisionBound),
        pb::Consistency::CONSISTENCY_SNAPSHOT_CONSISTENT => Ok(Consistency::SnapshotConsistent),
        pb::Consistency::CONSISTENCY_ORDERED_PER_AGGREGATE => Ok(Consistency::OrderedPerAggregate),
        pb::Consistency::CONSISTENCY_EVENTUAL_WITH_WATERMARK => {
            Ok(Consistency::EventualWithWatermark)
        }
        pb::Consistency::CONSISTENCY_EXPLICITLY_EPHEMERAL => Ok(Consistency::ExplicitlyEphemeral),
        pb::Consistency::CONSISTENCY_UNSPECIFIED => Err(malformed(
            field,
            "an operation declares its consistency class",
        )),
    }
}

impl From<Kernel<CommitDisposition>> for pb::CommitDisposition {
    fn from(value: Kernel<CommitDisposition>) -> Self {
        match value.0 {
            CommitDisposition::New => Self::COMMIT_DISPOSITION_NEW,
            CommitDisposition::Deduplicated => Self::COMMIT_DISPOSITION_DEDUPLICATED,
        }
    }
}

/// Reads a commit disposition off the wire.
fn disposition(
    field: &str,
    value: buffa::EnumValue<pb::CommitDisposition>,
) -> Result<CommitDisposition, StateError> {
    match known(field, value)? {
        pb::CommitDisposition::COMMIT_DISPOSITION_NEW => Ok(CommitDisposition::New),
        pb::CommitDisposition::COMMIT_DISPOSITION_DEDUPLICATED => {
            Ok(CommitDisposition::Deduplicated)
        }
        pb::CommitDisposition::COMMIT_DISPOSITION_UNSPECIFIED => Err(malformed(
            field,
            "a receipt reports whether it committed or replayed",
        )),
    }
}

impl From<Kernel<PageCompleteness>> for pb::PageCompleteness {
    fn from(value: Kernel<PageCompleteness>) -> Self {
        match value.0 {
            PageCompleteness::Complete => Self::PAGE_COMPLETENESS_COMPLETE,
            PageCompleteness::Truncated => Self::PAGE_COMPLETENESS_TRUNCATED,
        }
    }
}

/// Reads a page's completeness off the wire.
pub(crate) fn completeness(
    field: &str,
    value: buffa::EnumValue<pb::PageCompleteness>,
) -> Result<PageCompleteness, StateError> {
    match known(field, value)? {
        pb::PageCompleteness::PAGE_COMPLETENESS_COMPLETE => Ok(PageCompleteness::Complete),
        pb::PageCompleteness::PAGE_COMPLETENESS_TRUNCATED => Ok(PageCompleteness::Truncated),
        pb::PageCompleteness::PAGE_COMPLETENESS_UNSPECIFIED => Err(malformed(
            field,
            "a page reports whether records remain after it",
        )),
    }
}

impl From<Kernel<StreamEnd>> for pb::StreamEnd {
    fn from(value: Kernel<StreamEnd>) -> Self {
        match value.0 {
            StreamEnd::More => Self::STREAM_END_MORE,
            StreamEnd::Exhausted => Self::STREAM_END_EXHAUSTED,
            StreamEnd::Drained => Self::STREAM_END_DRAINED,
        }
    }
}

/// Reads why a chunk stopped off the wire.
pub(crate) fn stream_end(
    field: &str,
    value: buffa::EnumValue<pb::StreamEnd>,
) -> Result<StreamEnd, StateError> {
    match known(field, value)? {
        pb::StreamEnd::STREAM_END_MORE => Ok(StreamEnd::More),
        pb::StreamEnd::STREAM_END_EXHAUSTED => Ok(StreamEnd::Exhausted),
        pb::StreamEnd::STREAM_END_DRAINED => Ok(StreamEnd::Drained),
        pb::StreamEnd::STREAM_END_UNSPECIFIED => {
            Err(malformed(field, "a chunk reports why it stopped"))
        }
    }
}

impl From<Kernel<Delivery>> for pb::Delivery {
    fn from(value: Kernel<Delivery>) -> Self {
        match value.0 {
            Delivery::AtLeastOnce => Self::DELIVERY_AT_LEAST_ONCE,
            Delivery::AtMostOnce => Self::DELIVERY_AT_MOST_ONCE,
        }
    }
}

/// Reads a delivery guarantee off the wire.
fn delivery(field: &str, value: buffa::EnumValue<pb::Delivery>) -> Result<Delivery, StateError> {
    match known(field, value)? {
        pb::Delivery::DELIVERY_AT_LEAST_ONCE => Ok(Delivery::AtLeastOnce),
        pb::Delivery::DELIVERY_AT_MOST_ONCE => Ok(Delivery::AtMostOnce),
        pb::Delivery::DELIVERY_UNSPECIFIED => {
            Err(malformed(field, "a stream declares its delivery guarantee"))
        }
    }
}

impl From<Kernel<CompactedRange>> for pb::CompactedRange {
    fn from(value: Kernel<CompactedRange>) -> Self {
        match value.0 {
            CompactedRange::NeverCompacted => Self::COMPACTED_RANGE_NEVER_COMPACTED,
            CompactedRange::FailsOnCompactedCursor => {
                Self::COMPACTED_RANGE_FAILS_ON_COMPACTED_CURSOR
            }
        }
    }
}

/// Reads a compaction behavior off the wire.
fn compacted_range(
    field: &str,
    value: buffa::EnumValue<pb::CompactedRange>,
) -> Result<CompactedRange, StateError> {
    match known(field, value)? {
        pb::CompactedRange::COMPACTED_RANGE_NEVER_COMPACTED => Ok(CompactedRange::NeverCompacted),
        pb::CompactedRange::COMPACTED_RANGE_FAILS_ON_COMPACTED_CURSOR => {
            Ok(CompactedRange::FailsOnCompactedCursor)
        }
        pb::CompactedRange::COMPACTED_RANGE_UNSPECIFIED => Err(malformed(
            field,
            "a stream declares what a compacted cursor does",
        )),
    }
}

impl From<Kernel<Backpressure>> for pb::Backpressure {
    fn from(value: Kernel<Backpressure>) -> Self {
        match value.0 {
            Backpressure::BlockProducer => Self::BACKPRESSURE_BLOCK_PRODUCER,
            Backpressure::ShedSlowConsumer => Self::BACKPRESSURE_SHED_SLOW_CONSUMER,
        }
    }
}

/// Reads a backpressure policy off the wire.
fn backpressure(
    field: &str,
    value: buffa::EnumValue<pb::Backpressure>,
) -> Result<Backpressure, StateError> {
    match known(field, value)? {
        pb::Backpressure::BACKPRESSURE_BLOCK_PRODUCER => Ok(Backpressure::BlockProducer),
        pb::Backpressure::BACKPRESSURE_SHED_SLOW_CONSUMER => Ok(Backpressure::ShedSlowConsumer),
        pb::Backpressure::BACKPRESSURE_UNSPECIFIED => Err(malformed(
            field,
            "a stream declares what it does with a slow consumer",
        )),
    }
}

// ---------------------------------------------------------------------------
// Per-call admission and budget
// ---------------------------------------------------------------------------

/// The version of the semantics carried by protobuf `CallContext` field 1.
///
/// This is deliberately not [`polyc_state::id::ProtocolVersion`]. That version
/// is persisted with commands and validated during durable replay. Changing it
/// would make State refuse its existing log. Call-context semantics are a
/// transport contract and advance independently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CallContextVersion(u32);

impl CallContextVersion {
    /// Duration-budget semantics for `deadline_nanos`.
    pub const CURRENT: Self = Self(2);

    /// Wraps `version` as a call-context semantics version.
    #[must_use]
    pub const fn new(version: u32) -> Self {
        Self(version)
    }

    /// Returns the numeric wire version.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0
    }
}

impl std::fmt::Display for CallContextVersion {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "v{}", self.0)
    }
}

/// What one call declared about itself, read off the wire.
///
/// The shell checks [`Self::version`] and [`Self::audience`] at the
/// transport boundary, then spends the rest as the kernel's budget.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclaredCall {
    /// The call-context semantics version the caller speaks.
    pub version: CallContextVersion,
    /// The audience the caller is asking on behalf of.
    pub audience: Audience,
    /// The remaining end-to-end budget, independent of any process's clock.
    pub budget: Duration,
    /// Whether the caller has already withdrawn interest.
    pub cancelled: bool,
}

impl DeclaredCall {
    /// Declares one call with a finite end-to-end budget.
    ///
    /// State deadlines use the authority module's monotonic timeline, whose
    /// origin is not transferable across processes. The wire therefore carries
    /// the remaining duration from that origin, while the client transport
    /// derives its relative timeout from this same value. A caller with a
    /// larger parent budget passes only what remains; a retry must not mint a
    /// fresh parent budget.
    #[must_use]
    pub const fn bounded(audience: Audience, remaining: Duration) -> Self {
        Self::live(audience, remaining)
    }

    /// Declares a live call of the current wire-semantics version.
    #[must_use]
    pub const fn live(audience: Audience, budget: Duration) -> Self {
        Self {
            version: CallContextVersion::CURRENT,
            audience,
            budget,
            cancelled: false,
        }
    }

    /// Returns the same declaration from a caller that has withdrawn.
    #[must_use]
    pub const fn withdrawn(mut self) -> Self {
        self.cancelled = true;
        self
    }

    /// Returns the kernel budget this call runs under.
    ///
    /// The cancellation signal is raised up front when the caller declared it
    /// had already withdrawn, so the module sees the same withdrawal the
    /// caller sees rather than a fresh, live token.
    #[must_use]
    pub fn origin_relative_context(&self) -> CallContext {
        CallContext::from_origin_relative_budget(self.budget, cancelled_token(self.cancelled))
    }

    /// Returns the relative budget carried to the authority.
    ///
    /// This is also the only value a unary client's Connect timeout may use,
    /// so the message body and the live request cannot disagree about how long
    /// the call has left.
    #[must_use]
    pub const fn remaining_budget(&self) -> Duration {
        self.budget
    }
}

impl From<Kernel<&DeclaredCall>> for pb::CallContext {
    fn from(value: Kernel<&DeclaredCall>) -> Self {
        let call = value.0;
        Self {
            protocol_version: call.version.get(),
            audience: call.audience.as_str().to_owned(),
            deadline_nanos: nanos_from_duration(call.budget),
            cancelled: call.cancelled,
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl From<pb::CallContext> for Kernel<DeclaredCall> {
    fn from(value: pb::CallContext) -> Self {
        Self(DeclaredCall {
            version: CallContextVersion::new(value.protocol_version),
            audience: Audience::new(value.audience),
            budget: duration_from_nanos(value.deadline_nanos),
            cancelled: value.cancelled,
        })
    }
}

/// Reads the call context a request carries, refusing one that omits it.
///
/// # Errors
///
/// Returns [`StateError::Malformed`] when the field is absent — a call with no
/// declared version, audience, or budget is one nothing could be checked
/// against.
pub fn declared_call(
    context: impl Into<Option<pb::CallContext>>,
) -> Result<DeclaredCall, StateError> {
    let message = context.into().ok_or_else(|| {
        malformed(
            "context",
            "every call declares its version, audience, and budget",
        )
    })?;
    Ok(Kernel::<DeclaredCall>::from(message).into_inner())
}

// ---------------------------------------------------------------------------
// Preconditions and observed state
// ---------------------------------------------------------------------------

impl From<Kernel<Precondition>> for pb::Precondition {
    fn from(value: Kernel<Precondition>) -> Self {
        use pb::__buffa::oneof::precondition::Kind;
        let kind = match value.0 {
            Precondition::Unconditional => Kind::from(pb::Unconditional::default()),
            Precondition::NoExistingState => Kind::from(pb::NoExistingState::default()),
            Precondition::Revision(revision) => Kind::Revision(revision.get()),
            Precondition::JournalHead(position) => Kind::JournalHead(position.get()),
        };
        Self {
            kind: Some(kind),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads what durable state a command requires before it commits.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `precondition` when the sender
    /// set no variant, so the command requires nothing this side can check.
    fn try_from(value: pb::Precondition) -> Result<Self, Self::Error> {
        use pb::__buffa::oneof::precondition::Kind;
        let precondition = match value.kind {
            Some(Kind::Unconditional(_)) => Precondition::Unconditional,
            Some(Kind::NoExistingState(_)) => Precondition::NoExistingState,
            Some(Kind::Revision(revision)) => Precondition::Revision(Revision::new(revision)),
            Some(Kind::JournalHead(position)) => {
                Precondition::JournalHead(JournalPosition::new(position))
            }
            None => {
                return Err(malformed(
                    "precondition",
                    "a precondition names what durable state the command requires",
                ));
            }
        };
        Ok(Self(precondition))
    }
}

impl From<Kernel<ObservedState>> for pb::ObservedState {
    fn from(value: Kernel<ObservedState>) -> Self {
        use pb::__buffa::oneof::observed_state::Kind;
        let kind = match value.0 {
            ObservedState::Absent => Kind::from(pb::AbsentState::default()),
            ObservedState::Revision(revision) => Kind::Revision(revision.get()),
            ObservedState::JournalHead(position) => Kind::JournalHead(position.get()),
        };
        Self {
            kind: Some(kind),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads the durable state a conflict was checked against.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `observed` when the sender set
    /// no variant.
    fn try_from(value: pb::ObservedState) -> Result<Self, Self::Error> {
        use pb::__buffa::oneof::observed_state::Kind;
        let observed = match value.kind {
            Some(Kind::Absent(_)) => ObservedState::Absent,
            Some(Kind::Revision(revision)) => ObservedState::Revision(Revision::new(revision)),
            Some(Kind::JournalHead(position)) => {
                ObservedState::JournalHead(JournalPosition::new(position))
            }
            None => {
                return Err(malformed(
                    "observed",
                    "a conflict names the durable state it was checked against",
                ));
            }
        };
        Ok(Self(observed))
    }
}

// ---------------------------------------------------------------------------
// Receipts
// ---------------------------------------------------------------------------

impl From<Kernel<&Cursor>> for pb::Cursor {
    fn from(value: Kernel<&Cursor>) -> Self {
        Self {
            position: value.0.position().get(),
            snapshot: value
                .0
                .snapshot()
                .map(|snapshot| snapshot.as_str().to_owned()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl From<pb::Cursor> for Kernel<Cursor> {
    fn from(value: pb::Cursor) -> Self {
        let position = JournalPosition::new(value.position);
        Self(value.snapshot.map_or_else(
            || Cursor::at(position),
            |snapshot| Cursor::in_snapshot(SnapshotId::new(snapshot), position),
        ))
    }
}

impl From<Kernel<&CommitEvidence>> for pb::CommitEvidence {
    fn from(value: Kernel<&CommitEvidence>) -> Self {
        let evidence = value.0;
        Self {
            revision: evidence.revision().map(Revision::get),
            position: evidence.position().map(JournalPosition::get),
            root: evidence.root().map(|root| root.as_bytes().to_vec()),
            snapshot: evidence
                .snapshot()
                .map(|snapshot| snapshot.as_str().to_owned()),
            cursor: evidence
                .cursor()
                .map_or_else(buffa::MessageField::default, |cursor| {
                    buffa::MessageField::some(pb::Cursor::from(Kernel(cursor)))
                }),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads what a commit produced. Every field is optional: an operation
    /// family carries whichever of them it defines.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `root` when a committed root
    /// is present but is not [`CommitRoot::LEN`] bytes.
    fn try_from(value: pb::CommitEvidence) -> Result<Self, Self::Error> {
        let mut evidence = CommitEvidence::new();
        if let Some(revision) = value.revision {
            evidence = evidence.with_revision(Revision::new(revision));
        }
        if let Some(position) = value.position {
            evidence = evidence.with_position(JournalPosition::new(position));
        }
        if let Some(root) = value.root {
            let bytes = fixed_bytes::<{ CommitRoot::LEN }>("root", &root)?;
            evidence = evidence.with_root(CommitRoot::from_bytes(bytes));
        }
        if let Some(snapshot) = value.snapshot {
            evidence = evidence.with_snapshot(SnapshotId::new(snapshot));
        }
        if let Some(cursor) = value.cursor.into_option() {
            evidence = evidence.with_cursor(Kernel::<Cursor>::from(cursor).into_inner());
        }
        Ok(Self(evidence))
    }
}

impl From<Kernel<&Receipt>> for pb::Receipt {
    fn from(value: Kernel<&Receipt>) -> Self {
        let receipt = value.0;
        Self {
            command_id: receipt.command_id().as_str().to_owned(),
            family: receipt.family().as_str().to_owned(),
            digest: receipt.digest().as_bytes().to_vec(),
            disposition: pb::CommitDisposition::from(Kernel(receipt.disposition())).into(),
            evidence: buffa::MessageField::some(pb::CommitEvidence::from(Kernel(
                receipt.evidence(),
            ))),
            consistency: pb::Consistency::from(Kernel(receipt.consistency())).into(),
            fence: receipt.fence().map(FencingToken::get),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Rebuilds the durable outcome the module recorded.
    ///
    /// The kernel's only receipt constructor takes a command, because a
    /// receipt is minted from what committed and is never assembled field by
    /// field out of a wire response (INV-22). This respects that: it rebuilds
    /// exactly the four things [`Receipt::committed`] copies out of a command
    /// — identity, family, digest, and fence — and lets the constructor do the
    /// copying. The scope and envelope the constructor never reads are the
    /// synthetic family's own declared constants, so no value is invented.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `disposition`, `consistency`,
    /// `evidence`, or `digest` — whichever the sender left unset, named a
    /// value this build does not know, or sized wrong.
    fn try_from(value: pb::Receipt) -> Result<Self, Self::Error> {
        let disposition = disposition("disposition", value.disposition)?;
        let consistency = consistency("consistency", value.consistency)?;
        let evidence = Kernel::<CommitEvidence>::try_from(required(
            "evidence",
            "a receipt carries what its commit produced",
            value.evidence,
        )?)?
        .into_inner();
        let digest = ContentDigest::from_bytes(fixed_bytes::<{ ContentDigest::LEN }>(
            "digest",
            &value.digest,
        )?);

        let mut metadata = CommandMetadata::new(
            CommandId::new(value.command_id),
            OperationFamily::new(value.family),
            digest,
            CommandScope::new(
                AggregateId::new(family::AGGREGATE),
                PartitionId::new(family::AGGREGATE),
                NamespaceId::new(family::NAMESPACE),
            ),
            CommandEnvelope::new(
                Purpose::new(family::PURPOSE),
                Audience::new(family::AUDIENCE),
                ResourceBounds::new(family::MAX_PAYLOAD_BYTES, family::MAX_RECORDS_PER_COMMAND),
            ),
        );
        if let Some(fence) = value.fence {
            metadata = metadata.with_fence(FencingToken::new(fence));
        }

        let receipt = Receipt::committed(&metadata, evidence, consistency);
        Ok(Self(match disposition {
            CommitDisposition::New => receipt,
            CommitDisposition::Deduplicated => receipt.as_replay(),
        }))
    }
}

// ---------------------------------------------------------------------------
// Bounded reads and durable streams
// ---------------------------------------------------------------------------

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

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

    /// Reads where a bounded read or stream begins.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `start` when the sender named
    /// neither a snapshot nor a resume cursor.
    fn try_from(value: pb::ReadStart) -> Result<Self, Self::Error> {
        use pb::__buffa::oneof::read_start::Start;
        let start = match value.start {
            Some(Start::Snapshot(snapshot)) => ReadStart::Snapshot(SnapshotId::new(snapshot)),
            Some(Start::Resume(cursor)) => {
                ReadStart::Resume(Kernel::<Cursor>::from(*cursor).into_inner())
            }
            None => return Err(malformed("start", "a bounded read names where it begins")),
        };
        Ok(Self(start))
    }
}

impl From<Kernel<&PageRequest>> for pb::PageRequest {
    fn from(value: Kernel<&PageRequest>) -> Self {
        Self {
            start: buffa::MessageField::some(pb::ReadStart::from(Kernel(value.0.start()))),
            limit: value.0.limit(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads a request for one bounded page.
    ///
    /// The limit is not checked here: the bound belongs to the operation
    /// family, and exceeding it is a typed [`StateError::BoundsExceeded`]
    /// outcome from the module rather than a decoding failure.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `start` when the request omits
    /// where it begins.
    fn try_from(value: pb::PageRequest) -> Result<Self, Self::Error> {
        let start = Kernel::<ReadStart>::try_from(required(
            "start",
            "a bounded read names where it begins",
            value.start,
        )?)?
        .into_inner();
        Ok(Self(PageRequest::new(start, value.limit)))
    }
}

impl From<Kernel<&StreamRequest>> for pb::StreamRequest {
    fn from(value: Kernel<&StreamRequest>) -> Self {
        Self {
            start: buffa::MessageField::some(pb::ReadStart::from(Kernel(value.0.start()))),
            max_chunk_records: value.0.max_chunk_records(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads a request for one bounded stream chunk.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `start` when the request omits
    /// where it begins.
    fn try_from(value: pb::StreamRequest) -> Result<Self, Self::Error> {
        let start = Kernel::<ReadStart>::try_from(required(
            "start",
            "a bounded read names where it begins",
            value.start,
        )?)?
        .into_inner();
        Ok(Self(StreamRequest::new(start, value.max_chunk_records)))
    }
}

impl From<Kernel<&SyntheticRecord>> for pb::SyntheticRecord {
    fn from(value: Kernel<&SyntheticRecord>) -> Self {
        Self {
            position: value.0.position().get(),
            command_id: value.0.command_id().as_str().to_owned(),
            amount: value.0.amount(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

impl From<pb::SyntheticRecord> for Kernel<SyntheticRecord> {
    fn from(value: pb::SyntheticRecord) -> Self {
        Self(SyntheticRecord::new(
            JournalPosition::new(value.position),
            CommandId::new(value.command_id),
            value.amount,
        ))
    }
}

impl From<Kernel<&Page<SyntheticRecord>>> for pb::Page {
    fn from(value: Kernel<&Page<SyntheticRecord>>) -> Self {
        let page = value.0;
        Self {
            records: page
                .records()
                .iter()
                .map(|record| pb::SyntheticRecord::from(Kernel(record)))
                .collect(),
            next: page
                .next_cursor()
                .map_or_else(buffa::MessageField::default, |cursor| {
                    buffa::MessageField::some(pb::Cursor::from(Kernel(cursor)))
                }),
            completeness: pb::PageCompleteness::from(Kernel(page.completeness())).into(),
            consistency: pb::Consistency::from(Kernel(page.consistency())).into(),
            watermark: page.watermark().map(Watermark::get),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads one bounded page of records.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `completeness` or
    /// `consistency` when either is unset or names a value this build does not
    /// know — a page that declares neither says nothing about what it omitted.
    fn try_from(value: pb::Page) -> Result<Self, Self::Error> {
        let completeness = completeness("completeness", value.completeness)?;
        let consistency = consistency("consistency", value.consistency)?;
        let records = value
            .records
            .into_iter()
            .map(|record| Kernel::<SyntheticRecord>::from(record).into_inner())
            .collect();
        let next = value
            .next
            .into_option()
            .map(|cursor| Kernel::<Cursor>::from(cursor).into_inner());
        let page = Page::new(records, next, completeness, consistency);
        Ok(Self(match value.watermark {
            Some(watermark) => page.with_watermark(Watermark::new(watermark)),
            None => page,
        }))
    }
}

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

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

    /// Reads one bounded chunk of a durable stream.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `end` when the chunk does not
    /// say why it stopped, which is what distinguishes a drain from
    /// exhaustion.
    fn try_from(value: pb::StreamChunk) -> Result<Self, Self::Error> {
        let end = stream_end("end", value.end)?;
        let records = value
            .records
            .into_iter()
            .map(|record| Kernel::<SyntheticRecord>::from(record).into_inner())
            .collect();
        let next = value
            .next
            .into_option()
            .map(|cursor| Kernel::<Cursor>::from(cursor).into_inner());
        Ok(Self(StreamChunk::new(records, next, end)))
    }
}

impl From<Kernel<StreamContract>> for pb::StreamContract {
    fn from(value: Kernel<StreamContract>) -> Self {
        let contract = value.0;
        Self {
            consistency: pb::Consistency::from(Kernel(contract.consistency())).into(),
            delivery: pb::Delivery::from(Kernel(contract.delivery())).into(),
            max_chunk_records: contract.max_chunk_records(),
            compacted_range: pb::CompactedRange::from(Kernel(contract.compacted_range())).into(),
            backpressure: pb::Backpressure::from(Kernel(contract.backpressure())).into(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

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

    /// Reads the contract a durable stream declares.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `consistency`, `delivery`,
    /// `compacted_range`, or `backpressure` — whichever the sender left unset
    /// or named a value this build does not know.
    fn try_from(value: pb::StreamContract) -> Result<Self, Self::Error> {
        Ok(Self(StreamContract::new(
            consistency("consistency", value.consistency)?,
            delivery("delivery", value.delivery)?,
            value.max_chunk_records,
            compacted_range("compacted_range", value.compacted_range)?,
            backpressure("backpressure", value.backpressure)?,
        )))
    }
}

// ---------------------------------------------------------------------------
// The conformance kit's synthetic family
// ---------------------------------------------------------------------------

impl From<Kernel<SyntheticOp>> for pb::SyntheticOp {
    fn from(value: Kernel<SyntheticOp>) -> Self {
        use pb::__buffa::oneof::synthetic_op::Kind;
        let unknown = buffa::UnknownFields::default;
        let kind = match value.0 {
            SyntheticOp::Append { amount } => Kind::from(pb::SyntheticAppend {
                amount,
                __buffa_unknown_fields: unknown(),
            }),
            SyntheticOp::Oversized {
                amount,
                payload_bytes,
            } => Kind::from(pb::SyntheticOversized {
                amount,
                payload_bytes,
                __buffa_unknown_fields: unknown(),
            }),
            SyntheticOp::AppendThenLoseResponse { amount } => {
                Kind::from(pb::SyntheticAppendThenLoseResponse {
                    amount,
                    __buffa_unknown_fields: unknown(),
                })
            }
            SyntheticOp::AppendThenObserveCancellation { amount } => {
                Kind::from(pb::SyntheticAppendThenObserveCancellation {
                    amount,
                    __buffa_unknown_fields: unknown(),
                })
            }
        };
        Self {
            kind: Some(kind),
            __buffa_unknown_fields: unknown(),
        }
    }
}

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

    /// Reads what a synthetic command asks the module to do.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `op` when the sender set no
    /// variant.
    fn try_from(value: pb::SyntheticOp) -> Result<Self, Self::Error> {
        use pb::__buffa::oneof::synthetic_op::Kind;
        let op = match value.kind {
            Some(Kind::Append(op)) => SyntheticOp::Append { amount: op.amount },
            Some(Kind::Oversized(op)) => SyntheticOp::Oversized {
                amount: op.amount,
                payload_bytes: op.payload_bytes,
            },
            Some(Kind::AppendThenLoseResponse(op)) => {
                SyntheticOp::AppendThenLoseResponse { amount: op.amount }
            }
            Some(Kind::AppendThenObserveCancellation(op)) => {
                SyntheticOp::AppendThenObserveCancellation { amount: op.amount }
            }
            None => {
                return Err(malformed(
                    "op",
                    "a command names what it asks the module to do",
                ));
            }
        };
        Ok(Self(op))
    }
}

impl From<Kernel<&SyntheticCommand>> for pb::SyntheticCommand {
    fn from(value: Kernel<&SyntheticCommand>) -> Self {
        let metadata = value.0.metadata();
        Self {
            command_id: metadata.command_id().as_str().to_owned(),
            op: buffa::MessageField::some(pb::SyntheticOp::from(Kernel(value.0.op()))),
            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::SyntheticCommand> for Kernel<SyntheticCommand> {
    type Error = StateError;

    /// Reads one command of the synthetic family.
    ///
    /// The digest is derived from the operation rather than read off the wire,
    /// so a command always carries the digest its own content produces.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::Malformed`] naming `op` or `precondition` when
    /// either is absent, and whatever those conversions themselves report.
    fn try_from(value: pb::SyntheticCommand) -> Result<Self, Self::Error> {
        let op = Kernel::<SyntheticOp>::try_from(required(
            "op",
            "a command names what it asks the module to do",
            value.op,
        )?)?
        .into_inner();
        let precondition = Kernel::<Precondition>::try_from(required(
            "precondition",
            "a precondition names what durable state the command requires",
            value.precondition,
        )?)?
        .into_inner();

        let mut command =
            SyntheticCommand::new(value.command_id.as_str(), op).with_precondition(precondition);
        if let Some(fence) = value.fence {
            command = command.with_fence(FencingToken::new(fence));
        }
        Ok(Self(command))
    }
}

/// Returns the duration `nanos` names.
#[must_use]
pub const fn duration_from_nanos(nanos: u64) -> Duration {
    Duration::from_nanos(nanos)
}

/// Returns the whole nanoseconds `budget` names, saturating at [`u64::MAX`].
#[must_use]
pub fn nanos_from_duration(budget: Duration) -> u64 {
    u64::try_from(budget.as_nanos()).unwrap_or(u64::MAX)
}

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

    use super::*;
    use polyc_state::{conformance::ConformanceAdapter, memory::MemoryState};

    fn live() -> DeclaredCall {
        DeclaredCall::live(Audience::new(family::AUDIENCE), Duration::from_secs(30))
    }

    #[test]
    fn a_call_context_round_trips() {
        let declared = live();
        let wire = pb::CallContext::from(Kernel(&declared));
        assert_eq!(
            wire.protocol_version, 2,
            "CallContext field 1 versions wire semantics independently of persisted commands"
        );
        assert_eq!(Kernel::<DeclaredCall>::from(wire).into_inner(), declared);
        assert!(!declared.origin_relative_context().is_cancelled());
    }

    #[test]
    fn a_withdrawn_call_arrives_withdrawn() {
        let declared = live().withdrawn();
        let wire = pb::CallContext::from(Kernel(&declared));
        assert!(wire.cancelled);
        assert!(declared.origin_relative_context().is_cancelled());
    }

    #[test]
    fn a_command_round_trips_with_its_derived_digest() {
        let command = SyntheticCommand::new(
            "cmd-1",
            SyntheticOp::Oversized {
                amount: 3,
                payload_bytes: 99,
            },
        )
        .with_precondition(Precondition::Revision(Revision::new(4)))
        .with_fence(FencingToken::new(7));
        let back =
            Kernel::<SyntheticCommand>::try_from(pb::SyntheticCommand::from(Kernel(&command)))
                .unwrap()
                .into_inner();
        assert_eq!(back, command);
        assert_eq!(back.metadata().digest(), command.metadata().digest());
    }

    #[test]
    fn a_receipt_round_trips_field_for_field() {
        let mut state = MemoryState::new();
        let declared = live();
        let receipt = state
            .submit(
                SyntheticCommand::new("cmd-1", SyntheticOp::Append { amount: 2 })
                    .with_fence(FencingToken::new(3)),
                &declared.origin_relative_context(),
            )
            .unwrap();
        let back = Kernel::<Receipt>::try_from(pb::Receipt::from(Kernel(&receipt)))
            .unwrap()
            .into_inner();
        assert_eq!(back, receipt);

        let replay = receipt.as_replay();
        let back_replay = Kernel::<Receipt>::try_from(pb::Receipt::from(Kernel(&replay)))
            .unwrap()
            .into_inner();
        assert_eq!(back_replay, replay);
        assert!(back_replay.is_deduplicated());
    }

    #[test]
    fn a_page_and_a_chunk_round_trip() {
        let mut state = MemoryState::new();
        let declared = live();
        for amount in 1..=3_u64 {
            state
                .submit(
                    SyntheticCommand::new(&format!("cmd-{amount}"), SyntheticOp::Append { amount }),
                    &declared.origin_relative_context(),
                )
                .unwrap();
        }
        let snapshot = state
            .create_snapshot(&declared.origin_relative_context())
            .unwrap();
        let page = state
            .read_page(
                PageRequest::new(ReadStart::Snapshot(snapshot.clone()), 2),
                &declared.origin_relative_context(),
            )
            .unwrap();
        assert_eq!(
            Kernel::<Page<SyntheticRecord>>::try_from(pb::Page::from(Kernel(&page)))
                .unwrap()
                .into_inner(),
            page
        );

        let chunk = state
            .read_chunk(
                StreamRequest::new(ReadStart::Snapshot(snapshot), 2),
                &declared.origin_relative_context(),
            )
            .unwrap();
        assert_eq!(
            Kernel::<StreamChunk<SyntheticRecord>>::try_from(pb::StreamChunk::from(Kernel(&chunk)))
                .unwrap()
                .into_inner(),
            chunk
        );

        let contract = state.stream_contract();
        assert_eq!(
            Kernel::<StreamContract>::try_from(pb::StreamContract::from(Kernel(contract)))
                .unwrap()
                .into_inner(),
            contract
        );
    }

    #[test]
    fn read_requests_round_trip() {
        let page = PageRequest::new(ReadStart::Snapshot(SnapshotId::new("snap-1")), 3);
        assert_eq!(
            Kernel::<PageRequest>::try_from(pb::PageRequest::from(Kernel(&page)))
                .unwrap()
                .into_inner(),
            page
        );
        let chunk = StreamRequest::new(
            ReadStart::Resume(Cursor::in_snapshot(
                SnapshotId::new("snap-1"),
                JournalPosition::new(2),
            )),
            2,
        );
        assert_eq!(
            Kernel::<StreamRequest>::try_from(pb::StreamRequest::from(Kernel(&chunk)))
                .unwrap()
                .into_inner(),
            chunk
        );
    }

    #[test]
    fn a_short_digest_is_malformed() {
        let wire = pb::Receipt {
            command_id: "cmd-1".to_owned(),
            family: family::FAMILY.to_owned(),
            digest: vec![1, 2, 3],
            disposition: pb::CommitDisposition::COMMIT_DISPOSITION_NEW.into(),
            evidence: buffa::MessageField::some(pb::CommitEvidence::default()),
            consistency: pb::Consistency::CONSISTENCY_ORDERED_PER_AGGREGATE.into(),
            fence: None,
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let error = Kernel::<Receipt>::try_from(wire).unwrap_err();
        assert!(matches!(error, StateError::Malformed { ref field, .. } if field == "digest"));
    }

    #[test]
    fn an_unset_oneof_is_malformed() {
        assert!(matches!(
            Kernel::<Precondition>::try_from(pb::Precondition::default()).unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            Kernel::<ObservedState>::try_from(pb::ObservedState::default()).unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            Kernel::<ReadStart>::try_from(pb::ReadStart::default()).unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            Kernel::<SyntheticOp>::try_from(pb::SyntheticOp::default()).unwrap_err(),
            StateError::Malformed { .. }
        ));
    }

    #[test]
    fn an_unspecified_enum_is_malformed() {
        assert!(matches!(
            consistency(
                "consistency",
                pb::Consistency::CONSISTENCY_UNSPECIFIED.into()
            )
            .unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            stream_end("end", pb::StreamEnd::STREAM_END_UNSPECIFIED.into()).unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            delivery("delivery", pb::Delivery::DELIVERY_UNSPECIFIED.into()).unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            backpressure(
                "backpressure",
                pb::Backpressure::BACKPRESSURE_UNSPECIFIED.into()
            )
            .unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            compacted_range(
                "compacted_range",
                pb::CompactedRange::COMPACTED_RANGE_UNSPECIFIED.into()
            )
            .unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            completeness(
                "completeness",
                pb::PageCompleteness::PAGE_COMPLETENESS_UNSPECIFIED.into()
            )
            .unwrap_err(),
            StateError::Malformed { .. }
        ));
        assert!(matches!(
            disposition(
                "disposition",
                pb::CommitDisposition::COMMIT_DISPOSITION_UNSPECIFIED.into()
            )
            .unwrap_err(),
            StateError::Malformed { .. }
        ));
    }

    /// A value from a protocol this build does not know is refused, not
    /// guessed at.
    #[test]
    fn an_unknown_enum_value_is_malformed() {
        assert!(matches!(
            consistency("consistency", buffa::EnumValue::Unknown(99)).unwrap_err(),
            StateError::Malformed { .. }
        ));
    }

    #[test]
    fn a_missing_call_context_is_malformed() {
        assert!(matches!(
            declared_call(buffa::MessageField::<_, buffa::Inline<_>>::default()).unwrap_err(),
            StateError::Malformed { ref field, .. } if field == "context"
        ));
    }

    #[test]
    fn preconditions_and_observed_state_round_trip() {
        for precondition in [
            Precondition::Unconditional,
            Precondition::NoExistingState,
            Precondition::Revision(Revision::new(9)),
            Precondition::JournalHead(JournalPosition::new(4)),
        ] {
            assert_eq!(
                Kernel::<Precondition>::try_from(pb::Precondition::from(Kernel(precondition)))
                    .unwrap()
                    .into_inner(),
                precondition
            );
        }
        for observed in [
            ObservedState::Absent,
            ObservedState::Revision(Revision::new(2)),
            ObservedState::JournalHead(JournalPosition::new(6)),
        ] {
            assert_eq!(
                Kernel::<ObservedState>::try_from(pb::ObservedState::from(Kernel(observed)))
                    .unwrap()
                    .into_inner(),
                observed
            );
        }
    }

    #[test]
    fn durations_convert_both_ways() {
        assert_eq!(nanos_from_duration(Duration::from_millis(3)), 3_000_000);
        assert_eq!(duration_from_nanos(3_000_000), Duration::from_millis(3));
    }
}