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
GitHub aien-dev/aien-sovereign-core-mv#60 (code only)
Apply it
git checkout -b patch-05a54b9d94d70b19 74c05d27845fca9dd289eb60e9a334f03358fe95 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/05a54b9d94d70b19.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
60
40fcf38441deee8d0fb94a505a5e5a20c5f067a3
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":60,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/60","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:38Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/cortex-rs/Dockerfile b/crates/cortex-rs/Dockerfile index 2c18de06..9af427fa 100644 --- a/crates/cortex-rs/Dockerfile +++ b/crates/cortex-rs/Dockerfile @@ -3,7 +3,7 @@ FROM rust:slim-bookworm AS builder WORKDIR /build -COPY Cargo.toml Cargo.lock ./ +COPY Cargo.toml Cargo.lock* ./ COPY src ./src RUN cargo build --release @@ -22,8 +22,6 @@ COPY --from=builder /build/target/release/cortex-rs /usr/local/bin/cortex-rs COPY scripts/reproduce.sh /usr/local/bin/reproduce.sh RUN chmod +x /usr/local/bin/reproduce.sh -ENV CORTEX_TOKEN=cortex-demo-token - EXPOSE 18080 ENTRYPOINT ["cortex-rs"] diff --git a/crates/cortex-rs/src/auth.rs b/crates/cortex-rs/src/auth.rs index 6afe941b..f5439282 100644 --- a/crates/cortex-rs/src/auth.rs +++ b/crates/cortex-rs/src/auth.rs @@ -29,10 +29,7 @@ pub fn load_cortex_token() -> String { } } -pub fn validate_auth_header( - auth_header: Option<&str>, - expected_token: &str, -) -> Result<(), StatusCode> { +pub fn validate_auth_header(auth_header: Option<&str>, expected_token: &str) -> Result<(), StatusCode> { if expected_token.is_empty() { return Err(StatusCode::SERVICE_UNAVAILABLE); } @@ -49,12 +46,10 @@ pub fn validate_auth_header( } } +#[allow(clippy::result_large_err)] pub async fn auth_middleware(req: Request, next: Next) -> Result<Response, Response> { let expected = load_cortex_token(); - let auth_header = req - .headers() - .get("Authorization") - .and_then(|h| h.to_str().ok()); + let auth_header = req.headers().get("Authorization").and_then(|h| h.to_str().ok()); match validate_auth_header(auth_header, &expected) { Ok(()) => Ok(next.run(req).await), @@ -69,8 +64,7 @@ pub async fn auth_middleware(req: Request, next: Next) -> Result<Response, Respo let err_resp = ( StatusCode::UNAUTHORIZED, Json(json!({"error": "Unauthorized: invalid or missing Cortex bearer token"})), - ) - .into_response(); + ).into_response(); Err(err_resp) } } diff --git a/crates/cortex-rs/src/bench.rs b/crates/cortex-rs/src/bench.rs index 0e18fd6a..1116c453 100644 --- a/crates/cortex-rs/src/bench.rs +++ b/crates/cortex-rs/src/bench.rs @@ -1,10 +1,19 @@ -use crate::db::Database; -use crate::models::{ClaimWriteInput, EntityWriteInput}; use std::fs; use std::time::Instant; +use crate::db::Database; +use crate::models::{ClaimWriteInput, EntityWriteInput}; pub fn run_benchmark(records: usize) -> Result<(), Box<dyn std::error::Error>> { - let tmp_path = std::env::temp_dir().join(format!("cortex_bench_{}.db", std::process::id())); + if records == 0 { + eprintln!("Error: --bench-records must be at least 1."); + return Ok(()); + } + + let timestamp_nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let tmp_path = std::env::temp_dir().join(format!("cortex_bench_{}_{}.db", std::process::id(), timestamp_nanos)); let _ = fs::remove_file(&tmp_path); println!("================================================================================"); @@ -35,10 +44,7 @@ pub fn run_benchmark(records: usize) -> Result<(), Box<dyn std::error::Error>> { for i in 0..records { let (domain, desc) = sample_domains[i % sample_domains.len()]; let canonical_name = format!("{}:entity_{:05}", domain, i); - let content = format!( - "{} Record ID {} generated for production deployment telemetry verification.", - desc, i - ); + let content = format!("{} Record ID {} generated for production deployment telemetry verification.", desc, i); let input = EntityWriteInput { id: None, space: "atlas-memory".to_string(), @@ -63,10 +69,7 @@ pub fn run_benchmark(records: usize) -> Result<(), Box<dyn std::error::Error>> { let ingest_qps = records as f64 / total_ingest_time.as_secs_f64(); // 2. Search Benchmark - println!( - "[2/3] Benchmarking FTS5 Lexical Search across {} records...", - records - ); + println!("[2/3] Benchmarking FTS5 Lexical Search across {} records...", records); let search_queries = [ "tpm vault", "unified memory", @@ -118,21 +121,28 @@ pub fn run_benchmark(records: usize) -> Result<(), Box<dyn std::error::Error>> { let mut traverse_latencies_us: Vec<f64> = Vec::with_capacity(num_claims); let start_traverse = Instant::now(); - for i in 0..num_claims { + for id in &entity_ids[..num_claims] { let t0 = Instant::now(); - let _claims = db.traverse_claims(&entity_ids[i], Some("atlas-memory"))?; + let _claims = db.traverse_claims(id, Some("atlas-memory"))?; let elapsed = t0.elapsed().as_secs_f64() * 1_000_000.0; traverse_latencies_us.push(elapsed); } let total_traverse_time = start_traverse.elapsed(); - let traverse_qps = num_claims as f64 / total_traverse_time.as_secs_f64(); + let traverse_qps = if total_traverse_time.as_secs_f64() > 0.0 { + num_claims as f64 / total_traverse_time.as_secs_f64() + } else { + 0.0 + }; // Compute percentiles - write_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap()); - search_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap()); - traverse_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap()); + write_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + search_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + traverse_latencies_us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let percentile = |vec: &[f64], p: f64| -> f64 { + if vec.is_empty() { + return 0.0; + } let idx = ((vec.len() as f64 * p) / 100.0).round() as usize; vec[idx.min(vec.len().saturating_sub(1))] }; @@ -167,20 +177,32 @@ pub fn run_benchmark(records: usize) -> Result<(), Box<dyn std::error::Error>> { traverse_qps ); println!("--------------------------------------------------------------------------------"); - println!( - "Search p50 in milliseconds: {:.3} ms", - percentile(&search_latencies_us, 50.0) / 1000.0 - ); - println!( - "Search p99 in milliseconds: {:.3} ms", - percentile(&search_latencies_us, 99.0) / 1000.0 - ); + println!("Search p50 in milliseconds: {:.3} ms", percentile(&search_latencies_us, 50.0) / 1000.0); + println!("Search p99 in milliseconds: {:.3} ms", percentile(&search_latencies_us, 99.0) / 1000.0); println!("================================================================================"); - // Cleanup + // Explicitly drop db to flush and close SQLite WAL before file removal + drop(db); let _ = fs::remove_file(&tmp_path); let _ = fs::remove_file(format!("{}-wal", tmp_path.display())); let _ = fs::remove_file(format!("{}-shm", tmp_path.display())); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_benchmark_zero_records_safe_exit() { + let res = run_benchmark(0); + assert!(res.is_ok()); + } + + #[test] + fn test_benchmark_minimal_records() { + let res = run_benchmark(2); + assert!(res.is_ok()); + } +} diff --git a/crates/cortex-rs/src/embeddings.rs b/crates/cortex-rs/src/embeddings.rs index c8f6480a..b2bd561c 100644 --- a/crates/cortex-rs/src/embeddings.rs +++ b/crates/cortex-rs/src/embeddings.rs @@ -12,6 +12,7 @@ pub fn embedding_to_bytes(v: &[f32]) -> Vec<u8> { bytes } +#[allow(clippy::chunks_exact_to_as_chunks)] pub fn bytes_to_embedding(b: &[u8]) -> Vec<f32> { let mut v = Vec::with_capacity(b.len() / 4); for chunk in b.chunks_exact(4) { @@ -46,11 +47,7 @@ pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 { 1.0 - cosine_similarity(a, b) } -pub async fn fetch_embedding( - client: &Client, - text: &str, - encoder_url: &str, -) -> Result<Vec<f32>, String> { +pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> Result<Vec<f32>, String> { let payload = json!({ "text": text, "modelId": "BAAI/bge-base-en-v1.5", @@ -64,12 +61,7 @@ pub async fn fetch_embedding( .json(&payload) .send() .await - .map_err(|e| { - format!( - "Failed to connect to embedding encoder on {}: {}", - encoder_url, e - ) - })?; + .map_err(|e| format!("Failed to connect to embedding encoder on {}: {}", encoder_url, e))?; if !resp.status().is_success() { let status = resp.status(); @@ -77,9 +69,7 @@ pub async fn fetch_embedding( return Err(format!("Encoder returned error HTTP {}: {}", status, body)); } - let val: serde_json::Value = resp - .json() - .await + let val: serde_json::Value = resp.json().await .map_err(|e| format!("Failed to parse embedding response JSON: {}", e))?; if let Some(arr) = val.get("embedding").and_then(|v| v.as_array()) { @@ -92,11 +82,7 @@ pub async fn fetch_embedding( if emb.len() == EMBEDDING_DIMENSIONS { return Ok(emb); } else { - return Err(format!( - "Expected {} dimensions, got {}", - EMBEDDING_DIMENSIONS, - emb.len() - )); + return Err(format!("Expected {} dimensions, got {}", EMBEDDING_DIMENSIONS, emb.len())); } }