lean_ctx/core/execution_ledger/
projection.rs1use lean_ctx_protocol::{
4 EvidenceKind, EvidenceRefV1, ExecutionReceiptV1, ReceiptId, SignatureStatus, TaskId,
5};
6use serde::{Deserialize, Deserializer, Serialize};
7
8use super::{Result, event::ExecutionEvent, store::ExecutionLedgerStore};
9
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct TaskCostSummary {
13 pub task_id: String,
14 pub total_tokens: u64,
15 pub total_tokens_in: u64,
16 pub total_tokens_out: u64,
17 pub cost_micros: u64,
18 pub total_cost_micros: u64,
19 pub model_calls: u32,
20 pub total_latency_ms: u64,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct CanonicalReceiptProjectionV1 {
29 pub task_id: String,
30 pub invocation_id: String,
31 pub receipt_id: String,
32 pub receipt_ref: String,
33 pub receipt_digest: String,
34 pub chain_id: String,
35 pub sequence_number: u64,
36 pub previous_receipt_id: Option<String>,
37}
38
39#[derive(Debug, Clone, PartialEq, Serialize)]
41#[serde(transparent)]
42pub struct LegacyReceiptProjectionV1 {
43 receipt: ExecutionReceiptV1,
44}
45
46impl<'de> Deserialize<'de> for LegacyReceiptProjectionV1 {
47 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
48 where
49 D: Deserializer<'de>,
50 {
51 let receipt = ExecutionReceiptV1::deserialize(deserializer)?;
52 receipt.validate().map_err(serde::de::Error::custom)?;
53 if receipt.outcome_ref.is_some()
54 || receipt
55 .evidence_refs
56 .iter()
57 .any(|evidence| evidence.signature_status == SignatureStatus::Verified)
58 {
59 return Err(serde::de::Error::custom(
60 "legacy receipt cannot carry outcome or verified-signature authority",
61 ));
62 }
63 Ok(Self { receipt })
64 }
65}
66
67impl LegacyReceiptProjectionV1 {
68 #[must_use]
70 pub const fn legacy_receipt(&self) -> &ExecutionReceiptV1 {
71 &self.receipt
72 }
73
74 #[must_use]
76 pub fn into_legacy_receipt(self) -> ExecutionReceiptV1 {
77 self.receipt
78 }
79}
80
81pub struct ExecutionProjection<'a> {
83 store: &'a ExecutionLedgerStore,
84}
85
86impl<'a> ExecutionProjection<'a> {
87 #[must_use]
88 pub const fn new(store: &'a ExecutionLedgerStore) -> Self {
89 Self { store }
90 }
91
92 #[must_use]
93 pub fn task_cost_summary(&self, task_id: &str) -> TaskCostSummary {
94 task_cost_summary_from_store(self.store, task_id)
95 }
96
97 #[must_use]
98 pub fn legacy_receipt_for_task(&self, task_id: &str) -> Option<LegacyReceiptProjectionV1> {
99 legacy_receipt_for_task_from_store(self.store, task_id)
100 }
101
102 #[must_use]
104 pub fn canonical_receipt_for_task(
105 &self,
106 task_id: &str,
107 ) -> Option<CanonicalReceiptProjectionV1> {
108 canonical_receipt_for_task_from_store(self.store, task_id)
109 }
110
111 pub fn canonical_receipt_for_task_verified(
113 &self,
114 task_id: &str,
115 ) -> Result<Option<CanonicalReceiptProjectionV1>> {
116 canonical_receipt_for_task_verified_from_store(self.store, task_id)
117 }
118}
119
120impl ExecutionLedgerStore {
121 #[must_use]
123 pub fn task_cost_summary(&self, task_id: &str) -> TaskCostSummary {
124 task_cost_summary_from_store(self, task_id)
125 }
126
127 #[must_use]
129 pub fn legacy_receipt_for_task(&self, task_id: &str) -> Option<LegacyReceiptProjectionV1> {
130 legacy_receipt_for_task_from_store(self, task_id)
131 }
132
133 #[must_use]
135 pub fn canonical_receipt_for_task(
136 &self,
137 task_id: &str,
138 ) -> Option<CanonicalReceiptProjectionV1> {
139 canonical_receipt_for_task_from_store(self, task_id)
140 }
141
142 pub fn canonical_receipt_for_task_verified(
144 &self,
145 task_id: &str,
146 ) -> Result<Option<CanonicalReceiptProjectionV1>> {
147 canonical_receipt_for_task_verified_from_store(self, task_id)
148 }
149}
150
151#[must_use]
155pub fn canonical_receipt_for_task_from_store(
156 store: &ExecutionLedgerStore,
157 task_id: &str,
158) -> Option<CanonicalReceiptProjectionV1> {
159 canonical_receipt_for_events(store.by_task(task_id))
160}
161
162pub fn canonical_receipt_for_task_verified_from_store(
164 store: &ExecutionLedgerStore,
165 task_id: &str,
166) -> Result<Option<CanonicalReceiptProjectionV1>> {
167 Ok(canonical_receipt_for_events(
168 store.by_task_verified(task_id)?,
169 ))
170}
171
172fn canonical_receipt_for_events(
173 events: Vec<ExecutionEvent>,
174) -> Option<CanonicalReceiptProjectionV1> {
175 events.into_iter().rev().find_map(|event| {
176 if let ExecutionEvent::CanonicalReceiptRecorded {
177 task_id,
178 invocation_id,
179 receipt_id,
180 receipt_ref,
181 receipt_digest,
182 receipt_chain_id,
183 receipt_sequence_number,
184 previous_receipt_id,
185 ..
186 } = event
187 {
188 Some(CanonicalReceiptProjectionV1 {
189 task_id,
190 invocation_id,
191 receipt_id,
192 receipt_ref,
193 receipt_digest,
194 chain_id: receipt_chain_id,
195 sequence_number: receipt_sequence_number,
196 previous_receipt_id,
197 })
198 } else {
199 None
200 }
201 })
202}
203
204#[must_use]
206pub fn task_cost_summary(task_id: &str) -> TaskCostSummary {
207 ExecutionLedgerStore::from_default().map_or_else(
208 |_| TaskCostSummary::default(),
209 |store| task_cost_summary_from_store(&store, task_id),
210 )
211}
212
213#[must_use]
215pub fn task_cost_summary_from_store(
216 store: &ExecutionLedgerStore,
217 task_id: &str,
218) -> TaskCostSummary {
219 let mut summary = TaskCostSummary {
220 task_id: task_id.to_owned(),
221 ..TaskCostSummary::default()
222 };
223
224 for event in store.by_task(task_id) {
225 let ExecutionEvent::ModelInvoked {
226 model,
227 tokens_in,
228 tokens_out,
229 latency_ms,
230 ..
231 } = event
232 else {
233 continue;
234 };
235 summary.total_tokens_in = summary.total_tokens_in.saturating_add(tokens_in);
236 summary.total_tokens_out = summary.total_tokens_out.saturating_add(tokens_out);
237 summary.total_tokens = summary
238 .total_tokens_in
239 .saturating_add(summary.total_tokens_out);
240 summary.model_calls = summary.model_calls.saturating_add(1);
241 summary.total_latency_ms = summary.total_latency_ms.saturating_add(latency_ms);
242 let cost = estimate_cost_micros(&model, tokens_in, tokens_out);
243 summary.cost_micros = summary.cost_micros.saturating_add(cost);
244 summary.total_cost_micros = summary.cost_micros;
245 }
246
247 summary
248}
249
250#[must_use]
256pub fn legacy_receipt_for_task(task_id: &str) -> Option<LegacyReceiptProjectionV1> {
257 ExecutionLedgerStore::from_default()
258 .ok()
259 .and_then(|store| legacy_receipt_for_task_from_store(&store, task_id))
260}
261
262#[must_use]
264pub fn legacy_receipt_for_task_from_store(
265 store: &ExecutionLedgerStore,
266 task_id: &str,
267) -> Option<LegacyReceiptProjectionV1> {
268 let events = store.by_task(task_id);
269 let task_id = TaskId::try_from(task_id.to_owned()).ok()?;
270
271 let mut plan_id = None;
272 let mut context_balance = None;
273 let mut receipt_identity: Option<(String, String, String)> = None;
274 let mut decision_refs = Vec::new();
275 let mut model_calls = 0_u32;
276 let mut total_input = 0_u64;
277 let mut total_output = 0_u64;
278 let mut total_latency = 0_u64;
279 let mut first_model = None;
280 let mut last_model = None;
281 let mut provider = None;
282 let mut has_canonical_receipt = false;
283
284 for event in events {
285 match event {
286 ExecutionEvent::PlanCreated { plan_id: value, .. } => plan_id = Some(value),
287 ExecutionEvent::ContextDelivered {
288 context_balance: value,
289 ..
290 } => context_balance = Some(value),
291 ExecutionEvent::ModelInvoked {
292 plan_id: invoked_plan,
293 model,
294 provider: invoked_provider,
295 tokens_in,
296 tokens_out,
297 latency_ms,
298 ..
299 } => {
300 if plan_id.is_none() {
301 plan_id = Some(invoked_plan);
302 }
303 model_calls = model_calls.saturating_add(1);
304 total_input = total_input.saturating_add(tokens_in);
305 total_output = total_output.saturating_add(tokens_out);
306 total_latency = total_latency.saturating_add(latency_ms);
307 if first_model.is_none() {
308 first_model = Some(model.clone());
309 }
310 last_model = Some(model);
311 provider = Some(invoked_provider);
312 }
313 ExecutionEvent::ReceiptSigned {
314 receipt_id,
315 receipt_hash,
316 signature,
317 ..
318 } => receipt_identity = Some((receipt_id, receipt_hash, signature)),
319 ExecutionEvent::DecisionRecorded { decision_id, .. } => decision_refs.push(decision_id),
320 ExecutionEvent::CanonicalReceiptRecorded { .. } => has_canonical_receipt = true,
321 ExecutionEvent::OutcomeRecorded { .. }
322 | ExecutionEvent::TaskStarted { .. }
323 | ExecutionEvent::EngineInvoked { .. } => {}
324 }
325 }
326
327 if has_canonical_receipt {
328 return None;
329 }
330
331 let plan_id = plan_id?;
332 let plan_id = lean_ctx_protocol::PlanId::try_from(plan_id).ok()?;
333 let context_balance = context_balance?;
334 let (receipt_id, receipt_hash, signature) = receipt_identity?;
335 let receipt_id = ReceiptId::try_from(receipt_id).ok()?;
336 let requested_model = first_model?;
337 let selected_model = last_model?;
338 let provider = provider?;
339 if model_calls == 0 {
340 return None;
341 }
342
343 let actual_cost_micros = estimate_cost_micros(&selected_model, total_input, total_output);
344 let evidence_refs = vec![EvidenceRefV1 {
345 kind: EvidenceKind::ProviderReceipt,
346 uri: format!("receipt:{receipt_hash}"),
347 digest: receipt_hash,
348 signature_status: if signature.is_empty() {
349 SignatureStatus::NotSigned
350 } else {
351 SignatureStatus::Unverified
352 },
353 }];
354
355 let receipt = ExecutionReceiptV1 {
356 schema_version: 1,
357 receipt_id,
358 task_id,
359 plan_id,
360 context_balance,
361 fresh_input_tokens: total_input,
362 cached_input_tokens: 0,
363 output_tokens: total_output,
364 reasoning_tokens: 0,
365 requested_model,
366 selected_model,
367 provider,
368 capability_id: None,
369 capability_version: None,
370 model_calls,
371 retries: 0,
372 latency_ms: total_latency,
373 actual_cost_micros,
374 baseline_cost_micros: actual_cost_micros,
375 avoided_cost_micros: 0,
376 etpao_milli: 0,
377 outcome_ref: None,
378 knowledge_refs: Vec::new(),
379 decision_refs,
380 evidence_refs,
381 signature,
382 };
383 receipt.validate().ok()?;
384 Some(LegacyReceiptProjectionV1 { receipt })
385}
386
387fn estimate_cost_micros(model: &str, tokens_in: u64, tokens_out: u64) -> u64 {
388 let quote = crate::core::gain::model_pricing::ModelPricing::load().quote(Some(model));
389 let usd = quote.cost.estimate_usd(tokens_in, tokens_out, 0, 0);
390 if !usd.is_finite() || usd <= 0.0 {
391 return 0;
392 }
393 (usd * 1_000_000.0).round() as u64
394}