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
aien-sovereign-core-mv / crates / cortex-path-m1 / src / run.rs
| 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::config::ExperimentConfig; |
| 17 | use crate::fixture::{self, EvalFixture, FixtureRejection}; |
| 18 | use crate::load::load_admitted_graph; |
| 19 | use crate::metrics::{self, ci_excludes_zero}; |
| 20 | use crate::score::{self, CandidateSuggestion}; |
| 21 | use chrono::{DateTime, Utc}; |
| 22 | use cortex_rs::Database; |
| 23 | use serde::Serialize; |
| 24 | use sha2::{Digest, Sha256}; |
| 25 | use std::fs; |
| 26 | use std::path::{Path, PathBuf}; |
| 27 | use std::time::Instant; |
| 28 | |
| 29 | #[derive(Debug, Clone, Serialize)] |
| 30 | pub struct QueryRow { |
| 31 | pub query_id: String, |
| 32 | pub baseline_ids: Vec<String>, |
| 33 | pub treatment_ids: Vec<String>, |
| 34 | pub baseline_ndcg: f64, |
| 35 | pub treatment_ndcg: f64, |
| 36 | pub absolute_ndcg_delta: f64, |
| 37 | pub relative_ndcg: Option<f64>, |
| 38 | pub baseline_recall: f64, |
| 39 | pub treatment_recall: f64, |
| 40 | pub baseline_latency_ms: f64, |
| 41 | pub treatment_latency_ms: f64, |
| 42 | pub baseline_accounted_bytes: u64, |
| 43 | pub treatment_accounted_bytes: u64, |
| 44 | pub paths_scored: usize, |
| 45 | pub suggestions: Vec<CandidateSuggestion>, |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Clone, Serialize)] |
| 49 | pub struct ZeroBaselineRow { |
| 50 | pub query_id: String, |
| 51 | pub baseline_ndcg: f64, |
| 52 | pub treatment_ndcg: f64, |
| 53 | pub absolute_delta: f64, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, Serialize)] |
| 57 | pub struct ExperimentReport { |
| 58 | pub dataset_snapshot_sha256: String, |
| 59 | pub eval_fixture_sha256: String, |
| 60 | pub experiment_binary_sha256: String, |
| 61 | pub config_sha256: String, |
| 62 | pub snapshot_time: String, |
| 63 | pub queries: Vec<QueryRow>, |
| 64 | pub relative_mean_ndcg: Option<f64>, |
| 65 | pub absolute_mean_ndcg_delta: f64, |
| 66 | pub zero_baseline: Vec<ZeroBaselineRow>, |
| 67 | pub recall_at_10_delta: f64, |
| 68 | pub baseline_p95_ms: f64, |
| 69 | pub treatment_p95_ms: f64, |
| 70 | pub baseline_peak_accounted_bytes: u64, |
| 71 | pub treatment_peak_accounted_bytes: u64, |
| 72 | pub bootstrap_low: Option<f64>, |
| 73 | pub bootstrap_high: Option<f64>, |
| 74 | pub writes: u64, |
| 75 | pub pass: bool, |
| 76 | pub strong_pass: bool, |
| 77 | pub fail: bool, |
| 78 | } |
| 79 | |
| 80 | #[derive(Debug)] |
| 81 | pub enum RunOutcome { |
| 82 | Rejected(FixtureRejection), |
| 83 | Report(Box<ExperimentReport>), |
| 84 | } |
| 85 | |
| 86 | pub fn sha256_bytes(bytes: &[u8]) -> String { |
| 87 | let mut hasher = Sha256::new(); |
| 88 | hasher.update(bytes); |
| 89 | format!("{:x}", hasher.finalize()) |
| 90 | } |
| 91 | |
| 92 | pub fn sha256_file(path: &Path) -> Result<String, String> { |
| 93 | let bytes = fs::read(path).map_err(|err| format!("read {}: {err}", path.display()))?; |
| 94 | Ok(sha256_bytes(&bytes)) |
| 95 | } |
| 96 | |
| 97 | pub fn run_experiment( |
| 98 | snapshot: &Path, |
| 99 | fixture_bytes: &[u8], |
| 100 | snapshot_time: DateTime<Utc>, |
| 101 | binary_bytes: &[u8], |
| 102 | ) -> Result<RunOutcome, String> { |
| 103 | let fixture = fixture::load_fixture(fixture_bytes)?; |
| 104 | let mut rejection = fixture::structural_rejection(&fixture); |
| 105 | if !rejection.reasons.is_empty() { |
| 106 | return Ok(RunOutcome::Rejected(rejection)); |
| 107 | } |
| 108 | |
| 109 | refuse_sidecar(snapshot)?; |
| 110 | let source_hash = sha256_file(snapshot)?; |
| 111 | let temp_dir = std::env::temp_dir().join(format!( |
| 112 | "cortex-path-m1-{}", |
| 113 | sha256_bytes(source_hash.as_bytes()) |
| 114 | )); |
| 115 | fs::create_dir_all(&temp_dir).map_err(|err| err.to_string())?; |
| 116 | let copy_path = temp_dir.join("snapshot.sqlite"); |
| 117 | fs::copy(snapshot, ©_path).map_err(|err| format!("copy snapshot: {err}"))?; |
| 118 | |
| 119 | let outcome = run_on_copy( |
| 120 | ©_path, |
| 121 | &fixture, |
| 122 | fixture_bytes, |
| 123 | snapshot_time, |
| 124 | binary_bytes, |
| 125 | &source_hash, |
| 126 | &mut rejection, |
| 127 | ); |
| 128 | let after = sha256_file(snapshot)?; |
| 129 | if after != source_hash { |
| 130 | return Err("source snapshot hash changed during the run".to_string()); |
| 131 | } |
| 132 | outcome |
| 133 | } |
| 134 | |
| 135 | fn run_on_copy( |
| 136 | copy_path: &Path, |
| 137 | fixture: &EvalFixture, |
| 138 | fixture_bytes: &[u8], |
| 139 | snapshot_time: DateTime<Utc>, |
| 140 | binary_bytes: &[u8], |
| 141 | source_hash: &str, |
| 142 | rejection: &mut FixtureRejection, |
| 143 | ) -> Result<RunOutcome, String> { |
| 144 | let db = Database::open(copy_path).map_err(|err| err.to_string())?; |
| 145 | let before = table_counts(copy_path)?; |
| 146 | let mut relational = 0usize; |
| 147 | for case in &fixture.cases { |
| 148 | let mut names = Vec::new(); |
| 149 | for entity_id in &case.relevant_entity_ids { |
| 150 | match db |
| 151 | .get_entity(entity_id, Some(&case.space_slug)) |
| 152 | .map_err(|err| err.to_string())? |
| 153 | { |
| 154 | Some(entity) => names.push(entity.canonical_name), |
| 155 | None => rejection |
| 156 | .reasons |
| 157 | .push(format!("case {} missing entity {entity_id}", case.id)), |
| 158 | } |
| 159 | } |
| 160 | if fixture::relational_case(&case.query, &names) { |
| 161 | relational += 1; |
| 162 | } |
| 163 | } |
| 164 | if relational < 15 { |
| 165 | rejection.reasons.push(format!( |
| 166 | "fixture has {relational} relational cases; a scientific run needs at least 15" |
| 167 | )); |
| 168 | } |
| 169 | if !rejection.reasons.is_empty() { |
| 170 | return Ok(RunOutcome::Rejected(rejection.clone())); |
| 171 | } |
| 172 | |
| 173 | let config = ExperimentConfig::default(); |
| 174 | let mut rows = Vec::with_capacity(fixture.cases.len()); |
| 175 | for case in &fixture.cases { |
| 176 | rows.push(score_case(&db, case, &config, snapshot_time)?); |
| 177 | } |
| 178 | let after = table_counts(copy_path)?; |
| 179 | let writes = count_delta(&before, &after); |
| 180 | |
| 181 | Ok(RunOutcome::Report(Box::new(build_report( |
| 182 | &config, |
| 183 | rows, |
| 184 | source_hash, |
| 185 | &sha256_bytes(fixture_bytes), |
| 186 | &sha256_bytes(binary_bytes), |
| 187 | snapshot_time, |
| 188 | writes, |
| 189 | )?))) |
| 190 | } |
| 191 | |
| 192 | fn score_case( |
| 193 | db: &Database, |
| 194 | case: &fixture::EvalCase, |
| 195 | config: &ExperimentConfig, |
| 196 | snapshot_time: DateTime<Utc>, |
| 197 | ) -> Result<QueryRow, String> { |
| 198 | let space = Some(case.space_slug.as_str()); |
| 199 | let baseline_started = Instant::now(); |
| 200 | let baseline_hits = db |
| 201 | .recall_entities( |
| 202 | &case.query, |
| 203 | Some(&case.query_embedding), |
| 204 | space, |
| 205 | config.top_k, |
| 206 | ) |
| 207 | .map_err(|err| err.to_string())?; |
| 208 | let baseline_latency_ms = elapsed_ms(baseline_started); |
| 209 | let baseline_ids: Vec<String> = baseline_hits |
| 210 | .iter() |
| 211 | .map(|item| item.entity.id.clone()) |
| 212 | .collect(); |
| 213 | |
| 214 | let treatment_started = Instant::now(); |
| 215 | let scored = db |
| 216 | .recall_entities( |
| 217 | &case.query, |
| 218 | Some(&case.query_embedding), |
| 219 | space, |
| 220 | config.full_scan_limit, |
| 221 | ) |
| 222 | .map_err(|err| err.to_string())?; |
| 223 | let baseline_pairs: Vec<(String, f64)> = scored |
| 224 | .iter() |
| 225 | .map(|item| (item.entity.id.clone(), item.final_score)) |
| 226 | .collect(); |
| 227 | let entity_ids: Vec<String> = baseline_pairs.iter().map(|(id, _)| id.clone()).collect(); |
| 228 | let anchors = score::select_anchors(config, &baseline_pairs); |
| 229 | let graph = load_admitted_graph(db, &case.space_slug, &entity_ids, config, snapshot_time)?; |
| 230 | let walked = score::walk_paths(config, &anchors, &graph.adjacency, &graph.direct); |
| 231 | let ranked = score::fuse_and_rank(config, &baseline_pairs, &walked.graph_score); |
| 232 | let treatment_latency_ms = elapsed_ms(treatment_started); |
| 233 | let treatment_ids: Vec<String> = ranked.iter().map(|item| item.id.clone()).collect(); |
| 234 | |
| 235 | let baseline_ndcg = metrics::ndcg_at_k(&baseline_ids, &case.relevant_entity_ids, config.top_k); |
| 236 | let treatment_ndcg = |
| 237 | metrics::ndcg_at_k(&treatment_ids, &case.relevant_entity_ids, config.top_k); |
| 238 | let relative_ndcg = if baseline_ndcg > 0.0 { |
| 239 | Some((treatment_ndcg - baseline_ndcg) / baseline_ndcg) |
| 240 | } else { |
| 241 | None |
| 242 | }; |
| 243 | let baseline_recall = |
| 244 | metrics::recall_at_k(&baseline_ids, &case.relevant_entity_ids, config.top_k); |
| 245 | let treatment_recall = |
| 246 | metrics::recall_at_k(&treatment_ids, &case.relevant_entity_ids, config.top_k); |
| 247 | let entity_bytes = entity_ids.len() as u64 * config.entity_bytes; |
| 248 | let top_bytes = config.top_k as u64 * config.result_bytes; |
| 249 | let suggestions = walked |
| 250 | .suggestions |
| 251 | .iter() |
| 252 | .map(|(subject, object, suggestion_score)| CandidateSuggestion { |
| 253 | query_id: case.id.clone(), |
| 254 | subject: subject.clone(), |
| 255 | predicate: config.suggestion_predicate.clone(), |
| 256 | object: object.clone(), |
| 257 | score: *suggestion_score, |
| 258 | }) |
| 259 | .collect(); |
| 260 | |
| 261 | Ok(QueryRow { |
| 262 | query_id: case.id.clone(), |
| 263 | baseline_ids, |
| 264 | treatment_ids, |
| 265 | baseline_ndcg, |
| 266 | treatment_ndcg, |
| 267 | absolute_ndcg_delta: treatment_ndcg - baseline_ndcg, |
| 268 | relative_ndcg, |
| 269 | baseline_recall, |
| 270 | treatment_recall, |
| 271 | baseline_latency_ms, |
| 272 | treatment_latency_ms, |
| 273 | baseline_accounted_bytes: entity_bytes + top_bytes, |
| 274 | treatment_accounted_bytes: entity_bytes |
| 275 | + graph.edges as u64 * config.edge_bytes |
| 276 | + walked.paths_scored as u64 * config.path_bytes |
| 277 | + top_bytes, |
| 278 | paths_scored: walked.paths_scored, |
| 279 | suggestions, |
| 280 | }) |
| 281 | } |
| 282 | |
| 283 | fn build_report( |
| 284 | config: &ExperimentConfig, |
| 285 | queries: Vec<QueryRow>, |
| 286 | source_hash: &str, |
| 287 | fixture_hash: &str, |
| 288 | binary_hash: &str, |
| 289 | snapshot_time: DateTime<Utc>, |
| 290 | writes: u64, |
| 291 | ) -> Result<ExperimentReport, String> { |
| 292 | let relatives: Vec<f64> = queries.iter().filter_map(|row| row.relative_ndcg).collect(); |
| 293 | let relative_mean_ndcg = if relatives.is_empty() { |
| 294 | None |
| 295 | } else { |
| 296 | Some(metrics::mean(&relatives)) |
| 297 | }; |
| 298 | let absolute_mean_ndcg_delta = metrics::mean( |
| 299 | &queries |
| 300 | .iter() |
| 301 | .map(|row| row.absolute_ndcg_delta) |
| 302 | .collect::<Vec<_>>(), |
| 303 | ); |
| 304 | let zero_baseline = queries |
| 305 | .iter() |
| 306 | .filter(|row| row.baseline_ndcg == 0.0) |
| 307 | .map(|row| ZeroBaselineRow { |
| 308 | query_id: row.query_id.clone(), |
| 309 | baseline_ndcg: row.baseline_ndcg, |
| 310 | treatment_ndcg: row.treatment_ndcg, |
| 311 | absolute_delta: row.absolute_ndcg_delta, |
| 312 | }) |
| 313 | .collect(); |
| 314 | let recall_at_10_delta = metrics::mean( |
| 315 | &queries |
| 316 | .iter() |
| 317 | .map(|row| row.treatment_recall - row.baseline_recall) |
| 318 | .collect::<Vec<_>>(), |
| 319 | ); |
| 320 | let baseline_p95_ms = |
| 321 | metrics::percentile_95(queries.iter().map(|row| row.baseline_latency_ms).collect()); |
| 322 | let treatment_p95_ms = |
| 323 | metrics::percentile_95(queries.iter().map(|row| row.treatment_latency_ms).collect()); |
| 324 | let interval = |
| 325 | metrics::bootstrap_mean_ci(&relatives, config.bootstrap_samples, config.bootstrap_seed); |
| 326 | let ci_ok = interval.map(ci_excludes_zero).unwrap_or(false); |
| 327 | let latency_ok = treatment_p95_ms <= 1.5 * baseline_p95_ms.max(f64::EPSILON); |
| 328 | let baseline_peak = queries |
| 329 | .iter() |
| 330 | .map(|row| row.baseline_accounted_bytes) |
| 331 | .max() |
| 332 | .unwrap_or(0); |
| 333 | let treatment_peak = queries |
| 334 | .iter() |
| 335 | .map(|row| row.treatment_accounted_bytes) |
| 336 | .max() |
| 337 | .unwrap_or(0); |
| 338 | let memory_ok = treatment_peak as f64 <= 2.0 * baseline_peak.max(1) as f64; |
| 339 | let recall_ok = recall_at_10_delta >= -0.01; |
| 340 | let gain_ok = relative_mean_ndcg.unwrap_or(0.0) >= 0.05; |
| 341 | let pass = writes == 0 && ci_ok && latency_ok && memory_ok && recall_ok && gain_ok; |
| 342 | let strong_pass = pass |
| 343 | && relative_mean_ndcg.unwrap_or(0.0) >= 0.10 |
| 344 | && recall_at_10_delta > 0.0 |
| 345 | && treatment_p95_ms <= 1.25 * baseline_p95_ms.max(f64::EPSILON); |
| 346 | let config_sha256 = sha256_bytes(&config.canonical_json()?); |
| 347 | |
| 348 | Ok(ExperimentReport { |
| 349 | dataset_snapshot_sha256: source_hash.to_string(), |
| 350 | eval_fixture_sha256: fixture_hash.to_string(), |
| 351 | experiment_binary_sha256: binary_hash.to_string(), |
| 352 | config_sha256, |
| 353 | snapshot_time: snapshot_time.to_rfc3339(), |
| 354 | queries, |
| 355 | relative_mean_ndcg, |
| 356 | absolute_mean_ndcg_delta, |
| 357 | zero_baseline, |
| 358 | recall_at_10_delta, |
| 359 | baseline_p95_ms, |
| 360 | treatment_p95_ms, |
| 361 | baseline_peak_accounted_bytes: baseline_peak, |
| 362 | treatment_peak_accounted_bytes: treatment_peak, |
| 363 | bootstrap_low: interval.map(|pair| pair.0), |
| 364 | bootstrap_high: interval.map(|pair| pair.1), |
| 365 | writes, |
| 366 | pass, |
| 367 | strong_pass, |
| 368 | fail: !pass, |
| 369 | }) |
| 370 | } |
| 371 | |
| 372 | fn elapsed_ms(started: Instant) -> f64 { |
| 373 | started.elapsed().as_secs_f64() * 1000.0 |
| 374 | } |
| 375 | |
| 376 | fn refuse_sidecar(snapshot: &Path) -> Result<(), String> { |
| 377 | for suffix in ["-wal", "-shm"] { |
| 378 | let sidecar = PathBuf::from(format!("{}{suffix}", snapshot.display())); |
| 379 | if sidecar.exists() { |
| 380 | return Err(format!( |
| 381 | "snapshot has {suffix}; checkpoint it to one file before hashing" |
| 382 | )); |
| 383 | } |
| 384 | } |
| 385 | Ok(()) |
| 386 | } |
| 387 | |
| 388 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 389 | struct TableCounts { |
| 390 | memory_candidates: i64, |
| 391 | promotion_receipts: i64, |
| 392 | claims: i64, |
| 393 | } |
| 394 | |
| 395 | fn table_counts(path: &Path) -> Result<TableCounts, String> { |
| 396 | let conn = |
| 397 | rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) |
| 398 | .map_err(|err| err.to_string())?; |
| 399 | let one = |sql: &str| -> Result<i64, String> { |
| 400 | conn.query_row(sql, [], |row| row.get(0)) |
| 401 | .map_err(|err| err.to_string()) |
| 402 | }; |
| 403 | Ok(TableCounts { |
| 404 | memory_candidates: one("SELECT COUNT(*) FROM memory_candidates")?, |
| 405 | promotion_receipts: one("SELECT COUNT(*) FROM promotion_receipts")?, |
| 406 | claims: one("SELECT COUNT(*) FROM claims")?, |
| 407 | }) |
| 408 | } |
| 409 | |
| 410 | fn count_delta(before: &TableCounts, after: &TableCounts) -> u64 { |
| 411 | let candidates = (after.memory_candidates - before.memory_candidates).max(0) as u64; |
| 412 | let promotions = (after.promotion_receipts - before.promotion_receipts).max(0) as u64; |
| 413 | let claims = (after.claims - before.claims).max(0) as u64; |
| 414 | candidates + promotions + claims |
| 415 | } |