Skip to main content

logit_loom_core/
generation.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Generation result accounting.
4
5use serde::{Deserialize, Serialize};
6
7use crate::{CoreError, Digest, TokenId};
8
9/// Why one bounded generation call stopped.
10#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case", tag = "kind")]
12pub enum GenerationFinish {
13    /// The model selected an end-of-generation token.
14    EndOfGeneration {
15        /// Selected terminal token, which was not admitted to causal state.
16        token: TokenId,
17    },
18    /// The caller's token limit was reached.
19    TokenLimit,
20    /// An exact byte stop suffix was causally generated.
21    StopSequence {
22        /// Zero-based stop index in the generation plan.
23        index: u32,
24    },
25    /// A Rust observer requested a cooperative stop.
26    ObserverStop,
27}
28
29/// Mechanical receipt for one bounded generation call.
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31pub struct GenerationReceipt {
32    /// Exact generation-plan identity.
33    pub plan: Digest,
34    /// Position before generation.
35    pub initial_position: u64,
36    /// Causally admitted generated tokens.
37    pub admitted_tokens: u32,
38    /// Exact generated token-byte count.
39    pub admitted_bytes: u64,
40    /// Final causal position.
41    pub final_position: u64,
42    /// Terminal disposition.
43    pub finish: GenerationFinish,
44    /// Optional transform-pipeline receipt identity.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub transform_receipt: Option<Digest>,
47    /// Ordered observer receipt identities.
48    #[serde(default)]
49    pub observer_receipts: Vec<Digest>,
50}
51
52impl GenerationReceipt {
53    /// Validates position progression and returns a content identity.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error for inconsistent accounting or failed serialization.
58    pub fn digest(&self) -> Result<Digest, CoreError> {
59        let expected_position = self
60            .initial_position
61            .checked_add(u64::from(self.admitted_tokens))
62            .ok_or_else(|| {
63                CoreError::invalid("generation receipt", "causal position overflowed")
64            })?;
65        if self.final_position != expected_position {
66            return Err(CoreError::invalid(
67                "generation receipt",
68                "position does not match admitted tokens",
69            ));
70        }
71        Digest::of_serializable("generation-receipt-v1", self)
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn generation_receipts_reject_position_overflow() {
81        let receipt = GenerationReceipt {
82            plan: Digest::of_bytes("test-plan", b"one"),
83            initial_position: u64::MAX,
84            admitted_tokens: 1,
85            admitted_bytes: 1,
86            final_position: u64::MAX,
87            finish: GenerationFinish::TokenLimit,
88            transform_receipt: None,
89            observer_receipts: Vec::new(),
90        };
91        assert!(receipt.digest().is_err());
92    }
93}