Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/cortex-rs/src/bench.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / cortex-rs / src / bench.rs` 239 lines · 9708 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use crate::db::Database; 17 use crate::models::{ClaimWriteInput, EntityWriteInput}; 18 use std::fs; 19 use std::time::Instant; 20 21 pub fn run_benchmark(records: usize) -> Result<(), Box> { 22 if records == 0 { 23 eprintln!("Error: --bench-records must be at least 1."); 24 return Ok(()); 25 } 26 27 let timestamp_nanos = std::time::SystemTime::now() 28 .duration_since(std::time::UNIX_EPOCH) 29 .map(|d| d.as_nanos()) 30 .unwrap_or(0); 31 let tmp_path = std::env::temp_dir().join(format!( 32 "cortex_bench_{}_{}.db", 33 std::process::id(), 34 timestamp_nanos 35 )); 36 let _ = fs::remove_file(&tmp_path); 37 38 println!("================================================================================"); 39 println!("CORTEX-RS FLAGSHIP REPRODUCTION BENCHMARK"); 40 println!("Target: SQLite WAL + FTS5 Inverted Index + Graph Claim Traversal"); 41 println!("Records to ingest: {}", records); 42 println!("================================================================================"); 43 44 let db = Database::open(&tmp_path)?; 45 46 // 1. Ingestion Benchmark 47 println!("\n[1/3] Benchmarking Entity Ingestion (FTS5 + SQLite WAL)..."); 48 let mut write_latencies_us: Vec = Vec::with_capacity(records); 49 let mut entity_ids: Vec = Vec::with_capacity(records); 50 51 let sample_domains = [ 52 ("tpm_vault", "Hardware TPM 2.0 key attestation and zero disk plaintext secret security."), 53 ("inference_scheduler", "Dynamic batching and continuous sequence allocation on Blackwell GB10 unified memory."), 54 ("kv_cache", "Paged KV cache allocation with zero copy tensor memory reuse under high concurrency."), 55 ("cortex_memory", "Lexical BM25 indexing with ONNX vector embeddings and sub-millisecond retrieval."), 56 ("kernel_optimization", "GPU kernel tile optimization for FP8 and BF16 GEMM matrix multiplication."), 57 ("resilience_protocol", "Crash-only idempotency, WAL transaction rollbacks, and self-healing supervisory loops."), 58 ("consensus_engine", "Decentralized state replication with cryptographic hash chained audit records."), 59 ("compiler_pipeline", "AOT binary compilation with strict link-time optimization and zero runtime interpreter overhead."), 60 ]; 61 62 let start_ingest = Instant::now(); 63 for i in 0..records { 64 let (domain, desc) = sample_domains[i % sample_domains.len()]; 65 let canonical_name = format!("{}:entity_{:05}", domain, i); 66 let content = format!( 67 "{} Record ID {} generated for production deployment metrics verification.", 68 desc, i 69 ); 70 let input = EntityWriteInput { 71 id: None, 72 space: "atlas-memory".to_string(), 73 entity_type: "lesson".to_string(), 74 canonical_name, 75 content, 76 aliases: vec![format!("alias_{:05}", i)], 77 metadata: serde_json::json!({"index": i, "domain": domain}), 78 confidence: 1.0, 79 valid_from: None, 80 valid_to: None, 81 external_id: None, 82 }; 83 84 let t0 = Instant::now(); 85 let receipt = db.upsert_entity(&input, None)?; 86 let elapsed = t0.elapsed().as_secs_f64() * 1_000_000.0; 87 write_latencies_us.push(elapsed); 88 entity_ids.push(receipt.target_id); 89 } 90 let total_ingest_time = start_ingest.elapsed(); 91 let ingest_qps = records as f64 / total_ingest_time.as_secs_f64(); 92 93 // 2. Search Benchmark 94 println!( 95 "[2/3] Benchmarking FTS5 Lexical Search across {} records...", 96 records 97 ); 98 let search_queries = [ 99 "tpm vault", 100 "unified memory", 101 "KV cache allocation", 102 "lexical BM25", 103 "kernel tile optimization", 104 "crash-only idempotency", 105 "cryptographic audit", 106 "zero runtime interpreter", 107 "metrics verification", 108 "nonexistent_token_xyz_404", 109 ]; 110 111 let query_iterations = 50; 112 let total_queries = search_queries.len() * query_iterations; 113 let mut search_latencies_us: Vec = Vec::with_capacity(total_queries); 114 115 let start_search = Instant::now(); 116 for _ in 0..query_iterations { 117 for query in &search_queries { 118 let t0 = Instant::now(); 119 let results = db.search_entities(query, Some("atlas-memory"), 10)?; 120 let elapsed = t0.elapsed().as_secs_f64() * 1_000_000.0; 121 search_latencies_us.push(elapsed); 122 let _ = results.len(); 123 } 124 } 125 let total_search_time = start_search.elapsed(); 126 let search_qps = total_queries as f64 / total_search_time.as_secs_f64(); 127 128 // 3. Graph Traversal Benchmark 129 println!("[3/3] Benchmarking Bidirectional Graph Claim Traversal..."); 130 let num_claims = records.min(200); 131 for i in 0..num_claims { 132 let sub = &entity_ids[i]; 133 let obj = &entity_ids[(i + 1) % records]; 134 let claim = ClaimWriteInput { 135 id: None, 136 space: "atlas-memory".to_string(), 137 subject_entity_id: sub.clone(), 138 predicate: "depends_on".to_string(), 139 object_entity_id: Some(obj.clone()), 140 literal_value: None, 141 confidence: 1.0, 142 metadata: serde_json::json!({}), 143 }; 144 db.upsert_claim(&claim)?; 145 } 146 147 let mut traverse_latencies_us: Vec = Vec::with_capacity(num_claims); 148 let start_traverse = Instant::now(); 149 for id in &entity_ids[..num_claims] { 150 let t0 = Instant::now(); 151 let _claims = db.traverse_claims(id, Some("atlas-memory"))?; 152 let elapsed = t0.elapsed().as_secs_f64() * 1_000_000.0; 153 traverse_latencies_us.push(elapsed); 154 } 155 let total_traverse_time = start_traverse.elapsed(); 156 let traverse_qps = if total_traverse_time.as_secs_f64() > 0.0 { 157 num_claims as f64 / total_traverse_time.as_secs_f64() 158 } else { 159 0.0 160 }; 161 162 // Compute percentiles 163 write_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); 164 search_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); 165 traverse_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); 166 167 let percentile = |vec: &[f64], p: f64| -> f64 { 168 if vec.is_empty() { 169 return 0.0; 170 } 171 let idx = ((vec.len() as f64 * p) / 100.0).round() as usize; 172 vec[idx.min(vec.len().saturating_sub(1))] 173 }; 174 175 println!("\n================================================================================"); 176 println!("BENCHMARK RESULTS SUMMARY (Reproducible Single-Command Output)"); 177 println!("================================================================================"); 178 println!("Corpus Size: {:>10} entities", records); 179 println!("Total Search Queries Run: {:>10}", total_queries); 180 println!("--------------------------------------------------------------------------------"); 181 println!("METRIC p50 (µs) p95 (µs) p99 (µs) Rate / QPS"); 182 println!("--------------------------------------------------------------------------------"); 183 println!( 184 "Entity Ingestion (WAL+FTS5) {:>8.1} {:>8.1} {:>8.1} {:>9.1} writes/s", 185 percentile(&write_latencies_us, 50.0), 186 percentile(&write_latencies_us, 95.0), 187 percentile(&write_latencies_us, 99.0), 188 ingest_qps 189 ); 190 println!( 191 "FTS5 Lexical Search {:>8.1} {:>8.1} {:>8.1} {:>9.1} qps", 192 percentile(&search_latencies_us, 50.0), 193 percentile(&search_latencies_us, 95.0), 194 percentile(&search_latencies_us, 99.0), 195 search_qps 196 ); 197 println!( 198 "Graph Claim Traversal {:>8.1} {:>8.1} {:>8.1} {:>9.1} qps", 199 percentile(&traverse_latencies_us, 50.0), 200 percentile(&traverse_latencies_us, 95.0), 201 percentile(&traverse_latencies_us, 99.0), 202 traverse_qps 203 ); 204 println!("--------------------------------------------------------------------------------"); 205 println!( 206 "Search p50 in milliseconds: {:.3} ms", 207 percentile(&search_latencies_us, 50.0) / 1000.0 208 ); 209 println!( 210 "Search p99 in milliseconds: {:.3} ms", 211 percentile(&search_latencies_us, 99.0) / 1000.0 212 ); 213 println!("================================================================================"); 214 215 // Explicitly drop db to flush and close SQLite WAL before file removal 216 drop(db); 217 let _ = fs::remove_file(&tmp_path); 218 let _ = fs::remove_file(format!("{}-wal", tmp_path.display())); 219 let _ = fs::remove_file(format!("{}-shm", tmp_path.display())); 220 221 Ok(()) 222 } 223 224 #[cfg(test)] 225 mod tests { 226 use super::*; 227 228 #[test] 229 fn test_benchmark_zero_records_safe_exit() { 230 let res = run_benchmark(0); 231 assert!(res.is_ok()); 232 } 233 234 #[test] 235 fn test_benchmark_minimal_records() { 236 let res = run_benchmark(2); 237 assert!(res.is_ok()); 238 } 239 }