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/spark-rsi-mv/blob/main/src/explain.rs # spark-rsi-mv Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger 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 `spark-rsi-mv / src / explain.rs` 792 lines ยท 29714 bytes Raw Blame History 1 //! "Why does RSI want to change this?" as an evidence graph. 2 //! 3 //! This module turns the real artifacts of one RSI cycle (capability graph, 4 //! bottleneck ranking, hypothesis contract, diagnostic context, evaluation receipt, 5 //! ratification record) into the language-neutral evidence-graph contract 6 //! `aien.explain.evidence-graph` v1. The aienos `aienos-explain` crate builds the 7 //! grounded explanation path from that document and renders it; spark-rsi has no 8 //! compile-time dependency on aienos. 9 //! 10 //! Rules kept here: 11 //! - only explicit fields become links (ids, cycle ids, candidate ids); where RSI has 12 //! no artifact for a link, the link is declared missing instead of invented; 13 //! - nothing here changes evaluation, safety, ratification or promotion; the 14 //! explanation is observational and authorizes nothing; 15 //! - free-text "lessons" from the outside memory service and model output are not 16 //! evidence and are never included. 17 18 use crate::evaluator::EvaluationReceipt; 19 use crate::graph::{BottleneckRank, CapabilityGraph, Measurement, RankingBasis}; 20 use crate::models::RatificationRecord; 21 use crate::propose::diagnose::DiagnosticContext; 22 use crate::propose::hypothesis::HypothesisContract; 23 use serde::{Deserialize, Serialize}; 24 25 pub const FORMAT: &str = "aien.explain.evidence-graph"; 26 pub const VERSION: u16 = 1; 27 pub const PRODUCER: &str = "spark-rsi/explain"; 28 29 // Contract codes (see aienos docs/EXPLAIN_EVIDENCE_GRAPH_V1.md). 30 pub const STATUS_UNCLASSIFIED: u8 = 0; 31 pub const STATUS_DIRECT_OBSERVATION: u8 = 1; 32 pub const STATUS_VERIFIED_FACT: u8 = 2; 33 pub const STATUS_INFERENCE: u8 = 3; 34 pub const STATUS_HYPOTHESIS: u8 = 4; 35 36 pub const KIND_CAPABILITY_METRIC: u16 = 2; 37 pub const KIND_CAPABILITY_ANALYSIS: u16 = 3; 38 pub const KIND_DIAGNOSTIC: u16 = 4; 39 pub const KIND_HYPOTHESIS: u16 = 5; 40 pub const KIND_PREDICTION: u16 = 6; 41 pub const KIND_FALSIFICATION: u16 = 7; 42 pub const KIND_EVALUATION_RECEIPT: u16 = 8; 43 pub const KIND_PROMOTION_STATE: u16 = 9; 44 pub const KIND_CONCLUSION: u16 = 12; 45 pub const KIND_ALTERNATIVE: u16 = 13; 46 47 pub const REL_SUPPORTED_BY: u16 = 1; 48 pub const REL_PART_OF: u16 = 3; 49 pub const REL_ALTERNATIVE_TO: u16 = 5; 50 pub const REL_REFERENCES: u16 = 6; 51 52 /// Most alternatives listed from the bottleneck ranking (rank 2 onward). 53 pub const MAX_ALTERNATIVES: usize = 3; 54 /// Contract cap on parents per node (`MAX_PARENTS_PER_NODE` in the contract). 55 pub const MAX_PARENTS: usize = 1024; 56 57 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 58 pub struct SourceRefDoc { 59 pub system: String, 60 pub artifact: String, 61 pub reference: String, 62 #[serde(default, skip_serializing_if = "Option::is_none")] 63 pub digest: Option, 64 } 65 66 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 67 pub struct MeasurementDoc { 68 pub name: String, 69 pub value: String, 70 #[serde(default)] 71 pub unit: String, 72 } 73 74 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 75 pub struct EdgeDoc { 76 pub to: String, 77 pub relation: u16, 78 } 79 80 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 81 pub struct MissingDoc { 82 pub expected: String, 83 pub reason: String, 84 } 85 86 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 87 pub struct NodeDoc { 88 pub id: String, 89 pub kind: u16, 90 pub status: u8, 91 pub statement: String, 92 pub source: SourceRefDoc, 93 #[serde(default, skip_serializing_if = "Option::is_none")] 94 pub confidence_permille: Option, 95 #[serde(default, skip_serializing_if = "Option::is_none")] 96 pub confidence_basis: Option, 97 #[serde(default, skip_serializing_if = "Option::is_none")] 98 pub recorded_at_utc: Option, 99 #[serde(default)] 100 pub parents: Vec, 101 #[serde(default)] 102 pub measurements: Vec, 103 #[serde(default)] 104 pub missing: Vec, 105 #[serde(default)] 106 pub notes: Vec, 107 } 108 109 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 110 pub struct EvidenceGraphDoc { 111 pub format: String, 112 pub version: u16, 113 pub producer: String, 114 pub nodes: Vec, 115 #[serde(default)] 116 pub truncated_at: Vec, 117 } 118 119 impl EvidenceGraphDoc { 120 /// Canonical JSON bytes (struct field order, node order as built). 121 pub fn to_json(&self) -> Vec { 122 serde_json::to_vec(self).expect("evidence graph serializes") 123 } 124 125 pub fn to_json_pretty(&self) -> String { 126 serde_json::to_string_pretty(self).expect("evidence graph serializes") 127 } 128 } 129 130 /// Where capability metrics come from. Every value present in the graph is measured from stage 131 /// samples; a stage without enough samples is marked unavailable on its node (and in the 132 /// evidence as a `MissingDoc`), never filled with a number. 133 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 134 pub enum MetricsOrigin { 135 Measured, 136 } 137 138 /// The artifacts of one RSI cycle, all optional except the cycle id. 139 pub struct RsiCycleEvidence<'a> { 140 pub cycle_id: &'a str, 141 pub graph: Option<&'a CapabilityGraph>, 142 pub metrics_origin: MetricsOrigin, 143 /// Bottleneck ranking as returned by `CapabilityGraph::rank_bottlenecks`. 144 pub bottlenecks: &'a [BottleneckRank], 145 pub hypothesis: Option<&'a HypothesisContract>, 146 pub diagnostic: Option<&'a DiagnosticContext>, 147 pub receipt: Option<&'a EvaluationReceipt>, 148 pub ratification: Option<&'a RatificationRecord>, 149 } 150 151 fn src(artifact: &str, reference: &str, digest: Option) -> SourceRefDoc { 152 SourceRefDoc { 153 system: "spark-rsi".into(), 154 artifact: artifact.into(), 155 reference: reference.into(), 156 digest, 157 } 158 } 159 160 fn m(name: &str, value: String, unit: &str) -> MeasurementDoc { 161 MeasurementDoc { 162 name: name.into(), 163 value, 164 unit: unit.into(), 165 } 166 } 167 168 fn node(id: String, kind: u16, status: u8, statement: String, source: SourceRefDoc) -> NodeDoc { 169 NodeDoc { 170 id, 171 kind, 172 status, 173 statement, 174 source, 175 confidence_permille: None, 176 confidence_basis: None, 177 recorded_at_utc: None, 178 parents: Vec::new(), 179 measurements: Vec::new(), 180 missing: Vec::new(), 181 notes: Vec::new(), 182 } 183 } 184 185 fn edge(to: &str, relation: u16) -> EdgeDoc { 186 EdgeDoc { 187 to: to.to_string(), 188 relation, 189 } 190 } 191 192 pub fn capability_node_id(node_id: &str) -> String { 193 format!("rsi:capability:{node_id}") 194 } 195 pub fn analysis_id(cycle_id: &str) -> String { 196 format!("rsi:bottleneck:{cycle_id}") 197 } 198 pub fn hypothesis_node_id(h: &HypothesisContract) -> String { 199 format!("rsi:hypothesis:{}", h.id) 200 } 201 pub fn diagnostic_id(cycle_id: &str) -> String { 202 format!("rsi:diagnostic:{cycle_id}") 203 } 204 pub fn receipt_node_id(r: &EvaluationReceipt) -> String { 205 format!("rsi:receipt:{}:{}", r.cycle_id, r.candidate_id) 206 } 207 pub fn ratification_id(r: &RatificationRecord) -> String { 208 format!("rsi:ratification:{}", r.proposal_id) 209 } 210 /// Id of the node to explain: "why does RSI want to change this?" 211 pub fn conclusion_id(cycle_id: &str) -> String { 212 format!("rsi:conclusion:{cycle_id}") 213 } 214 215 /// True when the hypothesis was built from this bottleneck the way the daemon builds 216 /// it: the node name appears quoted in the problem or root cause text, and the 217 /// baseline is the bottleneck's measured median latency (an exploratory hypothesis has no 218 /// baseline, so it matches only when the bottleneck has no measured latency either). This is a deterministic check on 219 /// explicit fields, not a guess; when it fails the link is declared missing. 220 pub fn hypothesis_derived_from(h: &HypothesisContract, b: &BottleneckRank) -> bool { 221 let quoted = format!("'{}'", b.node_name); 222 (h.observed_problem.contains("ed) || h.suspected_root_cause.contains("ed)) 223 && match (h.latency_claim(), b.latency_median_us) { 224 (Some((baseline, _)), Some(median)) => baseline == median, 225 (None, None) => true, 226 _ => false, 227 } 228 } 229 230 /// Build the evidence graph for one RSI cycle. Deterministic: node order is fixed, 231 /// capability nodes are sorted by id, numbers use fixed decimal formats. 232 pub fn evidence_graph(ev: &RsiCycleEvidence<'_>) -> EvidenceGraphDoc { 233 let mut nodes: Vec = Vec::new(); 234 let cycle = ev.cycle_id; 235 // Artifacts from another cycle are never attached; each mismatch is declared. 236 let mut foreign: Vec = Vec::new(); 237 let mut same_cycle = |what: &str, id: &str, their_cycle: &str| -> bool { 238 if their_cycle == cycle { 239 true 240 } else { 241 foreign.push(MissingDoc { 242 expected: format!("the {what} for cycle {cycle}"), 243 reason: format!( 244 "the supplied {what} {id} belongs to cycle {their_cycle}; it was left out" 245 ), 246 }); 247 false 248 } 249 }; 250 let hypothesis = ev 251 .hypothesis 252 .filter(|h| same_cycle("hypothesis", &h.id, &h.cycle_id)); 253 let diagnostic = ev 254 .diagnostic 255 .filter(|d| same_cycle("diagnostic", &d.target_file, &d.cycle_id)); 256 let receipt = ev 257 .receipt 258 .filter(|r| same_cycle("evaluation receipt", &r.candidate_id, &r.cycle_id)); 259 let MetricsOrigin::Measured = ev.metrics_origin; 260 261 // Observed: capability metrics. 262 let mut metric_ids: Vec = Vec::new(); 263 if let Some(g) = ev.graph { 264 let mut caps: Vec<_> = g.nodes.values().collect(); 265 caps.sort_by(|a, b| a.id.cmp(&b.id)); 266 for c in caps { 267 let id = capability_node_id(&c.id); 268 let measured = c.measurement == Measurement::Measured && c.latency_median_us.is_some(); 269 let mut n = node( 270 id.clone(), 271 KIND_CAPABILITY_METRIC, 272 if measured { 273 STATUS_DIRECT_OBSERVATION 274 } else { 275 STATUS_UNCLASSIFIED 276 }, 277 match c.latency_median_us.filter(|_| measured) { 278 Some(median) => format!( 279 "'{}' ({}) has measured median latency {:.1} us over {} samples", 280 c.name, c.subsystem, median, c.sample_count 281 ), 282 None => format!( 283 "'{}' ({}) has no measured latency (unavailable)", 284 c.name, c.subsystem 285 ), 286 }, 287 src("CapabilityNode", &c.id, None), 288 ); 289 let why = c 290 .unavailable_reason 291 .clone() 292 .unwrap_or_else(|| "no measurement".to_string()); 293 if measured { 294 n.measurements = vec![ 295 m( 296 "latency_median_us", 297 format!("{:.3}", c.latency_median_us.unwrap_or_default()), 298 "us", 299 ), 300 m("sample_count", c.sample_count.to_string(), ""), 301 ]; 302 if let Some(e) = c.error_rate_measured { 303 n.measurements 304 .push(m("error_rate_measured", format!("{:.6}", e), "fraction")); 305 } 306 match c.latency_p95_us_measured { 307 Some(p) => { 308 n.measurements 309 .push(m("latency_p95_us_measured", format!("{:.3}", p), "us")) 310 } 311 None => n.missing.push(MissingDoc { 312 expected: format!("measured p95 latency of stage '{}'", c.name), 313 reason: why, 314 }), 315 } 316 } else { 317 n.missing.push(MissingDoc { 318 expected: format!("measured median latency of stage '{}'", c.name), 319 reason: why.clone(), 320 }); 321 n.missing.push(MissingDoc { 322 expected: format!("measured error rate of stage '{}'", c.name), 323 reason: why, 324 }); 325 } 326 metric_ids.push(id); 327 nodes.push(n); 328 } 329 } 330 331 // System analysis: bottleneck ranking. 332 let top = ev.bottlenecks.first(); 333 let analysis = top.map(|b| { 334 let id = analysis_id(cycle); 335 let mut n = node( 336 id.clone(), 337 KIND_CAPABILITY_ANALYSIS, 338 STATUS_INFERENCE, 339 format!( 340 "The capability graph ranks '{}' ({}) as bottleneck #{} of {} ({})", 341 b.node_name, 342 b.subsystem, 343 b.rank, 344 ev.bottlenecks.len(), 345 b.causal_explanation 346 ), 347 src("BottleneckRank", &b.node_id, None), 348 ); 349 n.measurements = vec![ 350 m("bottleneck_score", format!("{:.4}", b.bottleneck_score), ""), 351 m("centrality", format!("{:.4}", b.centrality), ""), 352 m("ranking_basis", format!("{:?}", b.ranking_basis).to_lowercase(), ""), 353 ]; 354 match b.latency_median_us { 355 Some(v) => n.measurements.push(m("latency_median_us", format!("{:.3}", v), "us")), 356 None => n.missing.push(MissingDoc { 357 expected: format!("measured median latency of the top-ranked stage '{}'", b.node_name), 358 reason: b.unavailable_reason.clone().unwrap_or_else(|| "no measurement".to_string()), 359 }), 360 } 361 if b.ranking_basis == RankingBasis::Structural { 362 n.missing.push(MissingDoc { 363 expected: "latency and error terms of the bottleneck score".into(), 364 reason: "at least one stage is unavailable, so the ranking uses betweenness centrality only".into(), 365 }); 366 } 367 if metric_ids.is_empty() { 368 n.missing.push(MissingDoc { 369 expected: "capability metrics the ranking was computed from".into(), 370 reason: "no capability graph was supplied with this cycle".into(), 371 }); 372 } else { 373 n.parents = metric_ids 374 .iter() 375 .take(MAX_PARENTS) 376 .map(|i| edge(i, REL_SUPPORTED_BY)) 377 .collect(); 378 if metric_ids.len() > MAX_PARENTS { 379 n.notes.push(format!( 380 "only the first {MAX_PARENTS} of {} capability metrics are linked (contract cap)", 381 metric_ids.len() 382 )); 383 } 384 } 385 n.notes 386 .push("ranking computed by CapabilityGraph::rank_bottlenecks".into()); 387 nodes.push(n); 388 id 389 }); 390 391 // Alternatives explicitly present in the ranking. 392 if let Some(aid) = &analysis { 393 for b in ev.bottlenecks.iter().skip(1).take(MAX_ALTERNATIVES) { 394 let mut n = node( 395 format!("rsi:alternative:{cycle}:{}", b.node_id), 396 KIND_ALTERNATIVE, 397 STATUS_INFERENCE, 398 format!( 399 "Alternative bottleneck candidate #{}: '{}' ({}), score {:.4}", 400 b.rank, b.node_name, b.subsystem, b.bottleneck_score 401 ), 402 src("BottleneckRank", &b.node_id, None), 403 ); 404 n.parents = vec![edge(aid, REL_ALTERNATIVE_TO)]; 405 n.measurements = vec![m( 406 "bottleneck_score", 407 format!("{:.4}", b.bottleneck_score), 408 "", 409 )]; 410 nodes.push(n); 411 } 412 } 413 414 // Hypothesis, prediction, falsification. 415 let mut hyp_ids: Option<(String, String, String)> = None; 416 if let Some(h) = hypothesis { 417 let hid = hypothesis_node_id(h); 418 let mut n = node( 419 hid.clone(), 420 KIND_HYPOTHESIS, 421 STATUS_HYPOTHESIS, 422 format!( 423 "Suspected root cause: {}. Observed problem: {}", 424 h.suspected_root_cause, h.observed_problem 425 ), 426 src("HypothesisContract", &h.id, None), 427 ); 428 if h.confidence_score.is_finite() && !h.is_exploratory() { 429 n.confidence_permille = 430 Some((h.confidence_score.clamp(0.0, 1.0) * 1000.0).round() as u16); 431 n.confidence_basis = Some("declared in the HypothesisContract, not measured".into()); 432 } 433 match (top, &analysis) { 434 (Some(b), Some(aid)) if hypothesis_derived_from(h, b) => { 435 // A text and value match, not a recorded id: kept as a weak 436 // "references" link and the missing id is declared. 437 n.parents = vec![edge(aid, REL_REFERENCES)]; 438 n.missing.push(MissingDoc { 439 expected: "a recorded reference from the hypothesis to the bottleneck ranking" 440 .into(), 441 reason: format!( 442 "linked only because the hypothesis text names '{}' and its baseline \ 443 equals that bottleneck's p95 latency", 444 b.node_name 445 ), 446 }); 447 } 448 _ => n.missing.push(MissingDoc { 449 expected: "the system analysis this hypothesis was derived from".into(), 450 reason: "the HypothesisContract carries no bottleneck reference and does not \ 451 match the top-ranked bottleneck" 452 .into(), 453 }), 454 } 455 if let Err(e) = h.validate() { 456 n.notes 457 .push(format!("hypothesis contract fails validation: {e}")); 458 } 459 nodes.push(n); 460 461 let pid = format!("{hid}:prediction"); 462 let mut p = node( 463 pid.clone(), 464 KIND_PREDICTION, 465 STATUS_HYPOTHESIS, 466 match h.latency_claim() { 467 Some((baseline, delta)) => format!( 468 "Predicts {} improves by {:.1}% from baseline {:.3}", 469 h.target_metric, delta, baseline 470 ), 471 None => "Exploratory hypothesis: no performance prediction is made".to_string(), 472 }, 473 src("HypothesisContract", &h.id, None), 474 ); 475 p.parents = vec![edge(&hid, REL_PART_OF)]; 476 match h.latency_claim() { 477 Some((baseline, delta)) => { 478 p.measurements = vec![ 479 m("target_metric", h.target_metric.clone(), ""), 480 m("baseline_value", format!("{:.3}", baseline), ""), 481 m("predicted_delta_pct", format!("{:.3}", delta), "%"), 482 ]; 483 } 484 None => { 485 p.measurements = vec![m("target_metric", h.target_metric.clone(), "")]; 486 p.missing.push(MissingDoc { 487 expected: "a measured latency baseline and a predicted improvement".into(), 488 reason: "the top-ranked stage has no measured latency, so no performance claim is made".into(), 489 }); 490 } 491 } 492 nodes.push(p); 493 494 let fid = format!("{hid}:falsification"); 495 let protected: Vec = h 496 .protected_metrics 497 .iter() 498 .map(|pm| { 499 format!( 500 "{} may degrade at most {:.1}%", 501 pm.name, pm.max_allowed_degradation_pct 502 ) 503 }) 504 .collect(); 505 let mut f = node( 506 fid.clone(), 507 KIND_FALSIFICATION, 508 STATUS_HYPOTHESIS, 509 if h.falsification_test.is_empty() { 510 format!("Protected metrics: {}", protected.join("; ")) 511 } else { 512 format!( 513 "Refuted if this check fails: {}. Protected metrics: {}", 514 h.falsification_test, 515 protected.join("; ") 516 ) 517 }, 518 src("HypothesisContract", &h.id, None), 519 ); 520 f.parents = vec![edge(&hid, REL_PART_OF)]; 521 f.measurements = h 522 .protected_metrics 523 .iter() 524 .map(|pm| { 525 m( 526 &format!("protected.{}.max_degradation_pct", pm.name), 527 format!("{:.3}", pm.max_allowed_degradation_pct), 528 "%", 529 ) 530 }) 531 .collect(); 532 if h.falsification_test.is_empty() { 533 f.missing.push(MissingDoc { 534 expected: "a falsification test".into(), 535 reason: "the HypothesisContract has an empty falsification_test".into(), 536 }); 537 } 538 nodes.push(f); 539 hyp_ids = Some((hid, pid, fid)); 540 } 541 542 // Diagnostic context (explicitly carries the hypothesis it was built with). 543 let diag_id = diagnostic.map(|d| { 544 let id = diagnostic_id(cycle); 545 let mut n = node( 546 id.clone(), 547 KIND_DIAGNOSTIC, 548 STATUS_INFERENCE, 549 format!( 550 "Diagnosis for {}: primary defect {:?}; {}", 551 d.target_file, 552 d.primary_defect, 553 if d.violations.is_empty() { 554 "no violations listed".to_string() 555 } else { 556 d.violations.join("; ") 557 } 558 ), 559 src("DiagnosticContext", &d.cycle_id, None), 560 ); 561 match (&d.hypothesis, &hyp_ids) { 562 (Some(dh), Some((hid, _, _))) if hypothesis.map(|h| h.id == dh.id) == Some(true) => { 563 n.parents = vec![edge(hid, REL_SUPPORTED_BY)]; 564 } 565 (Some(dh), _) => n.missing.push(MissingDoc { 566 expected: format!("hypothesis {}", dh.id), 567 reason: "the diagnostic names a hypothesis that was not supplied".into(), 568 }), 569 (None, _) => n.missing.push(MissingDoc { 570 expected: "the hypothesis behind this diagnosis".into(), 571 reason: "the DiagnosticContext carries no hypothesis".into(), 572 }), 573 } 574 if !d.past_lessons.is_empty() { 575 n.notes.push(format!( 576 "{} recalled lesson(s) from the outside memory service were left out: they are \ 577 free text, not evidence", 578 d.past_lessons.len() 579 )); 580 } 581 nodes.push(n); 582 id 583 }); 584 585 // Evaluation receipt. The receipt digest covers cycle, candidate, parent, the 586 // admitted flag and the layer results only, so only those are stated on the 587 // receipt node (verified when the digest matches). The gate flags and the metrics 588 // summary are not covered by the digest; they go on a separate node whose status 589 // stays unknown. 590 let receipt_ids = receipt.map(|r| { 591 let id = receipt_node_id(r); 592 let digest_ok = r.verify_digest(); 593 let mut n = node( 594 id.clone(), 595 KIND_EVALUATION_RECEIPT, 596 if digest_ok { 597 STATUS_VERIFIED_FACT 598 } else { 599 STATUS_UNCLASSIFIED 600 }, 601 format!( 602 "Evaluation of candidate {} (parent {}): admitted={}, {} evaluation layer \ 603 result(s)", 604 r.candidate_id, 605 r.parent_id, 606 r.admitted, 607 r.layer_results.len() 608 ), 609 src( 610 "EvaluationReceipt", 611 &r.candidate_id, 612 Some(r.receipt_digest.clone()), 613 ), 614 ); 615 for l in &r.layer_results { 616 n.measurements.push(m( 617 &format!("layer.{}.passed", l.layer_name), 618 l.passed.to_string(), 619 "", 620 )); 621 n.measurements.push(m( 622 &format!("layer.{}.score", l.layer_name), 623 format!("{:.4}", l.score), 624 "", 625 )); 626 } 627 if !digest_ok { 628 n.notes 629 .push("the receipt digest does not match its contents".into()); 630 } 631 n.notes.push(if r.signature.is_some() { 632 "receipt is signed; the signature was not checked here (needs the evaluator public key)" 633 .into() 634 } else { 635 "receipt is unsigned".into() 636 }); 637 nodes.push(n); 638 639 let sid = format!("{id}:summary"); 640 let mut s = node( 641 sid.clone(), 642 KIND_EVALUATION_RECEIPT, 643 STATUS_UNCLASSIFIED, 644 format!( 645 "The evaluator reports: hard invariants passed={}, statistical gates passed={}", 646 r.passed_all_hard_invariants, r.passed_statistical_gates 647 ), 648 src("EvaluationReceipt", &r.candidate_id, None), 649 ); 650 s.parents = vec![edge(&id, REL_PART_OF)]; 651 if let Some(ms) = &r.metrics_summary { 652 s.measurements.extend([ 653 m( 654 "latency_delta_pct", 655 format!("{:.3}", ms.latency_delta_pct), 656 "%", 657 ), 658 m("p_value", format!("{:.6}", ms.p_value), ""), 659 m( 660 "p95_ci_upper_degradation_pct", 661 format!("{:.3}", ms.p95_ci_upper_degradation_pct), 662 "%", 663 ), 664 m( 665 "p99_ci_upper_degradation_pct", 666 format!("{:.3}", ms.p99_ci_upper_degradation_pct), 667 "%", 668 ), 669 m("rss_growth_pct", format!("{:.3}", ms.rss_growth_pct), "%"), 670 ]); 671 } 672 s.notes.push( 673 "these fields are not covered by the receipt digest, so they are reported, not \ 674 verified" 675 .into(), 676 ); 677 nodes.push(s); 678 (id, sid) 679 }); 680 681 // Promotion / ratification state. 682 // A ratification carries no cycle id; it belongs to this cycle only through a 683 // same-cycle receipt for the same candidate. Otherwise it is left out. 684 let ratification = ev.ratification.filter(|r| match receipt { 685 Some(rc) if rc.candidate_id == r.proposal_id => true, 686 _ => { 687 foreign.push(MissingDoc { 688 expected: format!( 689 "an evaluation receipt of cycle {cycle} for proposal {}", 690 r.proposal_id 691 ), 692 reason: 693 "the supplied ratification matches no receipt of this cycle; it was left out" 694 .into(), 695 }); 696 false 697 } 698 }); 699 let rat_id = ratification.map(|r| { 700 let id = ratification_id(r); 701 let mut n = node( 702 id.clone(), 703 KIND_PROMOTION_STATE, 704 STATUS_DIRECT_OBSERVATION, 705 format!( 706 "Ratification record for proposal {}: status {} ({})", 707 r.proposal_id, r.status, r.message 708 ), 709 src("RatificationRecord", &r.proposal_id, r.commit_hash.clone()), 710 ); 711 if let Some(rc) = receipt { 712 n.parents = vec![edge(&receipt_node_id(rc), REL_SUPPORTED_BY)]; 713 } 714 nodes.push(n); 715 id 716 }); 717 718 // Conclusion: the change RSI wants. 719 let ratified = ratification.map(|r| r.status == "Ratified") == Some(true); 720 let statement = match (diagnostic, hypothesis) { 721 (Some(d), _) => format!( 722 "RSI proposes changing {} to address {:?} (cycle {cycle})", 723 d.target_file, d.primary_defect 724 ), 725 (None, Some(h)) => format!("RSI proposes improving {} (cycle {cycle})", h.target_metric), 726 (None, None) => format!("RSI recorded no proposal rationale for cycle {cycle}"), 727 }; 728 let mut c = node( 729 conclusion_id(cycle), 730 KIND_CONCLUSION, 731 if ratified { 732 STATUS_INFERENCE 733 } else { 734 STATUS_HYPOTHESIS 735 }, 736 statement, 737 src("RsiCycle", cycle, None), 738 ); 739 if let Some(d) = &diag_id { 740 c.parents.push(edge(d, REL_SUPPORTED_BY)); 741 } else if let Some((hid, _, _)) = &hyp_ids { 742 c.parents.push(edge(hid, REL_SUPPORTED_BY)); 743 } 744 if let Some((_, pid, fid)) = &hyp_ids { 745 c.parents.push(edge(pid, REL_SUPPORTED_BY)); 746 c.parents.push(edge(fid, REL_SUPPORTED_BY)); 747 } 748 if let Some((r, s)) = &receipt_ids { 749 c.parents.push(edge(r, REL_SUPPORTED_BY)); 750 c.parents.push(edge(s, REL_SUPPORTED_BY)); 751 } 752 if let Some(r) = &rat_id { 753 c.parents.push(edge(r, REL_SUPPORTED_BY)); 754 } 755 match (receipt, hypothesis) { 756 (Some(r), Some(h)) => c.missing.push(MissingDoc { 757 expected: format!( 758 "an artifact linking candidate {} to hypothesis {}", 759 r.candidate_id, h.id 760 ), 761 reason: format!( 762 "both belong to cycle {}, but no RSI artifact records that the candidate was \ 763 generated from this hypothesis, so the evaluation is not shown as testing it", 764 r.cycle_id 765 ), 766 }), 767 (None, _) => c.missing.push(MissingDoc { 768 expected: format!("an evaluation receipt for cycle {cycle}"), 769 reason: "none was supplied; the evaluation is incomplete".into(), 770 }), 771 _ => {} 772 } 773 c.missing.extend(foreign); 774 if hypothesis.is_none() { 775 c.missing.push(MissingDoc { 776 expected: "a hypothesis contract".into(), 777 reason: "none was supplied for this cycle".into(), 778 }); 779 } 780 c.notes.push( 781 "this explanation is observational; it does not authorize promotion or any change".into(), 782 ); 783 nodes.push(c); 784 785 EvidenceGraphDoc { 786 format: FORMAT.into(), 787 version: VERSION, 788 producer: PRODUCER.into(), 789 nodes, 790 truncated_at: Vec::new(), 791 } 792 }