aien-local-stack
aien-dev/aien-local-stack
Brought by drakestapleton
aien-local-stack / src / bin / cow_demo.rs
| 1 | use aien_inference_protocol::*; |
| 2 | use aien_local_stack::{ContextRecipe, RecipeStore, SovereignInferenceService}; |
| 3 | use aien_provenance::compute_canonical_json_digest; |
| 4 | use serde::{Deserialize, Serialize}; |
| 5 | use std::time::Instant; |
| 6 | use uuid::Uuid; |
| 7 | |
| 8 | fn get_rss_kb() -> i64 { |
| 9 | unsafe { |
| 10 | let mut rusage = std::mem::zeroed::<libc::rusage>(); |
| 11 | libc::getrusage(libc::RUSAGE_SELF, &mut rusage); |
| 12 | rusage.ru_maxrss |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | fn get_git_sha(repo_path: &str) -> String { |
| 17 | std::process::Command::new("git") |
| 18 | .args(["-C", repo_path, "rev-parse", "HEAD"]) |
| 19 | .output() |
| 20 | .ok() |
| 21 | .and_then(|out| { |
| 22 | if out.status.success() { |
| 23 | String::from_utf8(out.stdout) |
| 24 | .ok() |
| 25 | .map(|s| s.trim().to_string()) |
| 26 | } else { |
| 27 | None |
| 28 | } |
| 29 | }) |
| 30 | .unwrap_or_else(|| "unknown".to_string()) |
| 31 | } |
| 32 | |
| 33 | fn get_uname_info() -> (String, String) { |
| 34 | unsafe { |
| 35 | let mut uts = std::mem::zeroed::<libc::utsname>(); |
| 36 | if libc::uname(&mut uts) == 0 { |
| 37 | let sysname = std::ffi::CStr::from_ptr(uts.sysname.as_ptr()).to_string_lossy(); |
| 38 | let release = std::ffi::CStr::from_ptr(uts.release.as_ptr()).to_string_lossy(); |
| 39 | let machine = std::ffi::CStr::from_ptr(uts.machine.as_ptr()).to_string_lossy(); |
| 40 | (machine.to_string(), format!("{} {}", sysname, release)) |
| 41 | } else { |
| 42 | ( |
| 43 | std::env::consts::ARCH.to_string(), |
| 44 | std::env::consts::OS.to_string(), |
| 45 | ) |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #[derive(Serialize, Deserialize, Debug)] |
| 51 | pub struct ExecutionReceipt { |
| 52 | pub demo_version: String, |
| 53 | pub dependency_shas: DependencyShas, |
| 54 | pub hardware: HardwareDescriptor, |
| 55 | pub runtime: RuntimeDescriptor, |
| 56 | pub measurements: Measurements, |
| 57 | pub invariants_verified: Vec<String>, |
| 58 | pub receipt_digest: String, |
| 59 | } |
| 60 | |
| 61 | #[derive(Serialize, Deserialize, Debug)] |
| 62 | pub struct DependencyShas { |
| 63 | pub aien_protocols: String, |
| 64 | pub aegis_runtime: String, |
| 65 | pub aien_sovereign_core: String, |
| 66 | pub aien_local_stack: String, |
| 67 | } |
| 68 | |
| 69 | #[derive(Serialize, Deserialize, Debug)] |
| 70 | pub struct HardwareDescriptor { |
| 71 | pub architecture: String, |
| 72 | pub kernel: String, |
| 73 | pub memory_kind: String, |
| 74 | pub peak_rss_kb: i64, |
| 75 | } |
| 76 | |
| 77 | #[derive(Serialize, Deserialize, Debug)] |
| 78 | pub struct RuntimeDescriptor { |
| 79 | pub engine_id: String, |
| 80 | pub backend: String, |
| 81 | pub is_hardware_accelerated: bool, |
| 82 | pub kv_dtype: String, |
| 83 | pub block_size: usize, |
| 84 | } |
| 85 | |
| 86 | #[derive(Serialize, Deserialize, Debug)] |
| 87 | pub struct Measurements { |
| 88 | pub prefill_latency_us: u128, |
| 89 | pub fork_latency_avg_us: u128, |
| 90 | pub branch_0_step_us: u128, |
| 91 | pub branch_1_step_us: u128, |
| 92 | pub zero_copy_merge_us: u128, |
| 93 | pub recipe_reconstruction_us: u128, |
| 94 | pub total_cow_faults: usize, |
| 95 | pub bytes_saved_vs_full_copy: usize, |
| 96 | } |
| 97 | |
| 98 | #[tokio::main] |
| 99 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 100 | println!("================================================================================"); |
| 101 | println!(" AIEN Sovereign Multi-Branch Copy-on-Write & State ABI Demonstration "); |
| 102 | println!("================================================================================"); |
| 103 | |
| 104 | let storage_dir = std::env::temp_dir().join(format!("aien-recipe-store-{}", Uuid::new_v4())); |
| 105 | let recipe_store = RecipeStore::with_storage_dir(&storage_dir).map_err(|e| { |
| 106 | format!( |
| 107 | "Failed to create durable RecipeStore at {:?}: {}", |
| 108 | storage_dir, e |
| 109 | ) |
| 110 | })?; |
| 111 | |
| 112 | // --- STAGE 1: Initialize Engine and Prefill Shared Root Context --- |
| 113 | println!("\n[Stage 1] Initializing Sovereign Inference Service (Epoch = 1)..."); |
| 114 | let service = SovereignInferenceService::new_with_epoch(1) |
| 115 | .map_err(|e| format!("Service initialization failed: {}", e))?; |
| 116 | |
| 117 | println!(" Engine ID: {}", service.engine_id); |
| 118 | println!(" Backend: {}", service.backend_name); |
| 119 | println!(" Accelerated: {}", service.is_accelerated); |
| 120 | println!(" Memory: {}", service.memory_kind); |
| 121 | println!(" Epoch: {}", service.runtime_epoch()); |
| 122 | |
| 123 | let root_prompt_tokens: Vec<u32> = (1..=40).map(|x| (x * 7) % 256).collect(); |
| 124 | println!( |
| 125 | " Prefilling root context with {} tokens (block_size = 16)...", |
| 126 | root_prompt_tokens.len() |
| 127 | ); |
| 128 | |
| 129 | let mut recipe = ContextRecipe::new(root_prompt_tokens.clone()); |
| 130 | recipe_store.insert(recipe.clone())?; |
| 131 | |
| 132 | let t0 = Instant::now(); |
| 133 | let (root_handle, root_context) = service |
| 134 | .create_root_context(&root_prompt_tokens, &recipe) |
| 135 | .map_err(|e| format!("Root context creation failed: {}", e))?; |
| 136 | let prefill_us = t0.elapsed().as_micros(); |
| 137 | |
| 138 | println!(" Root Context ID: {:?}", root_context.context_id); |
| 139 | println!(" Root Branch ID: {}", root_context.branch_id.0); |
| 140 | println!(" Root Physical Handle: {:?}", root_handle.0); |
| 141 | println!(" Root Token Count: {}", root_context.token_count); |
| 142 | println!(" Prefill Latency: {} us", prefill_us); |
| 143 | |
| 144 | let m1 = service.get_kv_metrics().unwrap(); |
| 145 | println!( |
| 146 | " Allocated Blocks: {} (shared root pages)", |
| 147 | m1.used_blocks |
| 148 | ); |
| 149 | println!(" Initial CoW Faults: {}", service.get_cow_faults()); |
| 150 | |
| 151 | let root_blocks = service.get_block_table(root_context.branch_id.0).unwrap(); |
| 152 | println!(" Root Block Table: {:?}", root_blocks); |
| 153 | for &b in &root_blocks { |
| 154 | println!( |
| 155 | " Block {}: refcount = {}", |
| 156 | b, |
| 157 | service.get_block_refcount(b).unwrap() |
| 158 | ); |
| 159 | } |
| 160 | println!(); |
| 161 | |
| 162 | // --- STAGE 2: Fork Shared Root into Multiple Subagent Branches --- |
| 163 | println!("[Stage 2] Forking root context into 3 concurrent subagent branches..."); |
| 164 | let mut branch_contexts = Vec::new(); |
| 165 | let mut fork_times = Vec::new(); |
| 166 | let branch_names = [ |
| 167 | "Branch-0 (CodeGen)", |
| 168 | "Branch-1 (SecurityAudit)", |
| 169 | "Branch-2 (DocGen)", |
| 170 | ]; |
| 171 | |
| 172 | for name in branch_names.iter() { |
| 173 | let child_branch_id = BranchId::new_v4(); |
| 174 | let branch_req = BranchContextRequest { |
| 175 | operation_id: Uuid::new_v4(), |
| 176 | parent_context: root_context.clone(), |
| 177 | child_branch_id, |
| 178 | isolation: root_context.isolation, |
| 179 | }; |
| 180 | |
| 181 | let t_fork = Instant::now(); |
| 182 | let receipt = service |
| 183 | .branch_context(branch_req) |
| 184 | .await |
| 185 | .map_err(|e| format!("Fork failed for {}: {}", name, e))?; |
| 186 | let us = t_fork.elapsed().as_micros(); |
| 187 | fork_times.push(us); |
| 188 | |
| 189 | println!(" Forked {} in {} us", name, us); |
| 190 | println!(" Branch ID: {}", receipt.child_context.branch_id.0); |
| 191 | println!(" Shared Pages: {}", receipt.shared_pages); |
| 192 | println!( |
| 193 | " Copied Pages: {} (Flat Zero-Copy Guaranteed)", |
| 194 | receipt.copied_pages |
| 195 | ); |
| 196 | println!(" Generation: {:?}", receipt.child_context.generation); |
| 197 | |
| 198 | branch_contexts.push(receipt.child_context); |
| 199 | assert_eq!( |
| 200 | receipt.copied_pages, 0, |
| 201 | "Fork must be pure zero-copy pointer retention" |
| 202 | ); |
| 203 | } |
| 204 | |
| 205 | let fork_avg_us: u128 = fork_times.iter().sum::<u128>() / fork_times.len() as u128; |
| 206 | println!(" Average Fork Latency: {} us", fork_avg_us); |
| 207 | |
| 208 | let m2 = service.get_kv_metrics().unwrap(); |
| 209 | println!( |
| 210 | " Total Used Blocks after 3-way Fork: {} (Zero block allocation)", |
| 211 | m2.used_blocks |
| 212 | ); |
| 213 | for &b in &root_blocks { |
| 214 | println!( |
| 215 | " Block {}: refcount = {} (root + 3 branches)", |
| 216 | b, |
| 217 | service.get_block_refcount(b).unwrap() |
| 218 | ); |
| 219 | } |
| 220 | println!(); |
| 221 | |
| 222 | // --- STAGE 3: Mutate Branch and Verify Copy-on-Write Fault --- |
| 223 | println!( |
| 224 | "[Stage 3] Mutating Branch 0 and Branch 1 with divergent deltas to trigger physical CoW..." |
| 225 | ); |
| 226 | |
| 227 | println!( |
| 228 | " Stepping Branch 0 ({}) with delta \"generate code\"...", |
| 229 | branch_names[0] |
| 230 | ); |
| 231 | let req0 = InferenceRequest { |
| 232 | request_id: Uuid::new_v4(), |
| 233 | model: "sovereign-embedded".to_string(), |
| 234 | messages: vec![InferenceMessage { |
| 235 | role: "user".to_string(), |
| 236 | content: "generate code".to_string(), |
| 237 | }], |
| 238 | context: Some(branch_contexts[0].clone()), |
| 239 | max_tokens: 1, |
| 240 | temperature: 0.0, |
| 241 | stop_sequences: vec![], |
| 242 | }; |
| 243 | |
| 244 | let t_step0 = Instant::now(); |
| 245 | let res0 = service |
| 246 | .infer(req0) |
| 247 | .await |
| 248 | .map_err(|e| format!("Infer on Branch 0 failed: {}", e))?; |
| 249 | let step0_us = t_step0.elapsed().as_micros(); |
| 250 | let cow_after_0 = service.get_cow_faults(); |
| 251 | let updated_ctx0 = res0.context.clone().unwrap(); |
| 252 | |
| 253 | println!( |
| 254 | " Branch 0 completed step in {} us (Tokens generated = {})", |
| 255 | step0_us, res0.completion_tokens |
| 256 | ); |
| 257 | println!( |
| 258 | " CoW Faults after Branch 0 write: {} (Exactly 1 tail page cloned)", |
| 259 | cow_after_0 |
| 260 | ); |
| 261 | assert_eq!( |
| 262 | cow_after_0, 1, |
| 263 | "Expected exactly 1 CoW fault after branch 0 mutation" |
| 264 | ); |
| 265 | |
| 266 | println!( |
| 267 | " Stepping Branch 1 ({}) with delta \"security audit\"...", |
| 268 | branch_names[1] |
| 269 | ); |
| 270 | let req1 = InferenceRequest { |
| 271 | request_id: Uuid::new_v4(), |
| 272 | model: "sovereign-embedded".to_string(), |
| 273 | messages: vec![InferenceMessage { |
| 274 | role: "user".to_string(), |
| 275 | content: "security audit".to_string(), |
| 276 | }], |
| 277 | context: Some(branch_contexts[1].clone()), |
| 278 | max_tokens: 1, |
| 279 | temperature: 0.0, |
| 280 | stop_sequences: vec![], |
| 281 | }; |
| 282 | |
| 283 | let t_step1 = Instant::now(); |
| 284 | let res1 = service |
| 285 | .infer(req1) |
| 286 | .await |
| 287 | .map_err(|e| format!("Infer on Branch 1 failed: {}", e))?; |
| 288 | let step1_us = t_step1.elapsed().as_micros(); |
| 289 | let cow_after_1 = service.get_cow_faults(); |
| 290 | let updated_ctx1 = res1.context.clone().unwrap(); |
| 291 | |
| 292 | println!( |
| 293 | " Branch 1 completed step in {} us (Tokens generated = {})", |
| 294 | step1_us, res1.completion_tokens |
| 295 | ); |
| 296 | println!( |
| 297 | " CoW Faults after Branch 1 write: {} (Cloned own tail page)", |
| 298 | cow_after_1 |
| 299 | ); |
| 300 | assert_eq!( |
| 301 | cow_after_1, 2, |
| 302 | "Expected exactly 2 CoW faults after independent branch mutations" |
| 303 | ); |
| 304 | |
| 305 | println!(" Verifying True Logical & Physical Divergence between Branch 0 and Branch 1..."); |
| 306 | println!( |
| 307 | " Branch 0 State Digest: {:?}", |
| 308 | updated_ctx0.logical_state_digest |
| 309 | ); |
| 310 | println!( |
| 311 | " Branch 1 State Digest: {:?}", |
| 312 | updated_ctx1.logical_state_digest |
| 313 | ); |
| 314 | assert_ne!( |
| 315 | updated_ctx0.logical_state_digest, updated_ctx1.logical_state_digest, |
| 316 | "Branch 0 and Branch 1 must physically and logically diverge" |
| 317 | ); |
| 318 | |
| 319 | println!(" Verifying Branch 2 remained untouched and fully shared..."); |
| 320 | let b2_blocks = service |
| 321 | .get_block_table(branch_contexts[2].branch_id.0) |
| 322 | .unwrap(); |
| 323 | assert_eq!(b2_blocks, root_blocks); |
| 324 | println!(); |
| 325 | |
| 326 | // Snapshot durable recipe from branch state (covers root prompt + branch delta + generated tokens) |
| 327 | recipe = service |
| 328 | .snapshot_branch_recipe(updated_ctx0.branch_id.0, &recipe) |
| 329 | .expect("Snapshot branch recipe failed"); |
| 330 | recipe_store.insert(recipe.clone())?; |
| 331 | |
| 332 | // --- STAGE 4: Zero-Copy Logical Merge (SelectBranch) --- |
| 333 | println!("[Stage 4] Demonstrating Logical Merge (SelectBranch)..."); |
| 334 | let winner_id = updated_ctx0.branch_id.0; |
| 335 | let sibling_ids = [ |
| 336 | branch_contexts[1].branch_id.0, |
| 337 | branch_contexts[2].branch_id.0, |
| 338 | ]; |
| 339 | |
| 340 | println!( |
| 341 | " Selecting Branch 0 ({}) as canonical winner...", |
| 342 | branch_names[0] |
| 343 | ); |
| 344 | let t_merge = Instant::now(); |
| 345 | service |
| 346 | .select_branch(winner_id, &sibling_ids) |
| 347 | .map_err(|e| format!("SelectBranch failed: {}", e))?; |
| 348 | let merge_us = t_merge.elapsed().as_micros(); |
| 349 | println!( |
| 350 | " SelectBranch completed in {} us (Zero-Copy Pointer Retention)", |
| 351 | merge_us |
| 352 | ); |
| 353 | |
| 354 | let m4 = service.get_kv_metrics().unwrap(); |
| 355 | println!( |
| 356 | " Allocated Blocks after Pruning Siblings: {}\n", |
| 357 | m4.used_blocks |
| 358 | ); |
| 359 | |
| 360 | // --- STAGE 5: Authentic Engine Crash & Durable ContextRecipeRef Recovery --- |
| 361 | println!("[Stage 5] Simulating Authentic Engine Crash & Recovery from RecipeStore..."); |
| 362 | let pre_crash_digest = updated_ctx0.logical_state_digest; |
| 363 | let pre_crash_recipe_ref = recipe.to_ref(); |
| 364 | |
| 365 | println!(" 1. Destroying Sovereign Core and RecipeStore (simulating process crash)..."); |
| 366 | drop(service); |
| 367 | drop(recipe_store); |
| 368 | |
| 369 | println!(" 2. Instantiating fresh Sovereign Core and re-opening RecipeStore from disk (Epoch = 2)..."); |
| 370 | let fresh_service = SovereignInferenceService::new_with_epoch(2) |
| 371 | .map_err(|e| format!("Restart failed: {}", e))?; |
| 372 | let recovered_recipe_store = RecipeStore::with_storage_dir(&storage_dir) |
| 373 | .map_err(|e| format!("Failed to reload RecipeStore from disk: {}", e))?; |
| 374 | println!( |
| 375 | " Restarted runtime epoch: {}", |
| 376 | fresh_service.runtime_epoch() |
| 377 | ); |
| 378 | |
| 379 | // Verify stale context rejection |
| 380 | println!(" 3. Probing stale binding from pre-crash Epoch 1 against new engine..."); |
| 381 | let stale_req = InferenceRequest { |
| 382 | request_id: Uuid::new_v4(), |
| 383 | model: "sovereign-embedded".to_string(), |
| 384 | messages: vec![InferenceMessage { |
| 385 | role: "user".to_string(), |
| 386 | content: "resume".to_string(), |
| 387 | }], |
| 388 | context: Some(updated_ctx0.clone()), |
| 389 | max_tokens: 1, |
| 390 | temperature: 0.0, |
| 391 | stop_sequences: vec![], |
| 392 | }; |
| 393 | match fresh_service.infer(stale_req).await { |
| 394 | Err(InferenceError::StaleRuntimeEpoch) => { |
| 395 | println!(" SUCCESS: StaleRuntimeEpoch correctly rejected stale epoch binding."); |
| 396 | } |
| 397 | other => panic!("Expected StaleRuntimeEpoch, got {:?}", other), |
| 398 | } |
| 399 | |
| 400 | // Durable Recipe Recovery |
| 401 | println!( |
| 402 | " 4. Resolving durable ContextRecipe from disk-backed RecipeStore via ContextRecipeRef..." |
| 403 | ); |
| 404 | let t_recon = Instant::now(); |
| 405 | let durable_recipe = recovered_recipe_store |
| 406 | .verify_and_get(&pre_crash_recipe_ref) |
| 407 | .map_err(|e| format!("Recipe verification failed: {}", e))?; |
| 408 | |
| 409 | let (recon_handle, recon_ctx) = fresh_service |
| 410 | .reconstruct_from_recipe(winner_id, &durable_recipe) |
| 411 | .map_err(|e| format!("Reconstruction failed: {}", e))?; |
| 412 | let recon_us = t_recon.elapsed().as_micros(); |
| 413 | |
| 414 | println!( |
| 415 | " Branch reconstructed in {} us (New Context Handle ID: {:?})", |
| 416 | recon_us, recon_handle.0 |
| 417 | ); |
| 418 | println!( |
| 419 | " Reconstructed Logical Digest: {:?}", |
| 420 | recon_ctx.logical_state_digest |
| 421 | ); |
| 422 | println!(" Pre-Crash Logical Digest: {:?}", pre_crash_digest); |
| 423 | assert_eq!( |
| 424 | recon_ctx.logical_state_digest, pre_crash_digest, |
| 425 | "Reconstructed state digest must match pre-crash state digest exactly" |
| 426 | ); |
| 427 | |
| 428 | // Clean up temporary storage directory |
| 429 | let _ = std::fs::remove_dir_all(&storage_dir); |
| 430 | |
| 431 | // Verify inference continues on reconstructed branch |
| 432 | let cont_req = InferenceRequest { |
| 433 | request_id: Uuid::new_v4(), |
| 434 | model: "sovereign-embedded".to_string(), |
| 435 | messages: vec![InferenceMessage { |
| 436 | role: "user".to_string(), |
| 437 | content: "continue".to_string(), |
| 438 | }], |
| 439 | context: Some(recon_ctx), |
| 440 | max_tokens: 1, |
| 441 | temperature: 0.0, |
| 442 | stop_sequences: vec![], |
| 443 | }; |
| 444 | let cont_res = fresh_service.infer(cont_req).await?; |
| 445 | println!( |
| 446 | " Inference on recovered branch succeeded (tokens = {})\n", |
| 447 | cont_res.completion_tokens |
| 448 | ); |
| 449 | |
| 450 | // --- Structured Execution Receipt --- |
| 451 | println!("================================================================================"); |
| 452 | println!(" STRUCTURED EXECUTION RECEIPT "); |
| 453 | println!("================================================================================"); |
| 454 | |
| 455 | let measurements = Measurements { |
| 456 | prefill_latency_us: prefill_us, |
| 457 | fork_latency_avg_us: fork_avg_us, |
| 458 | branch_0_step_us: step0_us, |
| 459 | branch_1_step_us: step1_us, |
| 460 | zero_copy_merge_us: merge_us, |
| 461 | recipe_reconstruction_us: recon_us, |
| 462 | total_cow_faults: fresh_service.get_cow_faults() + cow_after_1, |
| 463 | bytes_saved_vs_full_copy: m2.bytes_saved_vs_full_copy, |
| 464 | }; |
| 465 | |
| 466 | let (arch, kernel) = get_uname_info(); |
| 467 | let ws = format!( |
| 468 | "{}/workspace", |
| 469 | std::env::var("HOME").unwrap_or_else(|_| ".".to_string()) |
| 470 | ); |
| 471 | let receipt_data = ExecutionReceipt { |
| 472 | demo_version: "1.2.0".to_string(), |
| 473 | dependency_shas: DependencyShas { |
| 474 | aien_protocols: get_git_sha(&format!("{ws}/aien-protocols")), |
| 475 | aegis_runtime: get_git_sha(&format!("{ws}/aegis-runtime")), |
| 476 | aien_sovereign_core: get_git_sha(&format!("{ws}/aien-sovereign-core")), |
| 477 | aien_local_stack: get_git_sha(&format!("{ws}/aien-local-stack")), |
| 478 | }, |
| 479 | hardware: HardwareDescriptor { |
| 480 | architecture: arch, |
| 481 | kernel, |
| 482 | memory_kind: fresh_service.memory_kind.clone(), |
| 483 | peak_rss_kb: get_rss_kb(), |
| 484 | }, |
| 485 | runtime: RuntimeDescriptor { |
| 486 | engine_id: fresh_service.engine_id.clone(), |
| 487 | backend: fresh_service.backend_name.clone(), |
| 488 | is_hardware_accelerated: fresh_service.is_accelerated, |
| 489 | kv_dtype: "FP32".to_string(), |
| 490 | block_size: 16, |
| 491 | }, |
| 492 | measurements, |
| 493 | invariants_verified: vec![ |
| 494 | "flat_zero_copy_branch_fork".to_string(), |
| 495 | "isolated_tail_page_cow_fault".to_string(), |
| 496 | "untouched_sibling_block_sharing".to_string(), |
| 497 | "branch_delta_state_divergence".to_string(), |
| 498 | "zero_copy_logical_merge_select_branch".to_string(), |
| 499 | "stale_runtime_epoch_rejection".to_string(), |
| 500 | "durable_recipe_hash_verification".to_string(), |
| 501 | "post_crash_logical_state_digest_parity".to_string(), |
| 502 | "file_backed_recipe_store_persistence".to_string(), |
| 503 | "generated_token_state_parity".to_string(), |
| 504 | ], |
| 505 | receipt_digest: String::new(), |
| 506 | }; |
| 507 | |
| 508 | let canonical_digest = compute_canonical_json_digest(&receipt_data).unwrap(); |
| 509 | let final_receipt = ExecutionReceipt { |
| 510 | receipt_digest: canonical_digest.to_hex(), |
| 511 | ..receipt_data |
| 512 | }; |
| 513 | |
| 514 | let json_receipt = serde_json::to_string_pretty(&final_receipt)?; |
| 515 | std::fs::write("receipt-cow-demo.json", &json_receipt)?; |
| 516 | |
| 517 | println!("Receipt Digest (SHA-256): {}", final_receipt.receipt_digest); |
| 518 | println!("Saved to: receipt-cow-demo.json"); |
| 519 | println!("Summary:"); |
| 520 | println!(" - Backend: {}", final_receipt.runtime.backend); |
| 521 | println!( |
| 522 | " - Memory Subsystem: {}", |
| 523 | final_receipt.hardware.memory_kind |
| 524 | ); |
| 525 | println!(" - KV DType: {}", final_receipt.runtime.kv_dtype); |
| 526 | println!( |
| 527 | " - Prefill Latency: {} us", |
| 528 | final_receipt.measurements.prefill_latency_us |
| 529 | ); |
| 530 | println!( |
| 531 | " - Fork Latency (avg): {} us", |
| 532 | final_receipt.measurements.fork_latency_avg_us |
| 533 | ); |
| 534 | println!(" - True Divergence Verified: Branch A != Branch B state digest"); |
| 535 | println!( |
| 536 | " - Merge Latency (SelectBranch): {} us", |
| 537 | final_receipt.measurements.zero_copy_merge_us |
| 538 | ); |
| 539 | println!( |
| 540 | " - Recipe Reconstruction: {} us (Parity Verified)", |
| 541 | final_receipt.measurements.recipe_reconstruction_us |
| 542 | ); |
| 543 | println!( |
| 544 | " - Peak RSS Memory: {} KB", |
| 545 | final_receipt.hardware.peak_rss_kb |
| 546 | ); |
| 547 | println!("================================================================================"); |
| 548 | |
| 549 | Ok(()) |
| 550 | } |