Skip to main content

logit_loom_core/
state.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Content-bound checkpoint accounting.
4
5use serde::{Deserialize, Serialize};
6
7use crate::{CoreError, Digest};
8
9/// Serializable compatibility metadata for one backend-owned causal checkpoint.
10#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
11pub struct CheckpointReceipt {
12    /// Exact model artifact identity.
13    pub model: Digest,
14    /// Backend and compatibility identity.
15    pub backend: Digest,
16    /// Digest of the opaque state bytes.
17    pub state: Digest,
18    /// Number of opaque state bytes.
19    pub state_bytes: u64,
20    /// Digest of the exact causal token history.
21    pub token_history: Digest,
22    /// Causal token count and next native position.
23    pub position: u64,
24}
25
26impl CheckpointReceipt {
27    /// Validates backend-independent checkpoint accounting.
28    ///
29    /// # Errors
30    ///
31    /// Returns an error when no opaque state bytes were recorded.
32    pub fn validate(&self) -> Result<(), CoreError> {
33        if self.state_bytes == 0 {
34            return Err(CoreError::invalid(
35                "checkpoint receipt",
36                "opaque state byte count must be greater than zero",
37            ));
38        }
39        Ok(())
40    }
41
42    /// Returns a content identity for this checkpoint metadata.
43    ///
44    /// # Errors
45    ///
46    /// Returns a validation or serialization error.
47    pub fn digest(&self) -> Result<Digest, CoreError> {
48        self.validate()?;
49        Digest::of_serializable("checkpoint-receipt-v2", self)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn checkpoint_receipts_require_native_state_bytes() {
59        let identity = Digest::of_bytes("test-checkpoint", b"one");
60        let receipt = CheckpointReceipt {
61            model: identity.clone(),
62            backend: identity.clone(),
63            state: identity.clone(),
64            state_bytes: 0,
65            token_history: identity,
66            position: 0,
67        };
68        assert!(receipt.digest().is_err());
69    }
70
71    #[test]
72    fn checkpoint_receipts_use_the_v2_digest_domain() {
73        let identity = Digest::of_bytes("test-checkpoint", b"two");
74        let receipt = CheckpointReceipt {
75            model: identity.clone(),
76            backend: identity.clone(),
77            state: identity.clone(),
78            state_bytes: 1,
79            token_history: identity,
80            position: 0,
81        };
82        assert_eq!(
83            receipt.digest().unwrap(),
84            Digest::of_serializable("checkpoint-receipt-v2", &receipt).unwrap()
85        );
86    }
87}