1use 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: env!("CARGO_PKG_VERSION").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 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 pub fn content_hash(&self) -> String {
316 self.content_hash_with(canonical_json)
317 }
318
319 pub fn content_hash_legacy(&self) -> String {
323 self.content_hash_with(legacy_canonical_json)
324 }
325
326 fn content_hash_with(&self, canonical_json: fn(&serde_json::Value) -> String) -> String {
327 let mut hasher = Sha256::new();
328 let mut field = |label: &str, value: &str| {
329 hasher.update(label.as_bytes());
332 hasher.update(value.len().to_le_bytes());
333 hasher.update(value.as_bytes());
334 };
335
336 field("function_name", &self.function_name);
337 field("module_name", self.module_name.as_deref().unwrap_or(""));
338
339 for i in &self.inputs {
340 field("input.name", &i.name);
341 field("input.type", &i.data_type);
342 field("input.value", &canonical_json(&i.value));
343 }
344 for o in &self.outputs {
345 field("output.name", &o.name);
346 field("output.type", &o.data_type);
347 field("output.value", &canonical_json(&o.value));
348 field(
349 "output.confidence",
350 &o.confidence.map(|c| c.to_string()).unwrap_or_default(),
351 );
352 }
353
354 if let Some(p) = &self.model_parameters {
355 field("model.name", &p.model_name);
356 field("model.version", p.model_version.as_deref().unwrap_or(""));
357 field("model.provider", p.provider.as_deref().unwrap_or(""));
358 for (k, v) in sorted_pairs(&p.parameters) {
359 field("model.param", k);
360 field("model.param.value", &canonical_json(v));
361 }
362 for (k, v) in sorted_pairs(&p.hyperparameters) {
363 field("model.hyper", k);
364 field("model.hyper.value", &canonical_json(v));
365 }
366 }
367
368 let mut tags: Vec<_> = self.tags.iter().collect();
369 tags.sort_by(|a, b| a.0.cmp(b.0));
370 for (k, v) in tags {
371 field("tag", k);
372 field("tag.value", v);
373 }
374
375 field("error", self.error.as_deref().unwrap_or(""));
376 field("error_type", self.error_type.as_deref().unwrap_or(""));
377
378 format!("{:x}", hasher.finalize())
379 }
380}
381
382fn canonical_json(value: &serde_json::Value) -> String {
386 match value {
387 serde_json::Value::Object(map) => {
388 let mut keys: Vec<_> = map.keys().collect();
389 keys.sort();
390 let parts: Vec<String> = keys
391 .into_iter()
392 .map(|k| {
393 let key = serde_json::Value::String(k.clone());
394 format!("{}:{}", key, canonical_json(&map[k]))
395 })
396 .collect();
397 format!("{{{}}}", parts.join(","))
398 }
399 serde_json::Value::Array(items) => {
400 let parts: Vec<String> = items.iter().map(canonical_json).collect();
401 format!("[{}]", parts.join(","))
402 }
403 other => other.to_string(),
405 }
406}
407
408fn legacy_canonical_json(value: &serde_json::Value) -> String {
412 match value {
413 serde_json::Value::Object(map) => {
414 let mut keys: Vec<_> = map.keys().collect();
415 keys.sort();
416 let parts: Vec<String> = keys
417 .into_iter()
418 .map(|k| format!("{}:{}", k, legacy_canonical_json(&map[k])))
419 .collect();
420 format!("{{{}}}", parts.join(","))
421 }
422 serde_json::Value::Array(items) => {
423 let parts: Vec<String> = items.iter().map(legacy_canonical_json).collect();
424 format!("[{}]", parts.join(","))
425 }
426 other => other.to_string(),
427 }
428}
429
430fn sorted_pairs(map: &HashMap<String, serde_json::Value>) -> Vec<(&String, &serde_json::Value)> {
431 let mut pairs: Vec<_> = map.iter().collect();
432 pairs.sort_by(|a, b| a.0.cmp(b.0));
433 pairs
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
437pub struct Snapshot {
438 pub metadata: SnapshotMetadata,
439 pub decisions: Vec<DecisionSnapshot>,
440 pub snapshot_type: SnapshotType,
441}
442
443impl Snapshot {
444 pub fn new(t: SnapshotType) -> Self {
445 let mut s = Self {
446 metadata: SnapshotMetadata::new(),
447 decisions: Vec::new(),
448 snapshot_type: t,
449 };
450 s.update_checksum();
451 s
452 }
453 pub fn add_decision(&mut self, d: DecisionSnapshot) {
454 self.decisions.push(d);
455 self.update_checksum();
456 }
457 pub fn with_created_by(mut self, c: impl Into<String>) -> Self {
458 self.metadata.created_by = Some(c.into());
459 self.update_checksum();
460 self
461 }
462 fn update_checksum(&mut self) {
463 if let Ok(b) = serde_json::to_vec(self) {
464 self.metadata.compute_checksum(&b);
465 }
466 }
467}
468
469#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
470pub enum SnapshotType {
471 Decision,
472 Batch,
473 Session,
474}
475
476fn default_schema_version() -> String {
477 "1.0".to_string()
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483 use serde_json::json;
484
485 fn decision(answer: &str) -> DecisionSnapshot {
486 DecisionSnapshot::new("classify_ticket")
487 .add_input(Input::new("text", json!("reset my password"), "string"))
488 .add_output(Output::new("category", json!(answer), "string"))
489 .with_model_parameters(
490 ModelParameters::new("claude-opus-4-5").with_parameter("temperature", json!(0.0)),
491 )
492 }
493
494 #[test]
495 fn fingerprint_identifies_the_inputs_not_the_answer() {
496 assert_eq!(
498 decision("billing").fingerprint(),
499 decision("shipping").fingerprint()
500 );
501 }
502
503 #[test]
504 fn content_hash_covers_the_outputs() {
505 assert_ne!(
506 decision("billing").content_hash(),
507 decision("shipping").content_hash()
508 );
509 }
510
511 #[test]
512 fn content_hash_is_stable_for_identical_content() {
513 assert_eq!(
514 decision("billing").content_hash(),
515 decision("billing").content_hash()
516 );
517 }
518
519 #[test]
520 fn content_hash_ignores_construction_order() {
521 let a = DecisionSnapshot::new("f")
522 .add_input(Input::new("x", json!(1), "int"))
523 .with_module("m");
524 let b = DecisionSnapshot::new("f")
525 .with_module("m")
526 .add_input(Input::new("x", json!(1), "int"));
527 assert_eq!(a.content_hash(), b.content_hash());
528 }
529
530 #[test]
531 fn content_hash_covers_model_parameter_values() {
532 let cold = DecisionSnapshot::new("f").with_model_parameters(
533 ModelParameters::new("m").with_parameter("temperature", json!(0.0)),
534 );
535 let hot = DecisionSnapshot::new("f").with_model_parameters(
536 ModelParameters::new("m").with_parameter("temperature", json!(1.0)),
537 );
538 assert_ne!(cold.content_hash(), hot.content_hash());
539 assert_eq!(cold.fingerprint(), hot.fingerprint());
541 }
542
543 #[test]
544 fn content_hash_covers_tags_and_errors() {
545 let plain = decision("billing");
546 let tagged = decision("billing").add_tag("environment", "production");
547 let failed = decision("billing").with_error("boom", None);
548 assert_ne!(plain.content_hash(), tagged.content_hash());
549 assert_ne!(plain.content_hash(), failed.content_hash());
550 }
551
552 #[test]
553 fn sdk_version_is_the_crate_version() {
554 assert_eq!(
555 SnapshotMetadata::new().sdk_version,
556 env!("CARGO_PKG_VERSION")
557 );
558 }
559
560 #[test]
561 fn canonical_json_quotes_and_escapes_keys() {
562 let crafted = json!({"a:1,b": 2});
563 let plain = json!({"a": 1, "b": 2});
564 assert_eq!(canonical_json(&plain), r#"{"a":1,"b":2}"#);
565 assert_eq!(canonical_json(&crafted), r#"{"a:1,b":2}"#);
566 assert_eq!(canonical_json(&json!({"q\"k": "v\n"})), r#"{"q\"k":"v\n"}"#);
567 let nested = json!({"z": [1, {"y": null, "x": "s"}], "a": true});
569 let reparsed: serde_json::Value = serde_json::from_str(&canonical_json(&nested)).unwrap();
570 assert_eq!(reparsed, nested);
571 }
572
573 #[test]
574 fn content_hash_separates_values_the_legacy_form_conflated() {
575 let with = |v: serde_json::Value| {
576 DecisionSnapshot::new("f").add_input(Input::new("x", v, "object"))
577 };
578 let crafted = with(json!({"a:1,b": 2}));
579 let plain = with(json!({"a": 1, "b": 2}));
580
581 assert_eq!(crafted.content_hash_legacy(), plain.content_hash_legacy());
582 assert_ne!(crafted.content_hash(), plain.content_hash());
583 }
584
585 #[test]
586 fn content_hash_is_unchanged_for_values_without_objects() {
587 let d = decision("billing");
590 assert_eq!(d.content_hash(), d.content_hash_legacy());
591 }
592
593 #[test]
594 fn content_hash_ignores_volatile_metadata() {
595 let a = decision("billing");
598 let mut b = decision("billing");
599 b.metadata.snapshot_id = uuid::Uuid::new_v4();
600 assert_eq!(a.content_hash(), b.content_hash());
601 }
602}