spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / tests / test_explain_evidence_graph.rs
| 1 | //! RSI -> explanation evidence graph (contract aien.explain.evidence-graph v1). |
| 2 | //! |
| 3 | //! Builds one RSI cycle from the real types (capability graph, bottleneck ranking, |
| 4 | //! hypothesis contract built the way the daemon builds it, diagnostic context, |
| 5 | //! evaluation receipt, ratification record) and checks the emitted document. The |
| 6 | //! golden file tests/fixtures/rsi_kv_cycle.evidence.json is shared byte for byte with |
| 7 | //! aien-dev/aienux crates/aienos-explain, which builds and renders the explanation. |
| 8 | //! Regenerate with EXPLAIN_BLESS=1 and copy it to aienos. |
| 9 | |
| 10 | use sha2::{Digest, Sha256}; |
| 11 | use spark_rsi::evaluator::{EvaluationMetricsSummary, EvaluationReceipt, LayerResult}; |
| 12 | use spark_rsi::explain::{ |
| 13 | conclusion_id, evidence_graph, hypothesis_derived_from, EvidenceGraphDoc, MetricsOrigin, |
| 14 | RsiCycleEvidence, FORMAT, KIND_HYPOTHESIS, REL_REFERENCES, STATUS_HYPOTHESIS, |
| 15 | STATUS_UNCLASSIFIED, STATUS_VERIFIED_FACT, VERSION, |
| 16 | }; |
| 17 | use spark_rsi::graph::{CapabilityGraph, CapabilityNode}; |
| 18 | use spark_rsi::models::RatificationRecord; |
| 19 | use spark_rsi::propose::diagnose::{DefectCategory, DiagnosticContext}; |
| 20 | use spark_rsi::propose::hypothesis::HypothesisContract; |
| 21 | |
| 22 | const CYCLE: &str = "cycle-kv-0001"; |
| 23 | const FIXTURE: &str = "tests/fixtures/rsi_kv_cycle.evidence.json"; |
| 24 | /// sha256 of the fixture; the aienos side asserts the same value. |
| 25 | const FIXTURE_SHA256: &str = "7e9f1c1e09210fb3158cd001ecb6207d4d5c3fbd30996448c35c61dc900fc07d"; |
| 26 | |
| 27 | fn kv_graph() -> CapabilityGraph { |
| 28 | let mut g = CapabilityGraph::new(); |
| 29 | g.add_node( |
| 30 | CapabilityNode::new("req_gateway", "Request Gateway", "network") |
| 31 | .with_measured_latency(120.0, None, 0.0, 5) |
| 32 | .unwrap(), |
| 33 | ); |
| 34 | g.add_node( |
| 35 | CapabilityNode::new("scheduler", "Batch Scheduler", "scheduling") |
| 36 | .with_measured_latency(340.0, None, 0.0, 5) |
| 37 | .unwrap(), |
| 38 | ); |
| 39 | g.add_node( |
| 40 | CapabilityNode::new("kv_allocator", "Unified LPDDR5x KV Allocator", "memory") |
| 41 | .with_measured_latency(4200.0, Some(5100.0), 0.08, 20) |
| 42 | .unwrap(), |
| 43 | ); |
| 44 | g.add_node( |
| 45 | CapabilityNode::new("mojo_kernel", "Mojo Blackwell GEMM Kernel", "compute") |
| 46 | .with_measured_latency(1800.0, None, 0.01, 5) |
| 47 | .unwrap(), |
| 48 | ); |
| 49 | g.add_node( |
| 50 | CapabilityNode::new("sampler", "Greedy Token Sampler", "inference") |
| 51 | .with_measured_latency(150.0, None, 0.0, 5) |
| 52 | .unwrap(), |
| 53 | ); |
| 54 | g.add_edge("req_gateway", "scheduler", 100.0, 1.0); |
| 55 | g.add_edge("scheduler", "kv_allocator", 500.0, 1.0); |
| 56 | g.add_edge("kv_allocator", "mojo_kernel", 1200.0, 1.0); |
| 57 | g.add_edge("mojo_kernel", "sampler", 200.0, 1.0); |
| 58 | g |
| 59 | } |
| 60 | |
| 61 | /// Same construction as RsiEngine::run_cycle in src/daemon.rs (step 5, measured branch). |
| 62 | fn daemon_style_hypothesis(b: &spark_rsi::graph::BottleneckRank) -> HypothesisContract { |
| 63 | HypothesisContract::new( |
| 64 | "hypo-kv-0001", |
| 65 | CYCLE, |
| 66 | &format!( |
| 67 | "System throughput limited by bottleneck node '{}' (centrality={:.4})", |
| 68 | b.node_name, b.centrality |
| 69 | ), |
| 70 | &format!( |
| 71 | "High latency on '{}': {}", |
| 72 | b.node_name, b.causal_explanation |
| 73 | ), |
| 74 | "latency_median_us", |
| 75 | b.latency_median_us.expect("measured"), |
| 76 | 5.0, |
| 77 | ) |
| 78 | .with_protected_metric("correctness", 0.0) |
| 79 | .with_falsification_test("assert!(receipt.passed_all_hard_invariants)") |
| 80 | } |
| 81 | |
| 82 | fn receipt() -> EvaluationReceipt { |
| 83 | let layers = vec![ |
| 84 | LayerResult { |
| 85 | layer_name: "Correctness".into(), |
| 86 | is_hard_invariant: true, |
| 87 | passed: true, |
| 88 | score: 1.0, |
| 89 | summary: "all holdouts pass".into(), |
| 90 | violations: vec![], |
| 91 | }, |
| 92 | LayerResult { |
| 93 | layer_name: "Performance".into(), |
| 94 | is_hard_invariant: false, |
| 95 | passed: true, |
| 96 | score: 0.82, |
| 97 | summary: "p95 improved".into(), |
| 98 | violations: vec![], |
| 99 | }, |
| 100 | ]; |
| 101 | let digest = EvaluationReceipt::compute_digest(CYCLE, "cand-kv-0001", "parent", true, &layers); |
| 102 | EvaluationReceipt { |
| 103 | cycle_id: CYCLE.into(), |
| 104 | candidate_id: "cand-kv-0001".into(), |
| 105 | parent_id: "parent".into(), |
| 106 | evaluated_at: "2026-10-01T00:00:00Z".into(), |
| 107 | evaluator_version: "test".into(), |
| 108 | passed_all_hard_invariants: true, |
| 109 | passed_statistical_gates: true, |
| 110 | admitted: true, |
| 111 | layer_results: layers, |
| 112 | metrics_summary: Some(EvaluationMetricsSummary { |
| 113 | latency_delta_pct: -17.5, |
| 114 | p_value: 0.004, |
| 115 | p95_ci_upper_degradation_pct: -9.0, |
| 116 | p99_ci_upper_degradation_pct: -4.0, |
| 117 | rss_growth_pct: 0.5, |
| 118 | candidate_resident_mb: 512, |
| 119 | }), |
| 120 | receipt_digest: digest, |
| 121 | signature: None, |
| 122 | format_version: 1, |
| 123 | binding: None, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn ratification() -> RatificationRecord { |
| 128 | RatificationRecord { |
| 129 | proposal_id: "cand-kv-0001".into(), |
| 130 | commit_hash: None, |
| 131 | branch: None, |
| 132 | patch_path: None, |
| 133 | author: "test".into(), |
| 134 | cortex_receipt_id: None, |
| 135 | cortex_recorded: false, |
| 136 | timestamp: "2026-10-01T00:00:01Z".into(), |
| 137 | status: "Ratified".into(), |
| 138 | message: "test record".into(), |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn kv_cycle_doc() -> EvidenceGraphDoc { |
| 143 | let g = kv_graph(); |
| 144 | let ranks = g.rank_bottlenecks(); |
| 145 | let h = daemon_style_hypothesis(&ranks[0]); |
| 146 | let diag = DiagnosticContext::from_violations( |
| 147 | CYCLE, |
| 148 | "src/kv_allocator.rs", |
| 149 | "SOURCE TEXT MUST NOT APPEAR IN EVIDENCE", |
| 150 | DefectCategory::PerformanceRegression, |
| 151 | vec![format!("Bottleneck identified at {}", ranks[0].node_name)], |
| 152 | vec!["LESSON TEXT MUST NOT APPEAR IN EVIDENCE".into()], |
| 153 | ) |
| 154 | .with_hypothesis(h.clone()); |
| 155 | let r = receipt(); |
| 156 | let rat = ratification(); |
| 157 | evidence_graph(&RsiCycleEvidence { |
| 158 | cycle_id: CYCLE, |
| 159 | graph: Some(&g), |
| 160 | metrics_origin: MetricsOrigin::Measured, |
| 161 | bottlenecks: &ranks, |
| 162 | hypothesis: Some(&h), |
| 163 | diagnostic: Some(&diag), |
| 164 | receipt: Some(&r), |
| 165 | ratification: Some(&rat), |
| 166 | }) |
| 167 | } |
| 168 | |
| 169 | fn find<'a>(d: &'a EvidenceGraphDoc, id: &str) -> &'a spark_rsi::explain::NodeDoc { |
| 170 | d.nodes |
| 171 | .iter() |
| 172 | .find(|n| n.id == id) |
| 173 | .unwrap_or_else(|| panic!("node {id}")) |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn rsi_cycle_emits_contract_v1_with_explicit_links_only() { |
| 178 | let d = kv_cycle_doc(); |
| 179 | assert_eq!(d.format, FORMAT); |
| 180 | assert_eq!(d.version, VERSION); |
| 181 | |
| 182 | // Observed: five capability nodes with measured metrics. |
| 183 | let caps: Vec<_> = d |
| 184 | .nodes |
| 185 | .iter() |
| 186 | .filter(|n| n.id.starts_with("rsi:capability:")) |
| 187 | .collect(); |
| 188 | assert_eq!(caps.len(), 5); |
| 189 | assert!(caps.iter().all(|n| n.status == 1)); |
| 190 | // Only the allocator has enough samples for a p95; the rest declare it unavailable. |
| 191 | assert_eq!(caps.iter().filter(|n| n.missing.is_empty()).count(), 1); |
| 192 | |
| 193 | // System analysis rests on the metrics; alternatives are AlternativeTo, not support. |
| 194 | let a = find(&d, &format!("rsi:bottleneck:{CYCLE}")); |
| 195 | assert_eq!(a.parents.len(), 5); |
| 196 | assert!(a.statement.contains("Unified LPDDR5x KV Allocator")); |
| 197 | let alts: Vec<_> = d |
| 198 | .nodes |
| 199 | .iter() |
| 200 | .filter(|n| n.id.starts_with("rsi:alternative:")) |
| 201 | .collect(); |
| 202 | assert_eq!(alts.len(), 3); |
| 203 | assert!(alts |
| 204 | .iter() |
| 205 | .all(|n| n.parents.len() == 1 && n.parents[0].relation == 5)); |
| 206 | |
| 207 | // Hypothesis keeps its status and declared confidence, and links to the analysis. |
| 208 | let h = find(&d, "rsi:hypothesis:hypo-kv-0001"); |
| 209 | assert_eq!(h.kind, KIND_HYPOTHESIS); |
| 210 | assert_eq!(h.status, STATUS_HYPOTHESIS); |
| 211 | assert_eq!(h.confidence_permille, Some(850)); |
| 212 | assert!(h |
| 213 | .confidence_basis |
| 214 | .as_deref() |
| 215 | .unwrap() |
| 216 | .contains("not measured")); |
| 217 | // Matched by text and measured median only: a weak "references" link plus a declared gap. |
| 218 | assert_eq!(h.parents.len(), 1); |
| 219 | assert_eq!(h.parents[0].relation, REL_REFERENCES); |
| 220 | assert_eq!(h.missing.len(), 1); |
| 221 | assert!(h.missing[0].reason.contains("linked only because")); |
| 222 | |
| 223 | // Receipt digest verifies -> VerifiedFact; no fabricated Evaluates edge anywhere. |
| 224 | let r = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001")); |
| 225 | assert_eq!(r.status, STATUS_VERIFIED_FACT); |
| 226 | assert!(r.source.digest.is_some()); |
| 227 | assert!(!r.statement.contains("hard invariants")); |
| 228 | // Fields outside the receipt digest are reported, not verified. |
| 229 | let s = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001:summary")); |
| 230 | assert_eq!(s.status, STATUS_UNCLASSIFIED); |
| 231 | assert!(s.statement.contains("hard invariants passed=true")); |
| 232 | assert!(s |
| 233 | .notes |
| 234 | .iter() |
| 235 | .any(|t| t.contains("not covered by the receipt digest"))); |
| 236 | assert!(d |
| 237 | .nodes |
| 238 | .iter() |
| 239 | .all(|n| n.parents.iter().all(|e| e.relation != 2))); |
| 240 | |
| 241 | // The candidate-to-hypothesis gap is declared, not bridged. |
| 242 | let c = find(&d, &conclusion_id(CYCLE)); |
| 243 | assert!(c |
| 244 | .missing |
| 245 | .iter() |
| 246 | .any(|m| m.expected.contains("linking candidate cand-kv-0001"))); |
| 247 | assert!(c.notes.iter().any(|t| t.contains("does not authorize"))); |
| 248 | |
| 249 | // Source code and outside free-text lessons never enter the evidence. |
| 250 | let json = String::from_utf8(d.to_json()).unwrap(); |
| 251 | assert!(!json.contains("SOURCE TEXT MUST NOT APPEAR")); |
| 252 | assert!(!json.contains("LESSON TEXT MUST NOT APPEAR")); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn hypothesis_not_from_bottleneck_is_declared_missing() { |
| 257 | let g = kv_graph(); |
| 258 | let ranks = g.rank_bottlenecks(); |
| 259 | let unrelated = HypothesisContract::new( |
| 260 | "hypo-other", |
| 261 | CYCLE, |
| 262 | "Problem elsewhere", |
| 263 | "Some other cause", |
| 264 | "p95", |
| 265 | 1.0, |
| 266 | 5.0, |
| 267 | ); |
| 268 | assert!(!hypothesis_derived_from(&unrelated, &ranks[0])); |
| 269 | let d = evidence_graph(&RsiCycleEvidence { |
| 270 | cycle_id: CYCLE, |
| 271 | graph: Some(&g), |
| 272 | metrics_origin: MetricsOrigin::Measured, |
| 273 | bottlenecks: &ranks, |
| 274 | hypothesis: Some(&unrelated), |
| 275 | diagnostic: None, |
| 276 | receipt: None, |
| 277 | ratification: None, |
| 278 | }); |
| 279 | let h = find(&d, "rsi:hypothesis:hypo-other"); |
| 280 | assert!(h.parents.is_empty()); |
| 281 | assert_eq!(h.missing.len(), 1); |
| 282 | let c = find(&d, &conclusion_id(CYCLE)); |
| 283 | assert!(c |
| 284 | .missing |
| 285 | .iter() |
| 286 | .any(|m| m.expected.contains("evaluation receipt"))); |
| 287 | // Measured metrics are observations. |
| 288 | assert!(d |
| 289 | .nodes |
| 290 | .iter() |
| 291 | .filter(|n| n.id.starts_with("rsi:capability:")) |
| 292 | .all(|n| n.status == 1)); |
| 293 | } |
| 294 | |
| 295 | #[test] |
| 296 | fn tampered_receipt_is_not_a_verified_fact() { |
| 297 | let g = kv_graph(); |
| 298 | let ranks = g.rank_bottlenecks(); |
| 299 | let mut r = receipt(); |
| 300 | r.admitted = false; // digest no longer matches |
| 301 | let d = evidence_graph(&RsiCycleEvidence { |
| 302 | cycle_id: CYCLE, |
| 303 | graph: Some(&g), |
| 304 | metrics_origin: MetricsOrigin::Measured, |
| 305 | bottlenecks: &ranks, |
| 306 | hypothesis: None, |
| 307 | diagnostic: None, |
| 308 | receipt: Some(&r), |
| 309 | ratification: None, |
| 310 | }); |
| 311 | let n = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001")); |
| 312 | assert_eq!(n.status, STATUS_UNCLASSIFIED); |
| 313 | assert!(n.notes.iter().any(|t| t.contains("does not match"))); |
| 314 | } |
| 315 | |
| 316 | #[test] |
| 317 | fn rsi_evidence_graph_is_deterministic_and_matches_shared_fixture() { |
| 318 | let a = kv_cycle_doc().to_json_pretty(); |
| 319 | let b = kv_cycle_doc().to_json_pretty(); |
| 320 | assert_eq!(a, b, "same artifacts must give the same document"); |
| 321 | let bytes = format!("{a}\n"); |
| 322 | if std::env::var("EXPLAIN_BLESS").as_deref() == Ok("1") { |
| 323 | std::fs::write(FIXTURE, &bytes).unwrap(); |
| 324 | } |
| 325 | let on_disk = std::fs::read_to_string(FIXTURE).expect("fixture present"); |
| 326 | assert_eq!( |
| 327 | on_disk, bytes, |
| 328 | "fixture drifted; rerun with EXPLAIN_BLESS=1 and copy to aienos" |
| 329 | ); |
| 330 | let digest = hex::encode(Sha256::digest(on_disk.as_bytes())); |
| 331 | assert_eq!(digest, FIXTURE_SHA256, "update the pin here and in aienos"); |
| 332 | } |
| 333 | |
| 334 | #[test] |
| 335 | fn artifacts_from_another_cycle_are_not_attached() { |
| 336 | let g = kv_graph(); |
| 337 | let ranks = g.rank_bottlenecks(); |
| 338 | let mut r = receipt(); |
| 339 | r.cycle_id = "cycle-other".into(); |
| 340 | r.receipt_digest = EvaluationReceipt::compute_digest( |
| 341 | &r.cycle_id, |
| 342 | &r.candidate_id, |
| 343 | &r.parent_id, |
| 344 | r.admitted, |
| 345 | &r.layer_results, |
| 346 | ); |
| 347 | let h = daemon_style_hypothesis(&ranks[0]); |
| 348 | let d = evidence_graph(&RsiCycleEvidence { |
| 349 | cycle_id: CYCLE, |
| 350 | graph: Some(&g), |
| 351 | metrics_origin: MetricsOrigin::Measured, |
| 352 | bottlenecks: &ranks, |
| 353 | hypothesis: Some(&h), |
| 354 | diagnostic: None, |
| 355 | receipt: Some(&r), |
| 356 | ratification: None, |
| 357 | }); |
| 358 | assert!(d.nodes.iter().all(|n| !n.id.starts_with("rsi:receipt:"))); |
| 359 | let c = find(&d, &conclusion_id(CYCLE)); |
| 360 | assert!(c |
| 361 | .missing |
| 362 | .iter() |
| 363 | .any(|m| m.reason.contains("belongs to cycle cycle-other"))); |
| 364 | } |