Skip to main content

logit_loom_core/
steering.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Reversible session-steering descriptors and lifecycle receipts.
4
5use serde::{Deserialize, Serialize};
6
7use crate::{CoreError, Digest};
8
9/// One model-compatible `LoRA` adapter application.
10#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
11pub struct LoraSpec {
12    /// Adapter artifact identity.
13    pub artifact: Digest,
14    /// Finite native scale.
15    pub scale: f32,
16}
17
18impl LoraSpec {
19    /// Validates a finite, nonzero scale.
20    ///
21    /// # Errors
22    ///
23    /// Returns an error for zero, NaN, or infinite scale.
24    pub fn validate(&self) -> Result<(), CoreError> {
25        if !self.scale.is_finite() {
26            return Err(CoreError::NonFinite {
27                field: "LoRA scale",
28            });
29        }
30        if self.scale == 0.0 {
31            return Err(CoreError::invalid("LoRA scale", "must be nonzero"));
32        }
33        Ok(())
34    }
35
36    /// Returns a content identity for this exact application.
37    ///
38    /// # Errors
39    ///
40    /// Returns a validation or serialization error.
41    pub fn digest(&self) -> Result<Digest, CoreError> {
42        self.validate()?;
43        Digest::of_serializable("lora-spec-v1", self)
44    }
45}
46
47/// One in-memory control-vector application.
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49pub struct ControlVectorSpec {
50    /// Exact native `f32` data identity.
51    pub data: Digest,
52    /// Values per model layer.
53    pub embedding_width: u32,
54    /// Inclusive first model layer; layer zero is not steerable.
55    pub layer_start: i32,
56    /// Inclusive final model layer.
57    pub layer_end: i32,
58}
59
60impl ControlVectorSpec {
61    /// Validates width and the inclusive layer range.
62    ///
63    /// # Errors
64    ///
65    /// Returns an error for a zero width or malformed layer range.
66    pub fn validate(&self) -> Result<(), CoreError> {
67        if self.embedding_width == 0 || self.layer_start < 1 || self.layer_end < self.layer_start {
68            return Err(CoreError::invalid(
69                "control vector",
70                "embedding width must be nonzero and inclusive layer range must start at one",
71            ));
72        }
73        Ok(())
74    }
75
76    /// Returns a content identity for this exact application.
77    ///
78    /// # Errors
79    ///
80    /// Returns a validation or serialization error.
81    pub fn digest(&self) -> Result<Digest, CoreError> {
82        self.validate()?;
83        Digest::of_serializable("control-vector-spec-v1", self)
84    }
85}
86
87/// Session steering resource kind.
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum SteeringKind {
91    /// A `LoRA` adapter.
92    Lora,
93    /// A control vector.
94    ControlVector,
95}
96
97/// Lifecycle action recorded at the Rust/native boundary.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "snake_case")]
100pub enum SteeringAction {
101    /// Resource became active.
102    Applied,
103    /// Resource was explicitly cleared.
104    Cleared,
105}
106
107/// Mechanical receipt for one steering lifecycle transition.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct SteeringReceipt {
110    /// Resource kind.
111    pub kind: SteeringKind,
112    /// Resource descriptor identity.
113    pub resource: Digest,
114    /// Lifecycle action.
115    pub action: SteeringAction,
116    /// Causal position at the transition.
117    pub position: u64,
118}
119
120impl SteeringReceipt {
121    /// Returns a content identity for this transition.
122    ///
123    /// # Errors
124    ///
125    /// Returns a serialization error.
126    pub fn digest(&self) -> Result<Digest, CoreError> {
127        Digest::of_serializable("steering-receipt-v1", self)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn control_vector_uses_an_inclusive_nonzero_layer_range() {
137        let data = Digest::of_bytes("test-vector", b"one");
138        let valid = ControlVectorSpec {
139            data: data.clone(),
140            embedding_width: 4,
141            layer_start: 1,
142            layer_end: 1,
143        };
144        assert!(valid.validate().is_ok());
145        assert!(
146            ControlVectorSpec {
147                data,
148                embedding_width: 4,
149                layer_start: 0,
150                layer_end: 1,
151            }
152            .validate()
153            .is_err()
154        );
155    }
156
157    #[test]
158    fn lora_scale_must_be_finite_and_nonzero() {
159        let artifact = Digest::of_bytes("test-lora", b"one");
160        for scale in [0.0, f32::NAN, f32::INFINITY] {
161            assert!(
162                LoraSpec {
163                    artifact: artifact.clone(),
164                    scale,
165                }
166                .validate()
167                .is_err()
168            );
169        }
170    }
171}