Skip to main content

briefcase_core/models/
base.rs

1//! Core data models for AI decision tracking and observability
2
3use super::agent::AgentMetadata;
4use super::hardware::HardwareMetadata;
5use super::scorecard::{ExperimentMetadata, Scorecard};
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::collections::HashMap;
10use uuid::Uuid;
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
13pub struct Input {
14    pub name: String,
15    pub value: serde_json::Value,
16    pub data_type: String,
17    #[serde(default = "default_schema_version")]
18    pub schema_version: String,
19}
20
21impl Input {
22    pub fn new(
23        name: impl Into<String>,
24        value: serde_json::Value,
25        data_type: impl Into<String>,
26    ) -> Self {
27        Self {
28            name: name.into(),
29            value,
30            data_type: data_type.into(),
31            schema_version: default_schema_version(),
32        }
33    }
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub struct Output {
38    pub name: String,
39    pub value: serde_json::Value,
40    pub data_type: String,
41    pub confidence: Option<f64>,
42    #[serde(default = "default_schema_version")]
43    pub schema_version: String,
44}
45
46impl Output {
47    pub fn new(
48        name: impl Into<String>,
49        value: serde_json::Value,
50        data_type: impl Into<String>,
51    ) -> Self {
52        Self {
53            name: name.into(),
54            value,
55            data_type: data_type.into(),
56            confidence: None,
57            schema_version: default_schema_version(),
58        }
59    }
60    pub fn with_confidence(mut self, confidence: f64) -> Self {
61        self.confidence = Some(confidence.clamp(0.0, 1.0));
62        self
63    }
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
67pub struct ModelParameters {
68    pub model_name: String,
69    pub model_version: Option<String>,
70    pub provider: Option<String>,
71    #[serde(default)]
72    pub parameters: HashMap<String, serde_json::Value>,
73    #[serde(default)]
74    pub hyperparameters: HashMap<String, serde_json::Value>,
75    pub weights_hash: Option<String>,
76}
77
78impl ModelParameters {
79    pub fn new(model_name: impl Into<String>) -> Self {
80        Self {
81            model_name: model_name.into(),
82            model_version: None,
83            provider: None,
84            parameters: HashMap::new(),
85            hyperparameters: HashMap::new(),
86            weights_hash: None,
87        }
88    }
89    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
90        self.provider = Some(provider.into());
91        self
92    }
93    pub fn with_version(mut self, version: impl Into<String>) -> Self {
94        self.model_version = Some(version.into());
95        self
96    }
97    pub fn with_parameter(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
98        self.parameters.insert(key.into(), value);
99        self
100    }
101    pub fn with_hyperparameter(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
102        self.hyperparameters.insert(key.into(), value);
103        self
104    }
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
108pub struct ExecutionContext {
109    pub runtime_version: Option<String>,
110    #[serde(default)]
111    pub dependencies: HashMap<String, String>,
112    pub random_seed: Option<i64>,
113    #[serde(default)]
114    pub environment_variables: HashMap<String, String>,
115    #[serde(default)]
116    pub hardware_info: HashMap<String, serde_json::Value>,
117}
118
119impl ExecutionContext {
120    pub fn new() -> Self {
121        Self::default()
122    }
123    pub fn with_runtime_version(mut self, v: impl Into<String>) -> Self {
124        self.runtime_version = Some(v.into());
125        self
126    }
127    pub fn with_random_seed(mut self, s: i64) -> Self {
128        self.random_seed = Some(s);
129        self
130    }
131    pub fn with_dependency(mut self, n: impl Into<String>, v: impl Into<String>) -> Self {
132        self.dependencies.insert(n.into(), v.into());
133        self
134    }
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
138pub struct SnapshotMetadata {
139    pub snapshot_id: Uuid,
140    pub timestamp: DateTime<Utc>,
141    pub schema_version: String,
142    pub sdk_version: String,
143    pub created_by: Option<String>,
144    pub checksum: Option<String>,
145}
146
147impl Default for SnapshotMetadata {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153impl SnapshotMetadata {
154    pub fn new() -> Self {
155        Self {
156            snapshot_id: Uuid::new_v4(),
157            timestamp: Utc::now(),
158            schema_version: "1.0".to_string(),
159            sdk_version: "2.5.9".to_string(),
160            created_by: None,
161            checksum: None,
162        }
163    }
164    pub fn compute_checksum(&mut self, data: &[u8]) {
165        let mut hasher = Sha256::new();
166        hasher.update(data);
167        self.checksum = Some(format!("{:x}", hasher.finalize()));
168    }
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
172pub struct DecisionSnapshot {
173    pub metadata: SnapshotMetadata,
174    pub context: ExecutionContext,
175    pub function_name: String,
176    pub module_name: Option<String>,
177    pub inputs: Vec<Input>,
178    pub outputs: Vec<Output>,
179    pub model_parameters: Option<ModelParameters>,
180    pub execution_time_ms: Option<f64>,
181    pub error: Option<String>,
182    pub error_type: Option<String>,
183    pub scorecard: Option<Scorecard>,
184    pub experiment: Option<ExperimentMetadata>,
185    pub agent: Option<AgentMetadata>,
186    pub hardware: Option<HardwareMetadata>,
187    #[serde(default)]
188    pub tags: HashMap<String, String>,
189}
190
191impl DecisionSnapshot {
192    pub fn new(function_name: impl Into<String>) -> Self {
193        let mut s = Self {
194            metadata: SnapshotMetadata::new(),
195            context: ExecutionContext::new(),
196            function_name: function_name.into(),
197            module_name: None,
198            inputs: Vec::new(),
199            outputs: Vec::new(),
200            model_parameters: None,
201            execution_time_ms: None,
202            error: None,
203            error_type: None,
204            scorecard: None,
205            experiment: None,
206            agent: None,
207            hardware: None,
208            tags: HashMap::new(),
209        };
210        s.update_checksum();
211        s
212    }
213    pub fn with_module(mut self, m: impl Into<String>) -> Self {
214        self.module_name = Some(m.into());
215        self.update_checksum();
216        self
217    }
218    pub fn with_context(mut self, c: ExecutionContext) -> Self {
219        self.context = c;
220        self.update_checksum();
221        self
222    }
223    pub fn add_input(mut self, i: Input) -> Self {
224        self.inputs.push(i);
225        self.update_checksum();
226        self
227    }
228    pub fn add_output(mut self, o: Output) -> Self {
229        self.outputs.push(o);
230        self.update_checksum();
231        self
232    }
233    pub fn with_model_parameters(mut self, p: ModelParameters) -> Self {
234        self.model_parameters = Some(p);
235        self.update_checksum();
236        self
237    }
238    pub fn with_execution_time(mut self, t: f64) -> Self {
239        self.execution_time_ms = Some(t);
240        self.update_checksum();
241        self
242    }
243    pub fn with_error(mut self, e: impl Into<String>, et: Option<String>) -> Self {
244        self.error = Some(e.into());
245        self.error_type = et;
246        self.update_checksum();
247        self
248    }
249    pub fn with_scorecard(mut self, s: Scorecard) -> Self {
250        self.scorecard = Some(s);
251        self.update_checksum();
252        self
253    }
254    pub fn with_agent(mut self, a: AgentMetadata) -> Self {
255        self.agent = Some(a);
256        self.update_checksum();
257        self
258    }
259    pub fn with_hardware(mut self, h: HardwareMetadata) -> Self {
260        self.hardware = Some(h);
261        self.update_checksum();
262        self
263    }
264    pub fn add_tag(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
265        self.tags.insert(k.into(), v.into());
266        self.update_checksum();
267        self
268    }
269
270    fn update_checksum(&mut self) {
271        if let Ok(b) = serde_json::to_vec(self) {
272            self.metadata.compute_checksum(&b);
273        }
274    }
275    /// Hash of the question: function name, input names and values, and the
276    /// model name. Two decisions with the same inputs share a fingerprint
277    /// whatever they answered, which is what makes it useful for grouping and
278    /// lookup. To detect a changed answer, use [`Self::content_hash`].
279    pub fn fingerprint(&self) -> String {
280        let mut hasher = Sha256::new();
281        hasher.update(self.function_name.as_bytes());
282        for i in &self.inputs {
283            hasher.update(i.name.as_bytes());
284            hasher.update(
285                serde_json::to_string(&i.value)
286                    .unwrap_or_default()
287                    .as_bytes(),
288            );
289        }
290        if let Some(p) = &self.model_parameters {
291            hasher.update(p.model_name.as_bytes());
292        }
293        format!("{:x}", hasher.finalize())
294    }
295
296    /// Hash of everything that was decided: inputs, outputs, model parameters
297    /// and their values, module, tags, and any error.
298    ///
299    /// Volatile metadata (snapshot id, timestamps, execution time, the rolling
300    /// `metadata.checksum`) is excluded, so the digest depends only on content
301    /// and a verifier holding the record can recompute it. Map keys are sorted
302    /// so construction order does not change the result.
303    ///
304    /// The hash is unkeyed. It detects corruption and casual edits; anyone who
305    /// can rewrite the record can also recompute the digest, so store it
306    /// somewhere the record's holder cannot reach when it has to stand up to a
307    /// motivated party.
308    pub fn content_hash(&self) -> String {
309        let mut hasher = Sha256::new();
310        let mut field = |label: &str, value: &str| {
311            // Length-prefix each part so no concatenation of one field can
312            // impersonate another.
313            hasher.update(label.as_bytes());
314            hasher.update(value.len().to_le_bytes());
315            hasher.update(value.as_bytes());
316        };
317
318        field("function_name", &self.function_name);
319        field("module_name", self.module_name.as_deref().unwrap_or(""));
320
321        for i in &self.inputs {
322            field("input.name", &i.name);
323            field("input.type", &i.data_type);
324            field("input.value", &canonical_json(&i.value));
325        }
326        for o in &self.outputs {
327            field("output.name", &o.name);
328            field("output.type", &o.data_type);
329            field("output.value", &canonical_json(&o.value));
330            field(
331                "output.confidence",
332                &o.confidence.map(|c| c.to_string()).unwrap_or_default(),
333            );
334        }
335
336        if let Some(p) = &self.model_parameters {
337            field("model.name", &p.model_name);
338            field("model.version", p.model_version.as_deref().unwrap_or(""));
339            field("model.provider", p.provider.as_deref().unwrap_or(""));
340            for (k, v) in sorted_pairs(&p.parameters) {
341                field("model.param", k);
342                field("model.param.value", &canonical_json(v));
343            }
344            for (k, v) in sorted_pairs(&p.hyperparameters) {
345                field("model.hyper", k);
346                field("model.hyper.value", &canonical_json(v));
347            }
348        }
349
350        let mut tags: Vec<_> = self.tags.iter().collect();
351        tags.sort_by(|a, b| a.0.cmp(b.0));
352        for (k, v) in tags {
353            field("tag", k);
354            field("tag.value", v);
355        }
356
357        field("error", self.error.as_deref().unwrap_or(""));
358        field("error_type", self.error_type.as_deref().unwrap_or(""));
359
360        format!("{:x}", hasher.finalize())
361    }
362}
363
364/// Serialize a value with object keys sorted, so two structurally equal values
365/// hash the same however they were built.
366fn canonical_json(value: &serde_json::Value) -> String {
367    match value {
368        serde_json::Value::Object(map) => {
369            let mut keys: Vec<_> = map.keys().collect();
370            keys.sort();
371            let parts: Vec<String> = keys
372                .into_iter()
373                .map(|k| format!("{}:{}", k, canonical_json(&map[k])))
374                .collect();
375            format!("{{{}}}", parts.join(","))
376        }
377        serde_json::Value::Array(items) => {
378            let parts: Vec<String> = items.iter().map(canonical_json).collect();
379            format!("[{}]", parts.join(","))
380        }
381        other => other.to_string(),
382    }
383}
384
385fn sorted_pairs(map: &HashMap<String, serde_json::Value>) -> Vec<(&String, &serde_json::Value)> {
386    let mut pairs: Vec<_> = map.iter().collect();
387    pairs.sort_by(|a, b| a.0.cmp(b.0));
388    pairs
389}
390
391#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
392pub struct Snapshot {
393    pub metadata: SnapshotMetadata,
394    pub decisions: Vec<DecisionSnapshot>,
395    pub snapshot_type: SnapshotType,
396}
397
398impl Snapshot {
399    pub fn new(t: SnapshotType) -> Self {
400        let mut s = Self {
401            metadata: SnapshotMetadata::new(),
402            decisions: Vec::new(),
403            snapshot_type: t,
404        };
405        s.update_checksum();
406        s
407    }
408    pub fn add_decision(&mut self, d: DecisionSnapshot) {
409        self.decisions.push(d);
410        self.update_checksum();
411    }
412    pub fn with_created_by(mut self, c: impl Into<String>) -> Self {
413        self.metadata.created_by = Some(c.into());
414        self.update_checksum();
415        self
416    }
417    fn update_checksum(&mut self) {
418        if let Ok(b) = serde_json::to_vec(self) {
419            self.metadata.compute_checksum(&b);
420        }
421    }
422}
423
424#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
425pub enum SnapshotType {
426    Decision,
427    Batch,
428    Session,
429}
430
431fn default_schema_version() -> String {
432    "1.0".to_string()
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438    use serde_json::json;
439
440    fn decision(answer: &str) -> DecisionSnapshot {
441        DecisionSnapshot::new("classify_ticket")
442            .add_input(Input::new("text", json!("reset my password"), "string"))
443            .add_output(Output::new("category", json!(answer), "string"))
444            .with_model_parameters(
445                ModelParameters::new("claude-opus-4-5").with_parameter("temperature", json!(0.0)),
446            )
447    }
448
449    #[test]
450    fn fingerprint_identifies_the_inputs_not_the_answer() {
451        // Documented behavior: the fingerprint groups the same question asked twice.
452        assert_eq!(
453            decision("billing").fingerprint(),
454            decision("shipping").fingerprint()
455        );
456    }
457
458    #[test]
459    fn content_hash_covers_the_outputs() {
460        assert_ne!(
461            decision("billing").content_hash(),
462            decision("shipping").content_hash()
463        );
464    }
465
466    #[test]
467    fn content_hash_is_stable_for_identical_content() {
468        assert_eq!(
469            decision("billing").content_hash(),
470            decision("billing").content_hash()
471        );
472    }
473
474    #[test]
475    fn content_hash_ignores_construction_order() {
476        let a = DecisionSnapshot::new("f")
477            .add_input(Input::new("x", json!(1), "int"))
478            .with_module("m");
479        let b = DecisionSnapshot::new("f")
480            .with_module("m")
481            .add_input(Input::new("x", json!(1), "int"));
482        assert_eq!(a.content_hash(), b.content_hash());
483    }
484
485    #[test]
486    fn content_hash_covers_model_parameter_values() {
487        let cold = DecisionSnapshot::new("f").with_model_parameters(
488            ModelParameters::new("m").with_parameter("temperature", json!(0.0)),
489        );
490        let hot = DecisionSnapshot::new("f").with_model_parameters(
491            ModelParameters::new("m").with_parameter("temperature", json!(1.0)),
492        );
493        assert_ne!(cold.content_hash(), hot.content_hash());
494        // The fingerprint hashes only the model name, so it cannot see this.
495        assert_eq!(cold.fingerprint(), hot.fingerprint());
496    }
497
498    #[test]
499    fn content_hash_covers_tags_and_errors() {
500        let plain = decision("billing");
501        let tagged = decision("billing").add_tag("environment", "production");
502        let failed = decision("billing").with_error("boom", None);
503        assert_ne!(plain.content_hash(), tagged.content_hash());
504        assert_ne!(plain.content_hash(), failed.content_hash());
505    }
506
507    #[test]
508    fn content_hash_ignores_volatile_metadata() {
509        // Two records of the same decision differ in id and timestamp; the hash is
510        // over what was decided, so a verifier can recompute it from the content.
511        let a = decision("billing");
512        let mut b = decision("billing");
513        b.metadata.snapshot_id = uuid::Uuid::new_v4();
514        assert_eq!(a.content_hash(), b.content_hash());
515    }
516}