1use std::collections::BTreeMap;
8
9use anyhow::{Result, anyhow};
10use lean_ctx_protocol::{
11 ContextBalanceV1, EvidenceKind, EvidenceRefV1, ExecutionReceiptV1, PlanId, ReceiptId,
12 SignatureStatus, TaskId,
13};
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value};
16
17pub use super::provider_normalization::NormalizedUsage;
18
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub struct ModelInvocation {
26 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub requested_model: Option<String>,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub selected_model: Option<String>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub model: Option<String>,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub provider: Option<String>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub latency_ms: Option<u64>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub actual_cost_micros: Option<u64>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub baseline_cost_micros: Option<u64>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub retries: Option<u32>,
45}
46
47impl ModelInvocation {
48 #[must_use]
50 pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
51 let model = model.into();
52 Self {
53 provider: Some(provider.into()),
54 selected_model: Some(model.clone()),
55 model: Some(model),
56 ..Self::default()
57 }
58 }
59
60 #[must_use]
61 pub fn with_requested_model(mut self, model: impl Into<String>) -> Self {
62 self.requested_model = Some(model.into());
63 self
64 }
65
66 #[must_use]
67 pub fn with_latency_ms(mut self, latency_ms: u64) -> Self {
68 self.latency_ms = Some(latency_ms);
69 self
70 }
71
72 #[must_use]
73 pub fn with_actual_cost_micros(mut self, cost_micros: u64) -> Self {
74 self.actual_cost_micros = Some(cost_micros);
75 self
76 }
77
78 #[must_use]
79 pub fn with_baseline_cost_micros(mut self, cost_micros: u64) -> Self {
80 self.baseline_cost_micros = Some(cost_micros);
81 self
82 }
83
84 #[must_use]
85 pub fn with_retries(mut self, retries: u32) -> Self {
86 self.retries = Some(retries);
87 self
88 }
89
90 fn selected_model(&self) -> Option<&str> {
91 self.selected_model
92 .as_deref()
93 .or(self.model.as_deref())
94 .filter(|model| !model.trim().is_empty())
95 }
96}
97
98#[derive(Debug, Clone)]
100pub struct ReceiptBuilder {
101 task_id: String,
102 plan_id: Option<String>,
103 context_balance: Option<ContextBalanceV1>,
104 provider_usage: Option<NormalizedUsage>,
105 model_invocations: Vec<ModelInvocation>,
106 knowledge_refs: Vec<String>,
107 decision_refs: Vec<String>,
108 evidence_refs: Vec<EvidenceRefV1>,
109}
110
111impl ReceiptBuilder {
112 #[must_use]
114 pub fn new(task_id: String) -> Self {
115 Self {
116 task_id,
117 plan_id: None,
118 context_balance: None,
119 provider_usage: None,
120 model_invocations: Vec::new(),
121 knowledge_refs: Vec::new(),
122 decision_refs: Vec::new(),
123 evidence_refs: Vec::new(),
124 }
125 }
126
127 #[must_use]
128 pub fn with_plan(mut self, plan_id: String) -> Self {
129 self.plan_id = Some(plan_id);
130 self
131 }
132
133 #[must_use]
135 pub fn add_context_balance(mut self, balance: ContextBalanceV1) -> Self {
136 self.context_balance = Some(match self.context_balance.take() {
137 Some(ref existing) => merge_balances(existing, &balance),
138 None => balance,
139 });
140 self
141 }
142
143 #[must_use]
145 pub fn add_provider_usage(mut self, usage: NormalizedUsage) -> Self {
146 match self.provider_usage.as_mut() {
147 Some(existing) => existing.merge_additive(&usage),
148 None => self.provider_usage = Some(usage),
149 }
150 self
151 }
152
153 #[must_use]
154 pub fn add_model_invocation(mut self, invocation: ModelInvocation) -> Self {
155 self.model_invocations.push(invocation);
156 self
157 }
158
159 #[must_use]
161 pub fn with_knowledge_refs(mut self, refs: Vec<String>) -> Self {
162 self.knowledge_refs = refs;
163 self
164 }
165
166 #[must_use]
167 pub fn add_decision_ref(mut self, ref_id: String) -> Self {
168 if !ref_id.trim().is_empty() {
169 self.decision_refs.push(ref_id);
170 }
171 self
172 }
173
174 #[must_use]
176 pub fn add_evidence_ref(mut self, ref_id: String) -> Self {
177 if !ref_id.trim().is_empty() {
178 self.evidence_refs.push(evidence_ref_for_id(ref_id));
179 }
180 self
181 }
182
183 pub fn build(self) -> Result<ExecutionReceiptV1> {
185 let task_id = TaskId::try_from(self.task_id).map_err(|error| anyhow!(error.to_string()))?;
186 let plan_text = self
187 .plan_id
188 .unwrap_or_else(|| format!("plan:{}", task_id.as_str()));
189 let plan_id = PlanId::try_from(plan_text).map_err(|error| anyhow!(error.to_string()))?;
190 let balance = self.context_balance.unwrap_or_else(zero_balance);
191 balance
192 .validate()
193 .map_err(|error| anyhow!(error.to_string()))?;
194
195 let usage = self.provider_usage.unwrap_or_default();
196 let invocation_model = self
197 .model_invocations
198 .iter()
199 .rev()
200 .find_map(ModelInvocation::selected_model);
201 let selected_model = invocation_model
202 .or_else(|| non_empty(&usage.model))
203 .unwrap_or("unknown")
204 .to_owned();
205 let requested_model = self
206 .model_invocations
207 .iter()
208 .rev()
209 .find_map(|invocation| invocation.requested_model.as_deref())
210 .or(usage.requested_model.as_deref())
211 .unwrap_or(&selected_model)
212 .to_owned();
213 let provider = self
214 .model_invocations
215 .iter()
216 .rev()
217 .find_map(|invocation| invocation.provider.as_deref().and_then(non_empty))
218 .or_else(|| non_empty(&usage.provider))
219 .unwrap_or("unknown")
220 .to_owned();
221
222 let model_calls = usage
223 .total_model_calls
224 .or_else(|| u32::try_from(self.model_invocations.len()).ok())
225 .unwrap_or(0);
226 let retries = usage.retries.unwrap_or_else(|| {
227 self.model_invocations
228 .iter()
229 .filter_map(|invocation| invocation.retries)
230 .fold(0u32, u32::saturating_add)
231 });
232 let latency_ms = usage.latency_ms.unwrap_or_else(|| {
233 self.model_invocations
234 .iter()
235 .filter_map(|invocation| invocation.latency_ms)
236 .fold(0u64, u64::saturating_add)
237 });
238 let actual_cost = aggregate_actual_cost(&usage, &self.model_invocations);
239 let baseline_cost = aggregate_baseline_cost(&self.model_invocations);
240 let avoided_cost = match (actual_cost, baseline_cost) {
241 (Some(actual), Some(baseline)) => Some(baseline.saturating_sub(actual)),
242 _ => None,
243 };
244
245 let mut evidence_refs = self.evidence_refs;
250 evidence_refs.sort_unstable_by(|left, right| {
251 (left.digest.as_str(), left.uri.as_str())
252 .cmp(&(right.digest.as_str(), right.uri.as_str()))
253 });
254 evidence_refs.dedup_by(|left, right| left.digest == right.digest);
255
256 let mut decision_refs = self.decision_refs;
257 decision_refs.sort_unstable();
258 decision_refs.dedup();
259
260 let mut knowledge_refs = self.knowledge_refs;
261 knowledge_refs.retain(|reference| !reference.trim().is_empty());
262 knowledge_refs.sort_unstable();
263 knowledge_refs.dedup();
264
265 let mut receipt = ExecutionReceiptV1 {
266 schema_version: 1,
267 receipt_id: ReceiptId::try_from("pending".to_owned())
268 .map_err(|error| anyhow!(error.to_string()))?,
269 task_id,
270 plan_id,
271 context_balance: balance,
272 fresh_input_tokens: usage.fresh_input_tokens.unwrap_or(0),
273 cached_input_tokens: usage.cached_input_tokens.unwrap_or(0),
274 output_tokens: usage.output_tokens.unwrap_or(0),
275 reasoning_tokens: usage.reasoning_tokens.unwrap_or(0),
276 requested_model,
277 selected_model,
278 provider,
279 capability_id: None,
280 capability_version: None,
281 model_calls,
282 retries,
283 latency_ms,
284 actual_cost_micros: actual_cost.unwrap_or(0),
285 baseline_cost_micros: baseline_cost.unwrap_or(0),
286 avoided_cost_micros: avoided_cost.unwrap_or(0),
287 etpao_milli: 0,
288 outcome_ref: None,
289 knowledge_refs,
290 decision_refs,
291 evidence_refs,
292 signature: String::new(),
293 };
294
295 let receipt_id = blake3::hash(&canonical_bytes(&receipt, true))
296 .to_hex()
297 .to_string();
298 receipt.receipt_id =
299 ReceiptId::try_from(receipt_id).map_err(|error| anyhow!(error.to_string()))?;
300 receipt.signature = Self::sign(&receipt);
301 receipt
302 .validate()
303 .map_err(|error| anyhow!(error.to_string()))?;
304 Ok(receipt)
305 }
306
307 #[must_use]
309 pub fn sign(receipt: &ExecutionReceiptV1) -> String {
310 let bytes = canonical_bytes(receipt, false);
311 blake3::hash(&bytes).to_hex().to_string()
312 }
313
314 pub fn canonical_bytes(receipt: &ExecutionReceiptV1) -> Vec<u8> {
316 canonical_bytes(receipt, false)
317 }
318}
319
320fn zero_balance() -> ContextBalanceV1 {
321 ContextBalanceV1 {
322 original_tokens: 0,
323 materialized_tokens: 0,
324 delivered_tokens: 0,
325 provider_billed_tokens: 0,
326 }
327}
328
329fn merge_balances(left: &ContextBalanceV1, right: &ContextBalanceV1) -> ContextBalanceV1 {
330 ContextBalanceV1 {
331 original_tokens: left.original_tokens.saturating_add(right.original_tokens),
332 materialized_tokens: left
333 .materialized_tokens
334 .saturating_add(right.materialized_tokens),
335 delivered_tokens: left.delivered_tokens.saturating_add(right.delivered_tokens),
336 provider_billed_tokens: left
337 .provider_billed_tokens
338 .saturating_add(right.provider_billed_tokens),
339 }
340}
341
342fn non_empty(value: &str) -> Option<&str> {
343 (!value.trim().is_empty()).then_some(value)
344}
345
346fn aggregate_actual_cost(usage: &NormalizedUsage, invocations: &[ModelInvocation]) -> Option<u64> {
347 let invocation_costs = if invocations.is_empty() {
348 None
349 } else {
350 invocations
351 .iter()
352 .map(|invocation| invocation.actual_cost_micros)
353 .try_fold(0u64, |total, cost| cost?.checked_add(total))
354 };
355 invocation_costs.or(usage.provider_cost_micros)
356}
357
358fn aggregate_baseline_cost(invocations: &[ModelInvocation]) -> Option<u64> {
359 if invocations.is_empty() {
360 return None;
361 }
362 invocations
363 .iter()
364 .map(|invocation| invocation.baseline_cost_micros)
365 .try_fold(0u64, |total, cost| cost?.checked_add(total))
366}
367
368fn evidence_ref_for_id(ref_id: String) -> EvidenceRefV1 {
369 let digest = if ref_id.starts_with("blake3:") || ref_id.starts_with("sha") {
370 ref_id.clone()
371 } else {
372 format!("blake3:{}", blake3::hash(ref_id.as_bytes()).to_hex())
373 };
374 EvidenceRefV1 {
375 kind: EvidenceKind::RuntimeLog,
376 uri: ref_id,
377 digest,
378 signature_status: SignatureStatus::NotSigned,
379 }
380}
381
382fn canonical_bytes(receipt: &ExecutionReceiptV1, exclude_receipt_id: bool) -> Vec<u8> {
383 let mut value = serde_json::to_value(receipt).expect("ExecutionReceiptV1 is serializable");
384 if let Value::Object(object) = &mut value {
385 object.remove("signature");
386 if exclude_receipt_id {
387 object.remove("receipt_id");
388 }
389 }
390 let value = canonicalize(value);
391 serde_json::to_vec(&value).expect("canonical receipt JSON is serializable")
392}
393
394fn canonicalize(value: Value) -> Value {
395 match value {
396 Value::Array(values) => Value::Array(values.into_iter().map(canonicalize).collect()),
397 Value::Object(values) => {
398 let sorted: BTreeMap<String, Value> = values.into_iter().collect();
399 let mut canonical = Map::new();
400 for (key, value) in sorted {
401 canonical.insert(key, canonicalize(value));
402 }
403 Value::Object(canonical)
404 }
405 value => value,
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use lean_ctx_protocol::ContextBalanceV1;
412
413 use super::{ModelInvocation, ReceiptBuilder};
414 use crate::core::context_kernel::provider_normalization::NormalizedUsage;
415
416 fn balance() -> ContextBalanceV1 {
417 ContextBalanceV1 {
418 original_tokens: 1_000,
419 materialized_tokens: 700,
420 delivered_tokens: 650,
421 provider_billed_tokens: 700,
422 }
423 }
424
425 #[test]
426 fn builds_minimal_receipt() {
427 let receipt = ReceiptBuilder::new("task-minimal".to_owned())
428 .with_plan("plan-minimal".to_owned())
429 .add_context_balance(balance())
430 .build()
431 .expect("minimal receipt should build");
432 assert_eq!(receipt.task_id.as_str(), "task-minimal");
433 assert_eq!(receipt.plan_id.as_str(), "plan-minimal");
434 assert_eq!(receipt.context_balance, balance());
435 assert_eq!(receipt.signature, ReceiptBuilder::sign(&receipt));
436 assert_eq!(receipt.receipt_id.as_str().len(), 64);
437 }
438
439 #[test]
440 fn builds_full_receipt_and_deduplicates_refs() {
441 let usage = NormalizedUsage::complete("openai", "gpt-used", 100, 25, 50, 10);
442 let invocation = ModelInvocation::new("openai", "gpt-used")
443 .with_requested_model("gpt-requested")
444 .with_latency_ms(42)
445 .with_actual_cost_micros(12)
446 .with_baseline_cost_micros(20)
447 .with_retries(1);
448 let receipt = ReceiptBuilder::new("task-full".to_owned())
449 .with_plan("plan-full".to_owned())
450 .add_context_balance(balance())
451 .add_provider_usage(usage)
452 .add_model_invocation(invocation)
453 .with_knowledge_refs(vec![
454 "knowledge:b".to_owned(),
455 "knowledge:a".to_owned(),
456 "knowledge:a".to_owned(),
457 ])
458 .add_decision_ref("decision:b".to_owned())
459 .add_decision_ref("decision:a".to_owned())
460 .add_decision_ref("decision:a".to_owned())
461 .add_evidence_ref("evidence:one".to_owned())
462 .build()
463 .expect("full receipt should build");
464
465 assert_eq!(receipt.fresh_input_tokens, 100);
466 assert_eq!(receipt.cached_input_tokens, 25);
467 assert_eq!(receipt.output_tokens, 50);
468 assert_eq!(receipt.reasoning_tokens, 10);
469 assert_eq!(receipt.requested_model, "gpt-requested");
470 assert_eq!(receipt.selected_model, "gpt-used");
471 assert_eq!(receipt.model_calls, 1);
472 assert_eq!(receipt.retries, 0);
473 assert_eq!(receipt.latency_ms, 42);
474 assert_eq!(receipt.actual_cost_micros, 12);
475 assert_eq!(receipt.baseline_cost_micros, 20);
476 assert_eq!(receipt.avoided_cost_micros, 8);
477 assert_eq!(receipt.knowledge_refs, ["knowledge:a", "knowledge:b"]);
478 assert_eq!(receipt.decision_refs, ["decision:a", "decision:b"]);
479 assert_eq!(receipt.evidence_refs.len(), 1);
480 }
481
482 #[test]
483 fn receipt_id_and_signature_are_deterministic_and_cover_fields() {
484 let make = || {
485 ReceiptBuilder::new("task-deterministic".to_owned())
486 .with_plan("plan-deterministic".to_owned())
487 .add_context_balance(balance())
488 .add_provider_usage(NormalizedUsage::complete("openai", "gpt", 1, 2, 3, 4))
489 .build()
490 .expect("receipt should build")
491 };
492 let first = make();
493 let second = make();
494 assert_eq!(first.receipt_id, second.receipt_id);
495 assert_eq!(first.signature, second.signature);
496
497 let mut changed = first.clone();
498 changed.output_tokens += 1;
499 assert_ne!(ReceiptBuilder::sign(&first), ReceiptBuilder::sign(&changed));
500 }
501
502 #[test]
503 fn missing_normalized_provider_values_are_not_fabricated() {
504 let usage = NormalizedUsage {
505 provider: "openai".to_owned(),
506 model: "gpt".to_owned(),
507 output_tokens: None,
508 ..NormalizedUsage::default()
509 };
510 let receipt = ReceiptBuilder::new("task-unknown".to_owned())
511 .with_plan("plan-unknown".to_owned())
512 .add_provider_usage(usage)
513 .build()
514 .expect("unknown usage should still build");
515 assert_eq!(receipt.output_tokens, 0);
518 }
519}