1use std::{
13 collections::{BTreeSet, btree_set},
14 fmt,
15 str::FromStr,
16};
17
18use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
19use serde::{
20 Deserialize, Deserializer, Serialize, Serializer,
21 de::{self, SeqAccess},
22};
23use thiserror::Error;
24
25use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
26use crate::{
27 BoundedJson, CanonicalJson, CanonicalJsonError, CapabilityIdentity, CheckpointId, Digest,
28 JournalHead, JournalSequence, JsonLimits, RunId, SchemaReference, TenantId, Timestamp,
29};
30
31const MAX_DATABASE_ORDINAL: u64 = i64::MAX as u64;
32const SUPERSTEP_PATTERN: &str = "^(0|[1-9][0-9]{0,18})$";
33const NODE_ID_PATTERN: &str = "^(?!\\.{1,2}$)[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$";
34const STATE_DIGEST_DOMAIN: &[u8] = b"stateknot-checkpoint-state-v1\0";
35const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-checkpoint-intent-v1\0";
36const CHECKPOINT_DIGEST_DOMAIN: &[u8] = b"stateknot-checkpoint-v1\0";
37
38#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub struct Superstep(u64);
45
46impl Superstep {
47 pub const INITIAL: Self = Self(0);
49
50 pub const MAX: Self = Self(MAX_DATABASE_ORDINAL);
52
53 pub const fn new(value: u64) -> Result<Self, SuperstepError> {
60 if value > MAX_DATABASE_ORDINAL {
61 return Err(SuperstepError::AboveMaximum);
62 }
63 Ok(Self(value))
64 }
65
66 #[must_use]
68 pub const fn get(self) -> u64 {
69 self.0
70 }
71
72 #[must_use]
74 pub const fn checked_next(self) -> Option<Self> {
75 if self.0 == MAX_DATABASE_ORDINAL {
76 None
77 } else {
78 Some(Self(self.0 + 1))
79 }
80 }
81}
82
83impl fmt::Display for Superstep {
84 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85 self.0.fmt(formatter)
86 }
87}
88
89impl FromStr for Superstep {
90 type Err = SuperstepError;
91
92 fn from_str(value: &str) -> Result<Self, Self::Err> {
93 let value = parse_bounded_u64(value, MAX_DATABASE_ORDINAL)
94 .map_err(SuperstepError::from_decimal_error)?;
95 Self::new(value)
96 }
97}
98
99impl Serialize for Superstep {
100 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
101 where
102 S: Serializer,
103 {
104 serializer.collect_str(self)
105 }
106}
107
108impl<'de> Deserialize<'de> for Superstep {
109 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
110 where
111 D: Deserializer<'de>,
112 {
113 deserializer.deserialize_str(SuperstepVisitor)
114 }
115}
116
117struct SuperstepVisitor;
118
119impl de::Visitor<'_> for SuperstepVisitor {
120 type Value = Superstep;
121
122 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
123 formatter.write_str("a canonical non-negative decimal PostgreSQL BIGINT superstep")
124 }
125
126 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
127 where
128 E: de::Error,
129 {
130 value.parse().map_err(E::custom)
131 }
132}
133
134impl JsonSchema for Superstep {
135 fn schema_name() -> std::borrow::Cow<'static, str> {
136 "Superstep".into()
137 }
138
139 fn schema_id() -> std::borrow::Cow<'static, str> {
140 concat!(module_path!(), "::Superstep").into()
141 }
142
143 fn json_schema(_: &mut SchemaGenerator) -> Schema {
144 json_schema!({
145 "type": "string",
146 "minLength": 1,
147 "maxLength": 19,
148 "pattern": SUPERSTEP_PATTERN
149 })
150 }
151
152 fn inline_schema() -> bool {
153 true
154 }
155}
156
157#[derive(Clone, Debug, Eq, Error, PartialEq)]
159#[non_exhaustive]
160pub enum SuperstepError {
161 #[error("superstep must contain only unsigned ASCII decimal digits")]
163 InvalidFormat,
164
165 #[error("superstep must use canonical decimal text")]
167 NonCanonical,
168
169 #[error("superstep exceeds the PostgreSQL BIGINT maximum")]
171 AboveMaximum,
172}
173
174impl SuperstepError {
175 const fn from_decimal_error(error: UnsignedDecimalError) -> Self {
176 match error {
177 UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
178 Self::InvalidFormat
179 }
180 UnsignedDecimalError::LeadingZero => Self::NonCanonical,
181 UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => {
182 Self::AboveMaximum
183 }
184 }
185 }
186}
187
188#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
194pub struct NodeId(Box<str>);
195
196impl NodeId {
197 pub const MAX_LEN: usize = 128;
199
200 pub fn new(value: impl Into<String>) -> Result<Self, NodeIdError> {
207 let value = value.into();
208 validate_node_id(&value)?;
209 Ok(Self(value.into_boxed_str()))
210 }
211
212 #[must_use]
214 pub fn as_str(&self) -> &str {
215 &self.0
216 }
217}
218
219impl AsRef<str> for NodeId {
220 fn as_ref(&self) -> &str {
221 self.as_str()
222 }
223}
224
225impl fmt::Debug for NodeId {
226 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
227 formatter
228 .debug_tuple("NodeId")
229 .field(&self.as_str())
230 .finish()
231 }
232}
233
234impl fmt::Display for NodeId {
235 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
236 formatter.write_str(self.as_str())
237 }
238}
239
240impl FromStr for NodeId {
241 type Err = NodeIdError;
242
243 fn from_str(value: &str) -> Result<Self, Self::Err> {
244 Self::new(value)
245 }
246}
247
248impl TryFrom<String> for NodeId {
249 type Error = NodeIdError;
250
251 fn try_from(value: String) -> Result<Self, Self::Error> {
252 Self::new(value)
253 }
254}
255
256impl TryFrom<&str> for NodeId {
257 type Error = NodeIdError;
258
259 fn try_from(value: &str) -> Result<Self, Self::Error> {
260 Self::new(value)
261 }
262}
263
264impl Serialize for NodeId {
265 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
266 where
267 S: Serializer,
268 {
269 serializer.serialize_str(self.as_str())
270 }
271}
272
273impl<'de> Deserialize<'de> for NodeId {
274 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275 where
276 D: Deserializer<'de>,
277 {
278 deserializer.deserialize_string(NodeIdVisitor)
279 }
280}
281
282struct NodeIdVisitor;
283
284impl de::Visitor<'_> for NodeIdVisitor {
285 type Value = NodeId;
286
287 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
288 formatter.write_str("a bounded canonical StateKnot graph node identifier")
289 }
290
291 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
292 where
293 E: de::Error,
294 {
295 NodeId::try_from(value).map_err(E::custom)
296 }
297
298 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
299 where
300 E: de::Error,
301 {
302 NodeId::try_from(value).map_err(E::custom)
303 }
304}
305
306impl JsonSchema for NodeId {
307 fn schema_name() -> std::borrow::Cow<'static, str> {
308 "NodeId".into()
309 }
310
311 fn schema_id() -> std::borrow::Cow<'static, str> {
312 concat!(module_path!(), "::NodeId").into()
313 }
314
315 fn json_schema(_: &mut SchemaGenerator) -> Schema {
316 json_schema!({
317 "type": "string",
318 "minLength": 1,
319 "maxLength": 128,
320 "pattern": NODE_ID_PATTERN
321 })
322 }
323
324 fn inline_schema() -> bool {
325 true
326 }
327}
328
329fn validate_node_id(value: &str) -> Result<(), NodeIdError> {
330 if value.is_empty() {
331 return Err(NodeIdError::Empty);
332 }
333 if value.len() > NodeId::MAX_LEN {
334 return Err(NodeIdError::TooLong {
335 max: NodeId::MAX_LEN,
336 actual: value.len(),
337 });
338 }
339 if matches!(value, "." | "..") {
340 return Err(NodeIdError::PathLike);
341 }
342 if !value.as_bytes()[0].is_ascii_alphanumeric() {
343 return Err(NodeIdError::InvalidByte { index: 0 });
344 }
345 if let Some((index, _)) = value
346 .bytes()
347 .enumerate()
348 .find(|(_, byte)| !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b'-'))
349 {
350 return Err(NodeIdError::InvalidByte { index });
351 }
352 Ok(())
353}
354
355#[derive(Clone, Debug, Eq, Error, PartialEq)]
357#[non_exhaustive]
358pub enum NodeIdError {
359 #[error("node identifier must not be empty")]
361 Empty,
362
363 #[error("node identifier is {actual} bytes; maximum is {max}")]
365 TooLong {
366 max: usize,
368 actual: usize,
370 },
371
372 #[error("node identifier must not be path-like")]
374 PathLike,
375
376 #[error("node identifier contains an invalid byte at offset {index}")]
378 InvalidByte {
379 index: usize,
381 },
382}
383
384#[derive(Clone, Debug, Eq, PartialEq)]
386pub struct ReadyNodes(BTreeSet<NodeId>);
387
388impl ReadyNodes {
389 pub const MAX_LEN: usize = 1024;
391
392 pub fn try_new(nodes: impl IntoIterator<Item = NodeId>) -> Result<Self, ReadyNodesError> {
399 let mut values = BTreeSet::new();
400 for node in nodes {
401 if values.contains(&node) {
402 return Err(ReadyNodesError::Duplicate { node });
403 }
404 if values.len() == Self::MAX_LEN {
405 return Err(ReadyNodesError::TooMany {
406 maximum: Self::MAX_LEN,
407 actual: Self::MAX_LEN + 1,
408 });
409 }
410 values.insert(node);
411 }
412 Ok(Self(values))
413 }
414
415 #[must_use]
417 pub const fn empty() -> Self {
418 Self(BTreeSet::new())
419 }
420
421 #[must_use]
423 pub fn len(&self) -> usize {
424 self.0.len()
425 }
426
427 #[must_use]
429 pub fn is_empty(&self) -> bool {
430 self.0.is_empty()
431 }
432
433 pub fn iter(&self) -> btree_set::Iter<'_, NodeId> {
435 self.0.iter()
436 }
437
438 #[must_use]
440 pub fn contains(&self, node: &NodeId) -> bool {
441 self.0.contains(node)
442 }
443}
444
445impl Default for ReadyNodes {
446 fn default() -> Self {
447 Self::empty()
448 }
449}
450
451impl<'a> IntoIterator for &'a ReadyNodes {
452 type Item = &'a NodeId;
453 type IntoIter = btree_set::Iter<'a, NodeId>;
454
455 fn into_iter(self) -> Self::IntoIter {
456 self.iter()
457 }
458}
459
460impl TryFrom<Vec<NodeId>> for ReadyNodes {
461 type Error = ReadyNodesError;
462
463 fn try_from(nodes: Vec<NodeId>) -> Result<Self, Self::Error> {
464 Self::try_new(nodes)
465 }
466}
467
468impl Serialize for ReadyNodes {
469 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
470 where
471 S: Serializer,
472 {
473 serializer.collect_seq(self.iter())
474 }
475}
476
477impl<'de> Deserialize<'de> for ReadyNodes {
478 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
479 where
480 D: Deserializer<'de>,
481 {
482 deserializer.deserialize_seq(ReadyNodesVisitor)
483 }
484}
485
486struct ReadyNodesVisitor;
487
488impl<'de> de::Visitor<'de> for ReadyNodesVisitor {
489 type Value = ReadyNodes;
490
491 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
492 write!(
493 formatter,
494 "an array containing at most {} unique graph node identifiers",
495 ReadyNodes::MAX_LEN
496 )
497 }
498
499 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
500 where
501 A: SeqAccess<'de>,
502 {
503 let mut values = BTreeSet::new();
504 while let Some(node) = sequence.next_element::<NodeId>()? {
505 if values.contains(&node) {
506 return Err(de::Error::custom(ReadyNodesError::Duplicate { node }));
507 }
508 if values.len() == ReadyNodes::MAX_LEN {
509 return Err(de::Error::custom(ReadyNodesError::TooMany {
510 maximum: ReadyNodes::MAX_LEN,
511 actual: ReadyNodes::MAX_LEN + 1,
512 }));
513 }
514 values.insert(node);
515 }
516 Ok(ReadyNodes(values))
517 }
518}
519
520impl JsonSchema for ReadyNodes {
521 fn schema_name() -> std::borrow::Cow<'static, str> {
522 "ReadyNodes".into()
523 }
524
525 fn schema_id() -> std::borrow::Cow<'static, str> {
526 concat!(module_path!(), "::ReadyNodes").into()
527 }
528
529 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
530 json_schema!({
531 "type": "array",
532 "items": generator.subschema_for::<NodeId>(),
533 "maxItems": 1024,
534 "uniqueItems": true,
535 "description": "The wire array is serialized in deterministic ascending NodeId order. Runtime rejects duplicate identities."
536 })
537 }
538}
539
540#[derive(Clone, Debug, Eq, Error, PartialEq)]
542#[non_exhaustive]
543pub enum ReadyNodesError {
544 #[error("ready-node set contains duplicate node {node:?}")]
546 Duplicate {
547 node: NodeId,
549 },
550
551 #[error("ready-node set contains {actual} nodes; maximum is {maximum}")]
553 TooMany {
554 maximum: usize,
556 actual: usize,
558 },
559}
560
561#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
563#[serde(deny_unknown_fields)]
564pub struct GraphReference {
565 identity: CapabilityIdentity,
566 definition_digest: Digest,
567 state_schema: SchemaReference,
568}
569
570impl GraphReference {
571 #[must_use]
573 pub const fn new(
574 identity: CapabilityIdentity,
575 definition_digest: Digest,
576 state_schema: SchemaReference,
577 ) -> Self {
578 Self {
579 identity,
580 definition_digest,
581 state_schema,
582 }
583 }
584
585 #[must_use]
587 pub const fn identity(&self) -> &CapabilityIdentity {
588 &self.identity
589 }
590
591 #[must_use]
593 pub const fn definition_digest(&self) -> Digest {
594 self.definition_digest
595 }
596
597 #[must_use]
599 pub const fn state_schema(&self) -> &SchemaReference {
600 &self.state_schema
601 }
602}
603
604#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
611#[serde(deny_unknown_fields)]
612pub struct CheckpointState {
613 schema: SchemaReference,
614 data: BoundedJson,
615 digest: Digest,
616}
617
618impl CheckpointState {
619 pub fn new(schema: SchemaReference, data: BoundedJson) -> Result<Self, CheckpointStateError> {
626 let digest =
627 compute_state_digest(&schema, &data).map_err(CheckpointStateError::integrity)?;
628 Ok(Self {
629 schema,
630 data,
631 digest,
632 })
633 }
634
635 pub fn restore(
642 schema: SchemaReference,
643 data: BoundedJson,
644 digest: Digest,
645 ) -> Result<Self, CheckpointStateError> {
646 let expected =
647 compute_state_digest(&schema, &data).map_err(CheckpointStateError::integrity)?;
648 if digest != expected {
649 return Err(CheckpointStateError::DigestMismatch);
650 }
651 Ok(Self {
652 schema,
653 data,
654 digest,
655 })
656 }
657
658 #[must_use]
660 pub const fn schema(&self) -> &SchemaReference {
661 &self.schema
662 }
663
664 #[must_use]
666 pub const fn data(&self) -> &BoundedJson {
667 &self.data
668 }
669
670 #[must_use]
672 pub const fn digest(&self) -> Digest {
673 self.digest
674 }
675}
676
677impl fmt::Debug for CheckpointState {
678 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
679 formatter
680 .debug_struct("CheckpointState")
681 .field("schema", &self.schema)
682 .field("stats", &self.data.stats())
683 .field("digest", &self.digest)
684 .finish_non_exhaustive()
685 }
686}
687
688impl<'de> Deserialize<'de> for CheckpointState {
689 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
690 where
691 D: Deserializer<'de>,
692 {
693 #[derive(Deserialize)]
694 #[serde(deny_unknown_fields)]
695 struct Wire {
696 schema: SchemaReference,
697 #[serde(deserialize_with = "deserialize_checkpoint_data")]
698 data: BoundedJson,
699 digest: Digest,
700 }
701
702 let wire = Wire::deserialize(deserializer)?;
703 Self::restore(wire.schema, wire.data, wire.digest).map_err(de::Error::custom)
704 }
705}
706
707fn deserialize_checkpoint_data<'de, D>(deserializer: D) -> Result<BoundedJson, D::Error>
708where
709 D: Deserializer<'de>,
710{
711 BoundedJson::deserialize_with_limits(deserializer, JsonLimits::MAXIMUM)
712}
713
714#[derive(Clone, Debug, Eq, Error, PartialEq)]
716#[non_exhaustive]
717pub enum CheckpointStateError {
718 #[error("checkpoint state integrity calculation failed: {source}")]
720 Integrity {
721 #[source]
723 source: CheckpointIntegrityError,
724 },
725
726 #[error("checkpoint state digest does not match its schema and data")]
728 DigestMismatch,
729}
730
731impl CheckpointStateError {
732 const fn integrity(source: CheckpointIntegrityError) -> Self {
733 Self::Integrity { source }
734 }
735}
736
737#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
743#[serde(deny_unknown_fields)]
744pub struct CheckpointHead {
745 tenant_id: TenantId,
746 run_id: RunId,
747 checkpoint_id: CheckpointId,
748 superstep: Superstep,
749 graph: GraphReference,
750 journal_head: JournalHead,
751 digest: Digest,
752}
753
754impl CheckpointHead {
755 pub fn new(
762 tenant_id: TenantId,
763 run_id: RunId,
764 checkpoint_id: CheckpointId,
765 superstep: Superstep,
766 graph: GraphReference,
767 journal_head: JournalHead,
768 digest: Digest,
769 ) -> Result<Self, CheckpointHeadError> {
770 validate_journal_scope(&tenant_id, run_id, &journal_head)
771 .map_err(CheckpointHeadError::from_scope)?;
772 Ok(Self {
773 tenant_id,
774 run_id,
775 checkpoint_id,
776 superstep,
777 graph,
778 journal_head,
779 digest,
780 })
781 }
782
783 #[must_use]
785 pub const fn tenant_id(&self) -> &TenantId {
786 &self.tenant_id
787 }
788
789 #[must_use]
791 pub const fn run_id(&self) -> RunId {
792 self.run_id
793 }
794
795 #[must_use]
797 pub const fn checkpoint_id(&self) -> CheckpointId {
798 self.checkpoint_id
799 }
800
801 #[must_use]
803 pub const fn superstep(&self) -> Superstep {
804 self.superstep
805 }
806
807 #[must_use]
809 pub const fn graph(&self) -> &GraphReference {
810 &self.graph
811 }
812
813 #[must_use]
815 pub const fn journal_head(&self) -> &JournalHead {
816 &self.journal_head
817 }
818
819 #[must_use]
821 pub const fn digest(&self) -> Digest {
822 self.digest
823 }
824}
825
826impl<'de> Deserialize<'de> for CheckpointHead {
827 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
828 where
829 D: Deserializer<'de>,
830 {
831 #[derive(Deserialize)]
832 #[serde(deny_unknown_fields)]
833 struct Wire {
834 tenant_id: TenantId,
835 run_id: RunId,
836 checkpoint_id: CheckpointId,
837 superstep: Superstep,
838 graph: GraphReference,
839 journal_head: JournalHead,
840 digest: Digest,
841 }
842
843 let wire = Wire::deserialize(deserializer)?;
844 Self::new(
845 wire.tenant_id,
846 wire.run_id,
847 wire.checkpoint_id,
848 wire.superstep,
849 wire.graph,
850 wire.journal_head,
851 wire.digest,
852 )
853 .map_err(de::Error::custom)
854 }
855}
856
857#[derive(Clone, Debug, Eq, Error, PartialEq)]
859#[non_exhaustive]
860pub enum CheckpointHeadError {
861 #[error("checkpoint journal head crosses the checkpoint tenant boundary")]
863 JournalTenantMismatch,
864
865 #[error("checkpoint journal head does not belong to the checkpoint run")]
867 JournalRunMismatch,
868}
869
870impl CheckpointHeadError {
871 const fn from_scope(error: JournalScopeError) -> Self {
872 match error {
873 JournalScopeError::Tenant => Self::JournalTenantMismatch,
874 JournalScopeError::Run => Self::JournalRunMismatch,
875 }
876 }
877}
878
879#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
885#[serde(deny_unknown_fields)]
886pub struct CheckpointWrite {
887 tenant_id: TenantId,
888 run_id: RunId,
889 checkpoint_id: CheckpointId,
890 superstep: Superstep,
891 graph: GraphReference,
892 state: CheckpointState,
893 ready_nodes: ReadyNodes,
894 #[serde(skip_serializing_if = "Option::is_none")]
895 parent: Option<CheckpointHead>,
896 intent_digest: Digest,
897}
898
899impl CheckpointWrite {
900 pub fn initial(
907 tenant_id: TenantId,
908 run_id: RunId,
909 checkpoint_id: CheckpointId,
910 graph: GraphReference,
911 state: CheckpointState,
912 ready_nodes: ReadyNodes,
913 ) -> Result<Self, CheckpointWriteError> {
914 Self::build(
915 tenant_id,
916 run_id,
917 checkpoint_id,
918 Superstep::INITIAL,
919 graph,
920 state,
921 ready_nodes,
922 None,
923 None,
924 )
925 }
926
927 pub fn successor(
938 checkpoint_id: CheckpointId,
939 parent: &Checkpoint,
940 state: CheckpointState,
941 ready_nodes: ReadyNodes,
942 ) -> Result<Self, CheckpointWriteError> {
943 let superstep = parent
944 .superstep
945 .checked_next()
946 .ok_or(CheckpointWriteError::SuperstepOverflow)?;
947 Self::build(
948 parent.tenant_id.clone(),
949 parent.run_id,
950 checkpoint_id,
951 superstep,
952 parent.graph.clone(),
953 state,
954 ready_nodes,
955 Some(parent.head()),
956 None,
957 )
958 }
959
960 #[allow(clippy::too_many_arguments)]
970 pub fn restore(
971 tenant_id: TenantId,
972 run_id: RunId,
973 checkpoint_id: CheckpointId,
974 superstep: Superstep,
975 graph: GraphReference,
976 state: CheckpointState,
977 ready_nodes: ReadyNodes,
978 parent: Option<CheckpointHead>,
979 intent_digest: Digest,
980 ) -> Result<Self, CheckpointWriteError> {
981 Self::build(
982 tenant_id,
983 run_id,
984 checkpoint_id,
985 superstep,
986 graph,
987 state,
988 ready_nodes,
989 parent,
990 Some(intent_digest),
991 )
992 }
993
994 #[allow(clippy::too_many_arguments)]
995 fn build(
996 tenant_id: TenantId,
997 run_id: RunId,
998 checkpoint_id: CheckpointId,
999 superstep: Superstep,
1000 graph: GraphReference,
1001 state: CheckpointState,
1002 ready_nodes: ReadyNodes,
1003 parent: Option<CheckpointHead>,
1004 supplied_intent_digest: Option<Digest>,
1005 ) -> Result<Self, CheckpointWriteError> {
1006 validate_write_shape(
1007 &tenant_id,
1008 run_id,
1009 checkpoint_id,
1010 superstep,
1011 &graph,
1012 &state,
1013 parent.as_ref(),
1014 )?;
1015 let intent_digest = compute_intent_digest(&CheckpointIntentDigestWire {
1016 tenant_id: &tenant_id,
1017 run_id,
1018 checkpoint_id,
1019 superstep,
1020 graph: &graph,
1021 state_digest: state.digest,
1022 ready_nodes: &ready_nodes,
1023 parent: parent.as_ref(),
1024 })
1025 .map_err(CheckpointWriteError::integrity)?;
1026 if supplied_intent_digest.is_some_and(|supplied| supplied != intent_digest) {
1027 return Err(CheckpointWriteError::IntentDigestMismatch);
1028 }
1029 Ok(Self {
1030 tenant_id,
1031 run_id,
1032 checkpoint_id,
1033 superstep,
1034 graph,
1035 state,
1036 ready_nodes,
1037 parent,
1038 intent_digest,
1039 })
1040 }
1041
1042 #[must_use]
1044 pub const fn tenant_id(&self) -> &TenantId {
1045 &self.tenant_id
1046 }
1047
1048 #[must_use]
1050 pub const fn run_id(&self) -> RunId {
1051 self.run_id
1052 }
1053
1054 #[must_use]
1056 pub const fn checkpoint_id(&self) -> CheckpointId {
1057 self.checkpoint_id
1058 }
1059
1060 #[must_use]
1062 pub const fn superstep(&self) -> Superstep {
1063 self.superstep
1064 }
1065
1066 #[must_use]
1068 pub const fn graph(&self) -> &GraphReference {
1069 &self.graph
1070 }
1071
1072 #[must_use]
1074 pub const fn state(&self) -> &CheckpointState {
1075 &self.state
1076 }
1077
1078 #[must_use]
1080 pub const fn ready_nodes(&self) -> &ReadyNodes {
1081 &self.ready_nodes
1082 }
1083
1084 #[must_use]
1086 pub const fn parent(&self) -> Option<&CheckpointHead> {
1087 self.parent.as_ref()
1088 }
1089
1090 #[must_use]
1092 pub const fn intent_digest(&self) -> Digest {
1093 self.intent_digest
1094 }
1095}
1096
1097impl fmt::Debug for CheckpointWrite {
1098 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 formatter
1100 .debug_struct("CheckpointWrite")
1101 .field("tenant_id", &self.tenant_id)
1102 .field("run_id", &self.run_id)
1103 .field("checkpoint_id", &self.checkpoint_id)
1104 .field("superstep", &self.superstep)
1105 .field("graph", &self.graph)
1106 .field("state", &self.state)
1107 .field("ready_nodes", &self.ready_nodes)
1108 .field("parent", &self.parent)
1109 .field("intent_digest", &self.intent_digest)
1110 .finish_non_exhaustive()
1111 }
1112}
1113
1114impl<'de> Deserialize<'de> for CheckpointWrite {
1115 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1116 where
1117 D: Deserializer<'de>,
1118 {
1119 #[derive(Deserialize)]
1120 #[serde(deny_unknown_fields)]
1121 struct Wire {
1122 tenant_id: TenantId,
1123 run_id: RunId,
1124 checkpoint_id: CheckpointId,
1125 superstep: Superstep,
1126 graph: GraphReference,
1127 state: CheckpointState,
1128 ready_nodes: ReadyNodes,
1129 parent: Option<CheckpointHead>,
1130 intent_digest: Digest,
1131 }
1132
1133 let wire = Wire::deserialize(deserializer)?;
1134 Self::build(
1135 wire.tenant_id,
1136 wire.run_id,
1137 wire.checkpoint_id,
1138 wire.superstep,
1139 wire.graph,
1140 wire.state,
1141 wire.ready_nodes,
1142 wire.parent,
1143 Some(wire.intent_digest),
1144 )
1145 .map_err(de::Error::custom)
1146 }
1147}
1148
1149#[derive(Clone, Debug, Eq, Error, PartialEq)]
1151#[non_exhaustive]
1152pub enum CheckpointWriteError {
1153 #[error("checkpoint state schema does not match the graph state schema")]
1155 StateSchemaMismatch,
1156
1157 #[error("initial checkpoint must not contain a parent")]
1159 InitialHasParent,
1160
1161 #[error("non-initial checkpoint must contain a parent")]
1163 SuccessorMissingParent,
1164
1165 #[error("checkpoint parent crosses the checkpoint tenant boundary")]
1167 ParentTenantMismatch,
1168
1169 #[error("checkpoint parent does not belong to the checkpoint run")]
1171 ParentRunMismatch,
1172
1173 #[error("checkpoint successor must use a new checkpoint identifier")]
1175 ReusedCheckpointId,
1176
1177 #[error("checkpoint superstep overflowed")]
1179 SuperstepOverflow,
1180
1181 #[error("checkpoint superstep is {actual}; expected {expected}")]
1183 NonContiguousSuperstep {
1184 expected: Superstep,
1186 actual: Superstep,
1188 },
1189
1190 #[error("checkpoint graph reference differs from its parent")]
1192 ParentGraphMismatch,
1193
1194 #[error("checkpoint intent integrity calculation failed: {source}")]
1196 Integrity {
1197 #[source]
1199 source: CheckpointIntegrityError,
1200 },
1201
1202 #[error("checkpoint intent digest does not match its fields")]
1204 IntentDigestMismatch,
1205}
1206
1207impl CheckpointWriteError {
1208 const fn integrity(source: CheckpointIntegrityError) -> Self {
1209 Self::Integrity { source }
1210 }
1211}
1212
1213#[allow(clippy::struct_field_names)]
1219#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1220#[serde(deny_unknown_fields)]
1221pub struct Checkpoint {
1222 tenant_id: TenantId,
1223 run_id: RunId,
1224 checkpoint_id: CheckpointId,
1225 superstep: Superstep,
1226 graph: GraphReference,
1227 state: CheckpointState,
1228 ready_nodes: ReadyNodes,
1229 #[serde(skip_serializing_if = "Option::is_none")]
1230 parent: Option<CheckpointHead>,
1231 intent_digest: Digest,
1232 journal_head: JournalHead,
1233 digest: Digest,
1234}
1235
1236impl Checkpoint {
1237 pub fn commit(
1248 write: CheckpointWrite,
1249 journal_head: JournalHead,
1250 ) -> Result<Self, CheckpointError> {
1251 Self::build(write, journal_head, None)
1252 }
1253
1254 pub fn restore(
1261 write: CheckpointWrite,
1262 journal_head: JournalHead,
1263 digest: Digest,
1264 ) -> Result<Self, CheckpointError> {
1265 Self::build(write, journal_head, Some(digest))
1266 }
1267
1268 fn build(
1269 write: CheckpointWrite,
1270 journal_head: JournalHead,
1271 supplied_digest: Option<Digest>,
1272 ) -> Result<Self, CheckpointError> {
1273 validate_journal_scope(&write.tenant_id, write.run_id, &journal_head)
1274 .map_err(CheckpointError::from_scope)?;
1275 if let Some(parent) = &write.parent {
1276 if journal_head.sequence() <= parent.journal_head.sequence() {
1277 return Err(CheckpointError::JournalDidNotAdvance {
1278 previous: parent.journal_head.sequence(),
1279 actual: journal_head.sequence(),
1280 });
1281 }
1282 if journal_head.recorded_at() < parent.journal_head.recorded_at() {
1283 return Err(CheckpointError::ClockRegression {
1284 previous: parent.journal_head.recorded_at(),
1285 actual: journal_head.recorded_at(),
1286 });
1287 }
1288 }
1289
1290 let digest = compute_checkpoint_digest(&CheckpointDigestWire {
1291 intent_digest: write.intent_digest,
1292 journal_head: &journal_head,
1293 })
1294 .map_err(CheckpointError::integrity)?;
1295 if supplied_digest.is_some_and(|supplied| supplied != digest) {
1296 return Err(CheckpointError::DigestMismatch);
1297 }
1298
1299 Ok(Self {
1300 tenant_id: write.tenant_id,
1301 run_id: write.run_id,
1302 checkpoint_id: write.checkpoint_id,
1303 superstep: write.superstep,
1304 graph: write.graph,
1305 state: write.state,
1306 ready_nodes: write.ready_nodes,
1307 parent: write.parent,
1308 intent_digest: write.intent_digest,
1309 journal_head,
1310 digest,
1311 })
1312 }
1313
1314 #[must_use]
1316 pub const fn tenant_id(&self) -> &TenantId {
1317 &self.tenant_id
1318 }
1319
1320 #[must_use]
1322 pub const fn run_id(&self) -> RunId {
1323 self.run_id
1324 }
1325
1326 #[must_use]
1328 pub const fn checkpoint_id(&self) -> CheckpointId {
1329 self.checkpoint_id
1330 }
1331
1332 #[must_use]
1334 pub const fn superstep(&self) -> Superstep {
1335 self.superstep
1336 }
1337
1338 #[must_use]
1340 pub const fn graph(&self) -> &GraphReference {
1341 &self.graph
1342 }
1343
1344 #[must_use]
1346 pub const fn state(&self) -> &CheckpointState {
1347 &self.state
1348 }
1349
1350 #[must_use]
1352 pub const fn ready_nodes(&self) -> &ReadyNodes {
1353 &self.ready_nodes
1354 }
1355
1356 #[must_use]
1358 pub const fn parent(&self) -> Option<&CheckpointHead> {
1359 self.parent.as_ref()
1360 }
1361
1362 #[must_use]
1364 pub const fn intent_digest(&self) -> Digest {
1365 self.intent_digest
1366 }
1367
1368 #[must_use]
1370 pub const fn journal_head(&self) -> &JournalHead {
1371 &self.journal_head
1372 }
1373
1374 #[must_use]
1376 pub const fn digest(&self) -> Digest {
1377 self.digest
1378 }
1379
1380 #[must_use]
1382 pub fn head(&self) -> CheckpointHead {
1383 CheckpointHead {
1384 tenant_id: self.tenant_id.clone(),
1385 run_id: self.run_id,
1386 checkpoint_id: self.checkpoint_id,
1387 superstep: self.superstep,
1388 graph: self.graph.clone(),
1389 journal_head: self.journal_head.clone(),
1390 digest: self.digest,
1391 }
1392 }
1393
1394 #[must_use]
1396 pub fn matches_write(&self, write: &CheckpointWrite) -> bool {
1397 self.tenant_id == write.tenant_id
1398 && self.run_id == write.run_id
1399 && self.checkpoint_id == write.checkpoint_id
1400 && self.superstep == write.superstep
1401 && self.graph == write.graph
1402 && self.state == write.state
1403 && self.ready_nodes == write.ready_nodes
1404 && self.parent == write.parent
1405 && self.intent_digest == write.intent_digest
1406 }
1407
1408 #[must_use]
1410 pub fn write_intent(&self) -> CheckpointWrite {
1411 CheckpointWrite {
1412 tenant_id: self.tenant_id.clone(),
1413 run_id: self.run_id,
1414 checkpoint_id: self.checkpoint_id,
1415 superstep: self.superstep,
1416 graph: self.graph.clone(),
1417 state: self.state.clone(),
1418 ready_nodes: self.ready_nodes.clone(),
1419 parent: self.parent.clone(),
1420 intent_digest: self.intent_digest,
1421 }
1422 }
1423}
1424
1425impl fmt::Debug for Checkpoint {
1426 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 formatter
1428 .debug_struct("Checkpoint")
1429 .field("tenant_id", &self.tenant_id)
1430 .field("run_id", &self.run_id)
1431 .field("checkpoint_id", &self.checkpoint_id)
1432 .field("superstep", &self.superstep)
1433 .field("graph", &self.graph)
1434 .field("state", &self.state)
1435 .field("ready_nodes", &self.ready_nodes)
1436 .field("parent", &self.parent)
1437 .field("intent_digest", &self.intent_digest)
1438 .field("journal_head", &self.journal_head)
1439 .field("digest", &self.digest)
1440 .finish_non_exhaustive()
1441 }
1442}
1443
1444impl<'de> Deserialize<'de> for Checkpoint {
1445 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1446 where
1447 D: Deserializer<'de>,
1448 {
1449 #[derive(Deserialize)]
1450 #[serde(deny_unknown_fields)]
1451 struct Wire {
1452 tenant_id: TenantId,
1453 run_id: RunId,
1454 checkpoint_id: CheckpointId,
1455 superstep: Superstep,
1456 graph: GraphReference,
1457 state: CheckpointState,
1458 ready_nodes: ReadyNodes,
1459 parent: Option<CheckpointHead>,
1460 intent_digest: Digest,
1461 journal_head: JournalHead,
1462 digest: Digest,
1463 }
1464
1465 let wire = Wire::deserialize(deserializer)?;
1466 let write = CheckpointWrite::build(
1467 wire.tenant_id,
1468 wire.run_id,
1469 wire.checkpoint_id,
1470 wire.superstep,
1471 wire.graph,
1472 wire.state,
1473 wire.ready_nodes,
1474 wire.parent,
1475 Some(wire.intent_digest),
1476 )
1477 .map_err(de::Error::custom)?;
1478 Self::restore(write, wire.journal_head, wire.digest).map_err(de::Error::custom)
1479 }
1480}
1481
1482#[derive(Clone, Debug, Eq, Error, PartialEq)]
1484#[non_exhaustive]
1485pub enum CheckpointError {
1486 #[error("checkpoint journal head crosses the checkpoint tenant boundary")]
1488 JournalTenantMismatch,
1489
1490 #[error("checkpoint journal head does not belong to the checkpoint run")]
1492 JournalRunMismatch,
1493
1494 #[error("checkpoint journal sequence is {actual}; it must be greater than {previous}")]
1496 JournalDidNotAdvance {
1497 previous: JournalSequence,
1499 actual: JournalSequence,
1501 },
1502
1503 #[error("checkpoint journal time {actual} precedes parent time {previous}")]
1505 ClockRegression {
1506 previous: Timestamp,
1508 actual: Timestamp,
1510 },
1511
1512 #[error("checkpoint integrity calculation failed: {source}")]
1514 Integrity {
1515 #[source]
1517 source: CheckpointIntegrityError,
1518 },
1519
1520 #[error("checkpoint digest does not match its intent and journal head")]
1522 DigestMismatch,
1523}
1524
1525impl CheckpointError {
1526 const fn from_scope(error: JournalScopeError) -> Self {
1527 match error {
1528 JournalScopeError::Tenant => Self::JournalTenantMismatch,
1529 JournalScopeError::Run => Self::JournalRunMismatch,
1530 }
1531 }
1532
1533 const fn integrity(source: CheckpointIntegrityError) -> Self {
1534 Self::Integrity { source }
1535 }
1536}
1537
1538#[derive(Debug)]
1546pub struct CheckpointLineageVerifier {
1547 expected: Option<CheckpointHead>,
1548}
1549
1550impl CheckpointLineageVerifier {
1551 #[must_use]
1553 pub const fn from_tip(tip: CheckpointHead) -> Self {
1554 Self {
1555 expected: Some(tip),
1556 }
1557 }
1558
1559 #[must_use]
1561 pub const fn expected(&self) -> Option<&CheckpointHead> {
1562 self.expected.as_ref()
1563 }
1564
1565 #[must_use]
1567 pub const fn is_complete(&self) -> bool {
1568 self.expected.is_none()
1569 }
1570
1571 pub fn verify_next(&mut self, checkpoint: &Checkpoint) -> Result<(), CheckpointLineageError> {
1579 let Some(expected) = &self.expected else {
1580 return Err(CheckpointLineageError::AlreadyComplete);
1581 };
1582 if checkpoint.head() != *expected {
1583 return Err(CheckpointLineageError::HeadMismatch);
1584 }
1585 self.expected.clone_from(&checkpoint.parent);
1586 Ok(())
1587 }
1588}
1589
1590#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1592#[non_exhaustive]
1593pub enum CheckpointLineageError {
1594 #[error("checkpoint does not match the expected lineage head")]
1596 HeadMismatch,
1597
1598 #[error("checkpoint lineage is already complete")]
1600 AlreadyComplete,
1601}
1602
1603#[derive(Clone, Debug, Eq, Error, PartialEq)]
1605#[non_exhaustive]
1606pub enum CheckpointIntegrityError {
1607 #[error("checkpoint state canonicalization failed: {source}")]
1609 StateCanonicalization {
1610 #[source]
1612 source: CanonicalJsonError,
1613 },
1614
1615 #[error("checkpoint checksum preimage canonical serialization failed")]
1617 CanonicalSerialization,
1618}
1619
1620#[derive(Serialize)]
1621struct StateDigestWire<'a> {
1622 schema: &'a SchemaReference,
1623 data_digest: Digest,
1624}
1625
1626#[derive(Serialize)]
1627struct CheckpointIntentDigestWire<'a> {
1628 tenant_id: &'a TenantId,
1629 run_id: RunId,
1630 checkpoint_id: CheckpointId,
1631 superstep: Superstep,
1632 graph: &'a GraphReference,
1633 state_digest: Digest,
1634 ready_nodes: &'a ReadyNodes,
1635 parent: Option<&'a CheckpointHead>,
1636}
1637
1638#[derive(Serialize)]
1639struct CheckpointDigestWire<'a> {
1640 intent_digest: Digest,
1641 journal_head: &'a JournalHead,
1642}
1643
1644fn compute_state_digest(
1645 schema: &SchemaReference,
1646 data: &BoundedJson,
1647) -> Result<Digest, CheckpointIntegrityError> {
1648 let canonical = CanonicalJson::new(data)
1649 .map_err(|source| CheckpointIntegrityError::StateCanonicalization { source })?;
1650 domain_separated_digest(
1651 STATE_DIGEST_DOMAIN,
1652 &StateDigestWire {
1653 schema,
1654 data_digest: canonical.digest(),
1655 },
1656 )
1657}
1658
1659fn compute_intent_digest(
1660 value: &CheckpointIntentDigestWire<'_>,
1661) -> Result<Digest, CheckpointIntegrityError> {
1662 domain_separated_digest(INTENT_DIGEST_DOMAIN, value)
1663}
1664
1665fn compute_checkpoint_digest(
1666 value: &CheckpointDigestWire<'_>,
1667) -> Result<Digest, CheckpointIntegrityError> {
1668 domain_separated_digest(CHECKPOINT_DIGEST_DOMAIN, value)
1669}
1670
1671fn domain_separated_digest<T: Serialize>(
1672 domain: &[u8],
1673 value: &T,
1674) -> Result<Digest, CheckpointIntegrityError> {
1675 let canonical = serde_json_canonicalizer::to_vec(value)
1676 .map_err(|_| CheckpointIntegrityError::CanonicalSerialization)?;
1677 let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
1678 preimage.extend_from_slice(domain);
1679 preimage.extend_from_slice(&canonical);
1680 Ok(Digest::sha256(preimage))
1681}
1682
1683#[allow(clippy::too_many_arguments)]
1684fn validate_write_shape(
1685 tenant_id: &TenantId,
1686 run_id: RunId,
1687 checkpoint_id: CheckpointId,
1688 superstep: Superstep,
1689 graph: &GraphReference,
1690 state: &CheckpointState,
1691 parent: Option<&CheckpointHead>,
1692) -> Result<(), CheckpointWriteError> {
1693 if state.schema != graph.state_schema {
1694 return Err(CheckpointWriteError::StateSchemaMismatch);
1695 }
1696
1697 match (superstep, parent) {
1698 (Superstep::INITIAL, None) => Ok(()),
1699 (Superstep::INITIAL, Some(_)) => Err(CheckpointWriteError::InitialHasParent),
1700 (_, None) => Err(CheckpointWriteError::SuccessorMissingParent),
1701 (actual, Some(parent)) => {
1702 if parent.tenant_id != *tenant_id {
1703 return Err(CheckpointWriteError::ParentTenantMismatch);
1704 }
1705 if parent.run_id != run_id {
1706 return Err(CheckpointWriteError::ParentRunMismatch);
1707 }
1708 if parent.checkpoint_id == checkpoint_id {
1709 return Err(CheckpointWriteError::ReusedCheckpointId);
1710 }
1711 let expected = parent
1712 .superstep
1713 .checked_next()
1714 .ok_or(CheckpointWriteError::SuperstepOverflow)?;
1715 if actual != expected {
1716 return Err(CheckpointWriteError::NonContiguousSuperstep { expected, actual });
1717 }
1718 if parent.graph != *graph {
1719 return Err(CheckpointWriteError::ParentGraphMismatch);
1720 }
1721 Ok(())
1722 }
1723 }
1724}
1725
1726#[derive(Clone, Copy)]
1727enum JournalScopeError {
1728 Tenant,
1729 Run,
1730}
1731
1732fn validate_journal_scope(
1733 tenant_id: &TenantId,
1734 run_id: RunId,
1735 journal_head: &JournalHead,
1736) -> Result<(), JournalScopeError> {
1737 if journal_head.tenant_id() != tenant_id {
1738 return Err(JournalScopeError::Tenant);
1739 }
1740 if journal_head.run_id() != run_id {
1741 return Err(JournalScopeError::Run);
1742 }
1743 Ok(())
1744}
1745
1746#[cfg(test)]
1747mod tests {
1748 use super::*;
1749 use crate::{
1750 CapabilityName, CapabilityReference, EventId, IssuerId, PrincipalIdentity, SchemaId,
1751 SubjectId, Version,
1752 };
1753 use proptest::prelude::*;
1754 use serde_json::{Value, from_value, json, to_value};
1755
1756 fn tenant() -> TenantId {
1757 TenantId::try_from("tenant-production").unwrap()
1758 }
1759
1760 fn other_tenant() -> TenantId {
1761 TenantId::try_from("tenant-other").unwrap()
1762 }
1763
1764 fn run() -> RunId {
1765 "01912345-6789-7abc-8def-0123456789ae".parse().unwrap()
1766 }
1767
1768 fn other_run() -> RunId {
1769 "01912345-6789-7abc-8def-0123456789af".parse().unwrap()
1770 }
1771
1772 fn checkpoint_id(suffix: &str) -> CheckpointId {
1773 format!("01912345-6789-7abc-8def-0123456789{suffix}")
1774 .parse()
1775 .unwrap()
1776 }
1777
1778 fn state_schema(label: &[u8]) -> SchemaReference {
1779 SchemaReference::new(
1780 "https://stateknot.github.io/schema/test/workflow-state/1.0.0"
1781 .parse::<SchemaId>()
1782 .unwrap(),
1783 Version::new(1, 0, 0),
1784 Digest::sha256(label),
1785 )
1786 }
1787
1788 fn graph_with_schema(schema: SchemaReference) -> GraphReference {
1789 let owner = PrincipalIdentity::new(
1790 "https://issuer.example.com/stateknot"
1791 .parse::<IssuerId>()
1792 .unwrap(),
1793 "workflow-registry".parse::<SubjectId>().unwrap(),
1794 );
1795 let capability = CapabilityReference::new(
1796 "orders.fulfillment".parse::<CapabilityName>().unwrap(),
1797 Version::new(1, 4, 0),
1798 );
1799 GraphReference::new(
1800 CapabilityIdentity::new(owner, capability),
1801 Digest::sha256(b"compiled-order-graph-v1.4.0"),
1802 schema,
1803 )
1804 }
1805
1806 fn graph() -> GraphReference {
1807 graph_with_schema(state_schema(b"order-state-schema-v1"))
1808 }
1809
1810 fn state(value: Value) -> CheckpointState {
1811 CheckpointState::new(
1812 graph().state_schema().clone(),
1813 BoundedJson::try_from_value(value).unwrap(),
1814 )
1815 .unwrap()
1816 }
1817
1818 fn ready(values: &[&str]) -> ReadyNodes {
1819 ReadyNodes::try_new(values.iter().map(|value| value.parse::<NodeId>().unwrap())).unwrap()
1820 }
1821
1822 fn at(offset_micros: i64) -> Timestamp {
1823 let base = "2030-01-01T00:00:00.000000Z".parse::<Timestamp>().unwrap();
1824 Timestamp::from_unix_micros(base.unix_micros() + offset_micros).unwrap()
1825 }
1826
1827 fn journal(sequence: u64, observed_at: Timestamp) -> JournalHead {
1828 let event_id = format!("01912345-6789-7abc-8def-0123456789{sequence:02x}")
1829 .parse::<EventId>()
1830 .unwrap();
1831 JournalHead::new(
1832 tenant(),
1833 run(),
1834 JournalSequence::new(sequence).unwrap(),
1835 event_id,
1836 observed_at,
1837 Digest::sha256(format!("journal-event-{sequence}")),
1838 )
1839 }
1840
1841 fn initial_checkpoint() -> Checkpoint {
1842 let write = CheckpointWrite::initial(
1843 tenant(),
1844 run(),
1845 checkpoint_id("d1"),
1846 graph(),
1847 state(json!({"order_id": "order-42", "status": "pending"})),
1848 ready(&["authorize", "reserve-stock"]),
1849 )
1850 .unwrap();
1851 Checkpoint::commit(write, journal(1, at(1))).unwrap()
1852 }
1853
1854 fn successor_checkpoint() -> Checkpoint {
1855 let parent = initial_checkpoint();
1856 let write = CheckpointWrite::successor(
1857 checkpoint_id("d2"),
1858 &parent,
1859 state(json!({"order_id": "order-42", "status": "reserved"})),
1860 ready(&["capture-payment"]),
1861 )
1862 .unwrap();
1863 Checkpoint::commit(write, journal(3, at(3))).unwrap()
1864 }
1865
1866 #[test]
1867 fn supersteps_use_canonical_full_width_decimal_text() {
1868 for (text, expected) in [
1869 ("0", Superstep::INITIAL),
1870 ("1", Superstep::new(1).unwrap()),
1871 ("9223372036854775807", Superstep::MAX),
1872 ] {
1873 let decoded = text.parse::<Superstep>().unwrap();
1874 assert_eq!(decoded, expected);
1875 assert_eq!(decoded.to_string(), text);
1876 assert_eq!(to_value(decoded).unwrap(), Value::from(text));
1877 }
1878
1879 for invalid in ["", "00", "01", "-1", "1.0", "9223372036854775808"] {
1880 assert!(invalid.parse::<Superstep>().is_err(), "accepted {invalid}");
1881 }
1882 assert!(from_value::<Superstep>(json!(0)).is_err());
1883 assert_eq!(Superstep::MAX.checked_next(), None);
1884 }
1885
1886 #[test]
1887 fn node_ids_and_ready_sets_are_bounded_unique_and_sorted() {
1888 for value in ["a", "Authorize", "order.capture-v2", "node_42"] {
1889 let node = NodeId::try_from(value).unwrap();
1890 assert_eq!(node.as_str(), value);
1891 assert_eq!(node.to_string(), value);
1892 }
1893 for invalid in ["", ".", "..", "_private", "node/name", "node name", "节点"] {
1894 assert!(NodeId::try_from(invalid).is_err(), "accepted {invalid:?}");
1895 }
1896 assert!(NodeId::new("a".repeat(NodeId::MAX_LEN)).is_ok());
1897 assert!(NodeId::new("a".repeat(NodeId::MAX_LEN + 1)).is_err());
1898
1899 let set = ready(&["z-last", "a-first", "middle"]);
1900 assert_eq!(set.len(), 3);
1901 assert!(set.contains(&NodeId::try_from("middle").unwrap()));
1902 assert_eq!(
1903 to_value(&set).unwrap(),
1904 json!(["a-first", "middle", "z-last"])
1905 );
1906 assert!(from_value::<ReadyNodes>(json!(["same", "same"])).is_err());
1907
1908 let too_many =
1909 (0..=ReadyNodes::MAX_LEN).map(|index| NodeId::new(format!("node-{index:04}")).unwrap());
1910 assert_eq!(
1911 ReadyNodes::try_new(too_many),
1912 Err(ReadyNodesError::TooMany {
1913 maximum: ReadyNodes::MAX_LEN,
1914 actual: ReadyNodes::MAX_LEN + 1,
1915 })
1916 );
1917 }
1918
1919 #[test]
1920 fn state_digest_binds_schema_and_canonical_json() {
1921 let schema = state_schema(b"schema-a");
1922 let first = CheckpointState::new(
1923 schema.clone(),
1924 BoundedJson::from_str(r#"{"z":0,"a":[true,{"name":"é"}]}"#).unwrap(),
1925 )
1926 .unwrap();
1927 let equivalent = CheckpointState::new(
1928 schema.clone(),
1929 BoundedJson::from_str(" { \"a\" : [ true, { \"name\" : \"é\" } ], \"z\" : -0.0 }")
1930 .unwrap(),
1931 )
1932 .unwrap();
1933 assert_eq!(first.digest(), equivalent.digest());
1934
1935 let different_schema =
1936 CheckpointState::new(state_schema(b"schema-b"), equivalent.data().clone()).unwrap();
1937 assert_ne!(first.digest(), different_schema.digest());
1938
1939 let mut tampered = to_value(&first).unwrap();
1940 tampered["data"]["z"] = json!(1);
1941 assert!(from_value::<CheckpointState>(tampered).is_err());
1942
1943 let unsafe_integer = BoundedJson::from_str("9007199254740992").unwrap();
1944 assert!(matches!(
1945 CheckpointState::new(schema, unsafe_integer),
1946 Err(CheckpointStateError::Integrity { .. })
1947 ));
1948 }
1949
1950 #[test]
1951 fn checkpoint_state_deserialization_uses_the_explicit_two_mib_ceiling() {
1952 let large_data = BoundedJson::from_str_with_limits(
1953 &format!("\"{}\"", "x".repeat(JsonLimits::DEFAULT.max_bytes() + 1)),
1954 JsonLimits::MAXIMUM,
1955 )
1956 .unwrap();
1957 let state = CheckpointState::new(state_schema(b"large-state"), large_data).unwrap();
1958 let encoded = serde_json::to_vec(&state).unwrap();
1959 let decoded = serde_json::from_slice::<CheckpointState>(&encoded).unwrap();
1960 assert_eq!(decoded, state);
1961
1962 let oversized = json!({
1963 "schema": state_schema(b"oversized"),
1964 "data": "x".repeat(JsonLimits::MAXIMUM.max_string_bytes() + 1),
1965 "digest": Digest::sha256(b"irrelevant"),
1966 });
1967 assert!(from_value::<CheckpointState>(oversized).is_err());
1968 }
1969
1970 #[test]
1971 fn initial_checkpoint_round_trips_and_redacts_state() {
1972 let checkpoint = initial_checkpoint();
1973 assert_eq!(checkpoint.superstep(), Superstep::INITIAL);
1974 assert!(checkpoint.parent().is_none());
1975 assert_eq!(checkpoint.journal_head().sequence(), JournalSequence::FIRST);
1976 assert_eq!(checkpoint.graph(), &graph());
1977 assert_eq!(
1978 checkpoint.ready_nodes(),
1979 &ready(&["authorize", "reserve-stock"])
1980 );
1981 assert!(checkpoint.matches_write(&checkpoint.write_intent()));
1982
1983 let encoded = to_value(&checkpoint).unwrap();
1984 assert_eq!(from_value::<Checkpoint>(encoded).unwrap(), checkpoint);
1985 assert_eq!(
1986 Checkpoint::restore(
1987 checkpoint.write_intent(),
1988 checkpoint.journal_head().clone(),
1989 checkpoint.digest(),
1990 )
1991 .unwrap(),
1992 checkpoint
1993 );
1994
1995 let debug = format!("{checkpoint:?}");
1996 assert!(debug.contains("CheckpointState"));
1997 assert!(!debug.contains("order-42"));
1998 assert!(!debug.contains("pending"));
1999 }
2000
2001 #[test]
2002 fn successor_is_contiguous_and_inherits_scope_and_graph() {
2003 let parent = initial_checkpoint();
2004 let write = CheckpointWrite::successor(
2005 checkpoint_id("d2"),
2006 &parent,
2007 state(json!({"status": "authorized"})),
2008 ready(&["capture-payment"]),
2009 )
2010 .unwrap();
2011 assert_eq!(write.superstep(), Superstep::new(1).unwrap());
2012 assert_eq!(write.tenant_id(), parent.tenant_id());
2013 assert_eq!(write.run_id(), parent.run_id());
2014 assert_eq!(write.graph(), parent.graph());
2015 assert_eq!(write.parent(), Some(&parent.head()));
2016
2017 let restored = CheckpointWrite::restore(
2018 write.tenant_id().clone(),
2019 write.run_id(),
2020 write.checkpoint_id(),
2021 write.superstep(),
2022 write.graph().clone(),
2023 write.state().clone(),
2024 write.ready_nodes().clone(),
2025 write.parent().cloned(),
2026 write.intent_digest(),
2027 )
2028 .unwrap();
2029 assert_eq!(restored, write);
2030
2031 let checkpoint = Checkpoint::commit(write, journal(3, at(3))).unwrap();
2032 assert_eq!(checkpoint.superstep(), Superstep::new(1).unwrap());
2033 assert_eq!(checkpoint.parent(), Some(&parent.head()));
2034 assert_eq!(checkpoint.journal_head().sequence().get(), 3);
2035 }
2036
2037 #[test]
2038 fn write_shape_rejects_schema_scope_position_graph_and_identity_changes() {
2039 let parent = initial_checkpoint();
2040 let wrong_schema_state = CheckpointState::new(
2041 state_schema(b"wrong-schema"),
2042 BoundedJson::try_from_value(json!({})).unwrap(),
2043 )
2044 .unwrap();
2045 assert_eq!(
2046 CheckpointWrite::successor(
2047 checkpoint_id("d2"),
2048 &parent,
2049 wrong_schema_state,
2050 ReadyNodes::empty(),
2051 ),
2052 Err(CheckpointWriteError::StateSchemaMismatch)
2053 );
2054 assert_eq!(
2055 CheckpointWrite::successor(
2056 parent.checkpoint_id(),
2057 &parent,
2058 state(json!({})),
2059 ReadyNodes::empty(),
2060 ),
2061 Err(CheckpointWriteError::ReusedCheckpointId)
2062 );
2063
2064 let valid = CheckpointWrite::successor(
2065 checkpoint_id("d2"),
2066 &parent,
2067 state(json!({})),
2068 ReadyNodes::empty(),
2069 )
2070 .unwrap();
2071 let mut wire = to_value(&valid).unwrap();
2072
2073 wire["superstep"] = json!("3");
2074 assert!(from_value::<CheckpointWrite>(wire.clone()).is_err());
2075 wire["superstep"] = json!("1");
2076
2077 wire["tenant_id"] = json!(other_tenant());
2078 assert!(from_value::<CheckpointWrite>(wire.clone()).is_err());
2079 wire["tenant_id"] = json!(tenant());
2080
2081 wire["run_id"] = json!(other_run());
2082 assert!(from_value::<CheckpointWrite>(wire.clone()).is_err());
2083 wire["run_id"] = json!(run());
2084
2085 wire["parent"]["graph"]["definition_digest"] = json!(Digest::sha256(b"other-graph"));
2086 assert!(from_value::<CheckpointWrite>(wire).is_err());
2087 }
2088
2089 #[test]
2090 fn committed_checkpoint_rejects_nonadvancing_or_regressing_journal_heads() {
2091 let parent = initial_checkpoint();
2092 let make_write = || {
2093 CheckpointWrite::successor(
2094 checkpoint_id("d2"),
2095 &parent,
2096 state(json!({"status": "next"})),
2097 ReadyNodes::empty(),
2098 )
2099 .unwrap()
2100 };
2101
2102 assert_eq!(
2103 Checkpoint::commit(make_write(), journal(1, at(2))),
2104 Err(CheckpointError::JournalDidNotAdvance {
2105 previous: JournalSequence::FIRST,
2106 actual: JournalSequence::FIRST,
2107 })
2108 );
2109 assert_eq!(
2110 Checkpoint::commit(make_write(), journal(2, at(0))),
2111 Err(CheckpointError::ClockRegression {
2112 previous: at(1),
2113 actual: at(0),
2114 })
2115 );
2116
2117 let crossed_tenant = JournalHead::new(
2118 other_tenant(),
2119 run(),
2120 JournalSequence::new(2).unwrap(),
2121 "01912345-6789-7abc-8def-012345678902".parse().unwrap(),
2122 at(2),
2123 Digest::sha256(b"other-tenant"),
2124 );
2125 assert_eq!(
2126 Checkpoint::commit(make_write(), crossed_tenant),
2127 Err(CheckpointError::JournalTenantMismatch)
2128 );
2129 }
2130
2131 #[test]
2132 fn every_integrity_layer_rejects_tampering() {
2133 let checkpoint = successor_checkpoint();
2134 let original = to_value(&checkpoint).unwrap();
2135
2136 let mut state_data = original.clone();
2137 state_data["state"]["data"]["status"] = json!("captured");
2138 assert!(from_value::<Checkpoint>(state_data).is_err());
2139
2140 let mut state_digest = original.clone();
2141 state_digest["state"]["digest"] = json!(Digest::sha256(b"wrong-state"));
2142 assert!(from_value::<Checkpoint>(state_digest).is_err());
2143
2144 let mut ready_nodes = original.clone();
2145 ready_nodes["ready_nodes"] = json!(["different-node"]);
2146 assert!(from_value::<Checkpoint>(ready_nodes).is_err());
2147
2148 let mut intent_digest = original.clone();
2149 intent_digest["intent_digest"] = json!(Digest::sha256(b"wrong-intent"));
2150 assert!(from_value::<Checkpoint>(intent_digest).is_err());
2151
2152 let mut journal_head = original.clone();
2153 journal_head["journal_head"]["digest"] = json!(Digest::sha256(b"wrong-journal"));
2154 assert!(from_value::<Checkpoint>(journal_head).is_err());
2155
2156 let mut digest = original;
2157 digest["digest"] = json!(Digest::sha256(b"wrong-checkpoint"));
2158 assert!(from_value::<Checkpoint>(digest).is_err());
2159 }
2160
2161 #[test]
2162 fn compact_head_enforces_scope_and_public_schemas_are_closed() {
2163 let checkpoint = initial_checkpoint();
2164 let head = checkpoint.head();
2165 assert_eq!(
2166 from_value::<CheckpointHead>(to_value(&head).unwrap()).unwrap(),
2167 head
2168 );
2169
2170 assert_eq!(
2171 CheckpointHead::new(
2172 tenant(),
2173 other_run(),
2174 checkpoint.checkpoint_id(),
2175 checkpoint.superstep(),
2176 checkpoint.graph().clone(),
2177 checkpoint.journal_head().clone(),
2178 checkpoint.digest(),
2179 ),
2180 Err(CheckpointHeadError::JournalRunMismatch)
2181 );
2182
2183 for schema in [
2184 to_value(schemars::schema_for!(GraphReference)).unwrap(),
2185 to_value(schemars::schema_for!(CheckpointState)).unwrap(),
2186 to_value(schemars::schema_for!(CheckpointHead)).unwrap(),
2187 to_value(schemars::schema_for!(CheckpointWrite)).unwrap(),
2188 to_value(schemars::schema_for!(Checkpoint)).unwrap(),
2189 ] {
2190 assert_eq!(schema["additionalProperties"], false);
2191 }
2192 let ready_schema = to_value(schemars::schema_for!(ReadyNodes)).unwrap();
2193 assert_eq!(ready_schema["maxItems"], ReadyNodes::MAX_LEN);
2194 assert_eq!(ready_schema["uniqueItems"], true);
2195 }
2196
2197 #[test]
2198 fn reverse_lineage_verifier_is_streaming_exact_and_transactional() {
2199 let root = initial_checkpoint();
2200 let tip = successor_checkpoint();
2201 let mut verifier = CheckpointLineageVerifier::from_tip(tip.head());
2202
2203 assert_eq!(verifier.expected(), Some(&tip.head()));
2204 assert_eq!(
2205 verifier.verify_next(&root),
2206 Err(CheckpointLineageError::HeadMismatch)
2207 );
2208 assert_eq!(
2209 verifier.expected(),
2210 Some(&tip.head()),
2211 "rejection must not advance the verifier"
2212 );
2213
2214 verifier.verify_next(&tip).unwrap();
2215 assert_eq!(verifier.expected(), Some(&root.head()));
2216 verifier.verify_next(&root).unwrap();
2217 assert!(verifier.is_complete());
2218 assert_eq!(verifier.expected(), None);
2219 assert_eq!(
2220 verifier.verify_next(&root),
2221 Err(CheckpointLineageError::AlreadyComplete)
2222 );
2223 }
2224
2225 proptest! {
2226 #[test]
2227 fn every_supported_superstep_round_trips(value in 0_u64..=MAX_DATABASE_ORDINAL) {
2228 let step = Superstep::new(value).unwrap();
2229 prop_assert_eq!(step.to_string().parse::<Superstep>().unwrap(), step);
2230 prop_assert_eq!(serde_json::from_value::<Superstep>(to_value(step).unwrap()).unwrap(), step);
2231 }
2232 }
2233}