From 15488f078c77403b6822618678061cd9512cfd2e Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 11:57:56 -0500 Subject: [PATCH] explain: emit RSI cycle evidence as aien.explain.evidence-graph v1 Adds src/explain.rs, a read-only producer that turns one RSI cycle (capability metrics, bottleneck ranking, hypothesis contract, diagnostic, evaluation receipt, ratification) into the language-neutral evidence-graph contract consumed by aien-dev/aienos crates/aienos-explain. No compile dependency on aienos. Explicit links only: artifacts from another cycle are left out and declared; the hypothesis-to-ranking match is a weak References link with the missing recorded id declared; the candidate-to-hypothesis gap is declared, never bridged; the receipt node only states digest-covered fields (gate flags and metrics summary sit on a separate unverified node). Declared hypothesis confidence is labelled as such. No change to RSI safety or promotion policy. Tests: tests/test_explain_evidence_graph.rs (5) with a golden fixture pinned by sha256 in both repos. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- src/explain.rs | 735 ++++++++++++++++++++++ src/lib.rs | 1 + tests/fixtures/rsi_kv_cycle.evidence.json | 590 +++++++++++++++++ tests/test_explain_evidence_graph.rs | 356 +++++++++++ 4 files changed, 1682 insertions(+) create mode 100644 src/explain.rs create mode 100644 tests/fixtures/rsi_kv_cycle.evidence.json create mode 100644 tests/test_explain_evidence_graph.rs diff --git a/src/explain.rs b/src/explain.rs new file mode 100644 index 0000000..013a19d --- /dev/null +++ b/src/explain.rs @@ -0,0 +1,735 @@ +//! "Why does RSI want to change this?" as an evidence graph. +//! +//! This module turns the real artifacts of one RSI cycle (capability graph, +//! bottleneck ranking, hypothesis contract, diagnostic context, evaluation receipt, +//! ratification record) into the language-neutral evidence-graph contract +//! `aien.explain.evidence-graph` v1. The aienos `aienos-explain` crate builds the +//! grounded explanation path from that document and renders it; spark-rsi has no +//! compile-time dependency on aienos. +//! +//! Rules kept here: +//! - only explicit fields become links (ids, cycle ids, candidate ids); where RSI has +//! no artifact for a link, the link is declared missing instead of invented; +//! - nothing here changes evaluation, safety, ratification or promotion; the +//! explanation is observational and authorizes nothing; +//! - free-text "lessons" from the outside memory service and model output are not +//! evidence and are never included. + +use crate::evaluator::EvaluationReceipt; +use crate::graph::{BottleneckRank, CapabilityGraph}; +use crate::models::RatificationRecord; +use crate::propose::diagnose::DiagnosticContext; +use crate::propose::hypothesis::HypothesisContract; +use serde::{Deserialize, Serialize}; + +pub const FORMAT: &str = "aien.explain.evidence-graph"; +pub const VERSION: u16 = 1; +pub const PRODUCER: &str = "spark-rsi/explain"; + +// Contract codes (see aienos docs/EXPLAIN_EVIDENCE_GRAPH_V1.md). +pub const STATUS_UNCLASSIFIED: u8 = 0; +pub const STATUS_DIRECT_OBSERVATION: u8 = 1; +pub const STATUS_VERIFIED_FACT: u8 = 2; +pub const STATUS_INFERENCE: u8 = 3; +pub const STATUS_HYPOTHESIS: u8 = 4; + +pub const KIND_CAPABILITY_METRIC: u16 = 2; +pub const KIND_CAPABILITY_ANALYSIS: u16 = 3; +pub const KIND_DIAGNOSTIC: u16 = 4; +pub const KIND_HYPOTHESIS: u16 = 5; +pub const KIND_PREDICTION: u16 = 6; +pub const KIND_FALSIFICATION: u16 = 7; +pub const KIND_EVALUATION_RECEIPT: u16 = 8; +pub const KIND_PROMOTION_STATE: u16 = 9; +pub const KIND_CONCLUSION: u16 = 12; +pub const KIND_ALTERNATIVE: u16 = 13; + +pub const REL_SUPPORTED_BY: u16 = 1; +pub const REL_PART_OF: u16 = 3; +pub const REL_ALTERNATIVE_TO: u16 = 5; +pub const REL_REFERENCES: u16 = 6; + +/// Most alternatives listed from the bottleneck ranking (rank 2 onward). +pub const MAX_ALTERNATIVES: usize = 3; +/// Contract cap on parents per node (`MAX_PARENTS_PER_NODE` in the contract). +pub const MAX_PARENTS: usize = 1024; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceRefDoc { + pub system: String, + pub artifact: String, + pub reference: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub digest: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MeasurementDoc { + pub name: String, + pub value: String, + #[serde(default)] + pub unit: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EdgeDoc { + pub to: String, + pub relation: u16, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MissingDoc { + pub expected: String, + pub reason: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct NodeDoc { + pub id: String, + pub kind: u16, + pub status: u8, + pub statement: String, + pub source: SourceRefDoc, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub confidence_permille: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub confidence_basis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recorded_at_utc: Option, + #[serde(default)] + pub parents: Vec, + #[serde(default)] + pub measurements: Vec, + #[serde(default)] + pub missing: Vec, + #[serde(default)] + pub notes: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EvidenceGraphDoc { + pub format: String, + pub version: u16, + pub producer: String, + pub nodes: Vec, + #[serde(default)] + pub truncated_at: Vec, +} + +impl EvidenceGraphDoc { + /// Canonical JSON bytes (struct field order, node order as built). + pub fn to_json(&self) -> Vec { + serde_json::to_vec(self).expect("evidence graph serializes") + } + + pub fn to_json_pretty(&self) -> String { + serde_json::to_string_pretty(self).expect("evidence graph serializes") + } +} + +/// Whether capability metrics were measured or written in by hand. The daemon's +/// current capability graph uses fixed constants, which are `Declared`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MetricsOrigin { + Measured, + Declared, +} + +/// The artifacts of one RSI cycle, all optional except the cycle id. +pub struct RsiCycleEvidence<'a> { + pub cycle_id: &'a str, + pub graph: Option<&'a CapabilityGraph>, + pub metrics_origin: MetricsOrigin, + /// Bottleneck ranking as returned by `CapabilityGraph::rank_bottlenecks`. + pub bottlenecks: &'a [BottleneckRank], + pub hypothesis: Option<&'a HypothesisContract>, + pub diagnostic: Option<&'a DiagnosticContext>, + pub receipt: Option<&'a EvaluationReceipt>, + pub ratification: Option<&'a RatificationRecord>, +} + +fn src(artifact: &str, reference: &str, digest: Option) -> SourceRefDoc { + SourceRefDoc { + system: "spark-rsi".into(), + artifact: artifact.into(), + reference: reference.into(), + digest, + } +} + +fn m(name: &str, value: String, unit: &str) -> MeasurementDoc { + MeasurementDoc { + name: name.into(), + value, + unit: unit.into(), + } +} + +fn node(id: String, kind: u16, status: u8, statement: String, source: SourceRefDoc) -> NodeDoc { + NodeDoc { + id, + kind, + status, + statement, + source, + confidence_permille: None, + confidence_basis: None, + recorded_at_utc: None, + parents: Vec::new(), + measurements: Vec::new(), + missing: Vec::new(), + notes: Vec::new(), + } +} + +fn edge(to: &str, relation: u16) -> EdgeDoc { + EdgeDoc { + to: to.to_string(), + relation, + } +} + +pub fn capability_node_id(node_id: &str) -> String { + format!("rsi:capability:{node_id}") +} +pub fn analysis_id(cycle_id: &str) -> String { + format!("rsi:bottleneck:{cycle_id}") +} +pub fn hypothesis_node_id(h: &HypothesisContract) -> String { + format!("rsi:hypothesis:{}", h.id) +} +pub fn diagnostic_id(cycle_id: &str) -> String { + format!("rsi:diagnostic:{cycle_id}") +} +pub fn receipt_node_id(r: &EvaluationReceipt) -> String { + format!("rsi:receipt:{}:{}", r.cycle_id, r.candidate_id) +} +pub fn ratification_id(r: &RatificationRecord) -> String { + format!("rsi:ratification:{}", r.proposal_id) +} +/// Id of the node to explain: "why does RSI want to change this?" +pub fn conclusion_id(cycle_id: &str) -> String { + format!("rsi:conclusion:{cycle_id}") +} + +/// True when the hypothesis was built from this bottleneck the way the daemon builds +/// it: the node name appears quoted in the problem or root cause text, and the +/// baseline is the bottleneck's p95 latency. This is a deterministic check on +/// explicit fields, not a guess; when it fails the link is declared missing. +pub fn hypothesis_derived_from(h: &HypothesisContract, b: &BottleneckRank) -> bool { + let quoted = format!("'{}'", b.node_name); + (h.observed_problem.contains("ed) || h.suspected_root_cause.contains("ed)) + && h.baseline_value == b.latency_p95_us +} + +/// Build the evidence graph for one RSI cycle. Deterministic: node order is fixed, +/// capability nodes are sorted by id, numbers use fixed decimal formats. +pub fn evidence_graph(ev: &RsiCycleEvidence<'_>) -> EvidenceGraphDoc { + let mut nodes: Vec = Vec::new(); + let cycle = ev.cycle_id; + // Artifacts from another cycle are never attached; each mismatch is declared. + let mut foreign: Vec = Vec::new(); + let mut same_cycle = |what: &str, id: &str, their_cycle: &str| -> bool { + if their_cycle == cycle { + true + } else { + foreign.push(MissingDoc { + expected: format!("the {what} for cycle {cycle}"), + reason: format!( + "the supplied {what} {id} belongs to cycle {their_cycle}; it was left out" + ), + }); + false + } + }; + let hypothesis = ev + .hypothesis + .filter(|h| same_cycle("hypothesis", &h.id, &h.cycle_id)); + let diagnostic = ev + .diagnostic + .filter(|d| same_cycle("diagnostic", &d.target_file, &d.cycle_id)); + let receipt = ev + .receipt + .filter(|r| same_cycle("evaluation receipt", &r.candidate_id, &r.cycle_id)); + let metric_status = match ev.metrics_origin { + MetricsOrigin::Measured => STATUS_DIRECT_OBSERVATION, + MetricsOrigin::Declared => STATUS_UNCLASSIFIED, + }; + + // Observed: capability metrics. + let mut metric_ids: Vec = Vec::new(); + if let Some(g) = ev.graph { + let mut caps: Vec<_> = g.nodes.values().collect(); + caps.sort_by(|a, b| a.id.cmp(&b.id)); + for c in caps { + let id = capability_node_id(&c.id); + let mut n = node( + id.clone(), + KIND_CAPABILITY_METRIC, + metric_status, + format!( + "'{}' ({}) has p95 latency {:.1} us, error rate {:.2}%, resident memory {} KiB", + c.name, + c.subsystem, + c.latency_p95_us, + c.error_rate * 100.0, + c.memory_rss_kb + ), + src("CapabilityNode", &c.id, None), + ); + n.measurements = vec![ + m("latency_p95_us", format!("{:.3}", c.latency_p95_us), "us"), + m("error_rate", format!("{:.6}", c.error_rate), "fraction"), + m("memory_rss_kb", c.memory_rss_kb.to_string(), "KiB"), + ]; + if ev.metrics_origin == MetricsOrigin::Declared { + n.notes.push(format!( + "metric values for '{}' were declared in the capability graph, not measured", + c.name + )); + } + metric_ids.push(id); + nodes.push(n); + } + } + + // System analysis: bottleneck ranking. + let top = ev.bottlenecks.first(); + let analysis = top.map(|b| { + let id = analysis_id(cycle); + let mut n = node( + id.clone(), + KIND_CAPABILITY_ANALYSIS, + STATUS_INFERENCE, + format!( + "The capability graph ranks '{}' ({}) as bottleneck #{} of {} ({})", + b.node_name, + b.subsystem, + b.rank, + ev.bottlenecks.len(), + b.causal_explanation + ), + src("BottleneckRank", &b.node_id, None), + ); + n.measurements = vec![ + m("bottleneck_score", format!("{:.4}", b.bottleneck_score), ""), + m("centrality", format!("{:.4}", b.centrality), ""), + m("latency_p95_us", format!("{:.3}", b.latency_p95_us), "us"), + m("error_rate", format!("{:.6}", b.error_rate), "fraction"), + ]; + if metric_ids.is_empty() { + n.missing.push(MissingDoc { + expected: "capability metrics the ranking was computed from".into(), + reason: "no capability graph was supplied with this cycle".into(), + }); + } else { + n.parents = metric_ids + .iter() + .take(MAX_PARENTS) + .map(|i| edge(i, REL_SUPPORTED_BY)) + .collect(); + if metric_ids.len() > MAX_PARENTS { + n.notes.push(format!( + "only the first {MAX_PARENTS} of {} capability metrics are linked (contract cap)", + metric_ids.len() + )); + } + } + n.notes + .push("ranking computed by CapabilityGraph::rank_bottlenecks".into()); + nodes.push(n); + id + }); + + // Alternatives explicitly present in the ranking. + if let Some(aid) = &analysis { + for b in ev.bottlenecks.iter().skip(1).take(MAX_ALTERNATIVES) { + let mut n = node( + format!("rsi:alternative:{cycle}:{}", b.node_id), + KIND_ALTERNATIVE, + STATUS_INFERENCE, + format!( + "Alternative bottleneck candidate #{}: '{}' ({}), score {:.4}", + b.rank, b.node_name, b.subsystem, b.bottleneck_score + ), + src("BottleneckRank", &b.node_id, None), + ); + n.parents = vec![edge(aid, REL_ALTERNATIVE_TO)]; + n.measurements = vec![m( + "bottleneck_score", + format!("{:.4}", b.bottleneck_score), + "", + )]; + nodes.push(n); + } + } + + // Hypothesis, prediction, falsification. + let mut hyp_ids: Option<(String, String, String)> = None; + if let Some(h) = hypothesis { + let hid = hypothesis_node_id(h); + let mut n = node( + hid.clone(), + KIND_HYPOTHESIS, + STATUS_HYPOTHESIS, + format!( + "Suspected root cause: {}. Observed problem: {}", + h.suspected_root_cause, h.observed_problem + ), + src("HypothesisContract", &h.id, None), + ); + if h.confidence_score.is_finite() { + n.confidence_permille = + Some((h.confidence_score.clamp(0.0, 1.0) * 1000.0).round() as u16); + n.confidence_basis = Some("declared in the HypothesisContract, not measured".into()); + } + match (top, &analysis) { + (Some(b), Some(aid)) if hypothesis_derived_from(h, b) => { + // A text and value match, not a recorded id: kept as a weak + // "references" link and the missing id is declared. + n.parents = vec![edge(aid, REL_REFERENCES)]; + n.missing.push(MissingDoc { + expected: "a recorded reference from the hypothesis to the bottleneck ranking" + .into(), + reason: format!( + "linked only because the hypothesis text names '{}' and its baseline \ + equals that bottleneck's p95 latency", + b.node_name + ), + }); + } + _ => n.missing.push(MissingDoc { + expected: "the system analysis this hypothesis was derived from".into(), + reason: "the HypothesisContract carries no bottleneck reference and does not \ + match the top-ranked bottleneck" + .into(), + }), + } + if let Err(e) = h.validate() { + n.notes + .push(format!("hypothesis contract fails validation: {e}")); + } + nodes.push(n); + + let pid = format!("{hid}:prediction"); + let mut p = node( + pid.clone(), + KIND_PREDICTION, + STATUS_HYPOTHESIS, + format!( + "Predicts {} improves by {:.1}% from baseline {:.3}", + h.target_metric, h.predicted_delta_pct, h.baseline_value + ), + src("HypothesisContract", &h.id, None), + ); + p.parents = vec![edge(&hid, REL_PART_OF)]; + p.measurements = vec![ + m("target_metric", h.target_metric.clone(), ""), + m("baseline_value", format!("{:.3}", h.baseline_value), ""), + m( + "predicted_delta_pct", + format!("{:.3}", h.predicted_delta_pct), + "%", + ), + ]; + nodes.push(p); + + let fid = format!("{hid}:falsification"); + let protected: Vec = h + .protected_metrics + .iter() + .map(|pm| { + format!( + "{} may degrade at most {:.1}%", + pm.name, pm.max_allowed_degradation_pct + ) + }) + .collect(); + let mut f = node( + fid.clone(), + KIND_FALSIFICATION, + STATUS_HYPOTHESIS, + if h.falsification_test.is_empty() { + format!("Protected metrics: {}", protected.join("; ")) + } else { + format!( + "Refuted if this check fails: {}. Protected metrics: {}", + h.falsification_test, + protected.join("; ") + ) + }, + src("HypothesisContract", &h.id, None), + ); + f.parents = vec![edge(&hid, REL_PART_OF)]; + f.measurements = h + .protected_metrics + .iter() + .map(|pm| { + m( + &format!("protected.{}.max_degradation_pct", pm.name), + format!("{:.3}", pm.max_allowed_degradation_pct), + "%", + ) + }) + .collect(); + if h.falsification_test.is_empty() { + f.missing.push(MissingDoc { + expected: "a falsification test".into(), + reason: "the HypothesisContract has an empty falsification_test".into(), + }); + } + nodes.push(f); + hyp_ids = Some((hid, pid, fid)); + } + + // Diagnostic context (explicitly carries the hypothesis it was built with). + let diag_id = diagnostic.map(|d| { + let id = diagnostic_id(cycle); + let mut n = node( + id.clone(), + KIND_DIAGNOSTIC, + STATUS_INFERENCE, + format!( + "Diagnosis for {}: primary defect {:?}; {}", + d.target_file, + d.primary_defect, + if d.violations.is_empty() { + "no violations listed".to_string() + } else { + d.violations.join("; ") + } + ), + src("DiagnosticContext", &d.cycle_id, None), + ); + match (&d.hypothesis, &hyp_ids) { + (Some(dh), Some((hid, _, _))) if hypothesis.map(|h| h.id == dh.id) == Some(true) => { + n.parents = vec![edge(hid, REL_SUPPORTED_BY)]; + } + (Some(dh), _) => n.missing.push(MissingDoc { + expected: format!("hypothesis {}", dh.id), + reason: "the diagnostic names a hypothesis that was not supplied".into(), + }), + (None, _) => n.missing.push(MissingDoc { + expected: "the hypothesis behind this diagnosis".into(), + reason: "the DiagnosticContext carries no hypothesis".into(), + }), + } + if !d.past_lessons.is_empty() { + n.notes.push(format!( + "{} recalled lesson(s) from the outside memory service were left out: they are \ + free text, not evidence", + d.past_lessons.len() + )); + } + nodes.push(n); + id + }); + + // Evaluation receipt. The receipt digest covers cycle, candidate, parent, the + // admitted flag and the layer results only, so only those are stated on the + // receipt node (verified when the digest matches). The gate flags and the metrics + // summary are not covered by the digest; they go on a separate node whose status + // stays unknown. + let receipt_ids = receipt.map(|r| { + let id = receipt_node_id(r); + let digest_ok = r.verify_digest(); + let mut n = node( + id.clone(), + KIND_EVALUATION_RECEIPT, + if digest_ok { + STATUS_VERIFIED_FACT + } else { + STATUS_UNCLASSIFIED + }, + format!( + "Evaluation of candidate {} (parent {}): admitted={}, {} evaluation layer \ + result(s)", + r.candidate_id, + r.parent_id, + r.admitted, + r.layer_results.len() + ), + src( + "EvaluationReceipt", + &r.candidate_id, + Some(r.receipt_digest.clone()), + ), + ); + for l in &r.layer_results { + n.measurements.push(m( + &format!("layer.{}.passed", l.layer_name), + l.passed.to_string(), + "", + )); + n.measurements.push(m( + &format!("layer.{}.score", l.layer_name), + format!("{:.4}", l.score), + "", + )); + } + if !digest_ok { + n.notes + .push("the receipt digest does not match its contents".into()); + } + n.notes.push(if r.signature.is_some() { + "receipt is signed; the signature was not checked here (needs the evaluator public key)" + .into() + } else { + "receipt is unsigned".into() + }); + nodes.push(n); + + let sid = format!("{id}:summary"); + let mut s = node( + sid.clone(), + KIND_EVALUATION_RECEIPT, + STATUS_UNCLASSIFIED, + format!( + "The evaluator reports: hard invariants passed={}, statistical gates passed={}", + r.passed_all_hard_invariants, r.passed_statistical_gates + ), + src("EvaluationReceipt", &r.candidate_id, None), + ); + s.parents = vec![edge(&id, REL_PART_OF)]; + if let Some(ms) = &r.metrics_summary { + s.measurements.extend([ + m( + "latency_delta_pct", + format!("{:.3}", ms.latency_delta_pct), + "%", + ), + m("p_value", format!("{:.6}", ms.p_value), ""), + m( + "p95_ci_upper_degradation_pct", + format!("{:.3}", ms.p95_ci_upper_degradation_pct), + "%", + ), + m( + "p99_ci_upper_degradation_pct", + format!("{:.3}", ms.p99_ci_upper_degradation_pct), + "%", + ), + m("rss_growth_pct", format!("{:.3}", ms.rss_growth_pct), "%"), + ]); + } + s.notes.push( + "these fields are not covered by the receipt digest, so they are reported, not \ + verified" + .into(), + ); + nodes.push(s); + (id, sid) + }); + + // Promotion / ratification state. + // A ratification carries no cycle id; it belongs to this cycle only through a + // same-cycle receipt for the same candidate. Otherwise it is left out. + let ratification = ev.ratification.filter(|r| match receipt { + Some(rc) if rc.candidate_id == r.proposal_id => true, + _ => { + foreign.push(MissingDoc { + expected: format!( + "an evaluation receipt of cycle {cycle} for proposal {}", + r.proposal_id + ), + reason: + "the supplied ratification matches no receipt of this cycle; it was left out" + .into(), + }); + false + } + }); + let rat_id = ratification.map(|r| { + let id = ratification_id(r); + let mut n = node( + id.clone(), + KIND_PROMOTION_STATE, + STATUS_DIRECT_OBSERVATION, + format!( + "Ratification record for proposal {}: status {} ({})", + r.proposal_id, r.status, r.message + ), + src("RatificationRecord", &r.proposal_id, r.commit_hash.clone()), + ); + if let Some(rc) = receipt { + n.parents = vec![edge(&receipt_node_id(rc), REL_SUPPORTED_BY)]; + } + nodes.push(n); + id + }); + + // Conclusion: the change RSI wants. + let ratified = ratification.map(|r| r.status == "Ratified") == Some(true); + let statement = match (diagnostic, hypothesis) { + (Some(d), _) => format!( + "RSI proposes changing {} to address {:?} (cycle {cycle})", + d.target_file, d.primary_defect + ), + (None, Some(h)) => format!("RSI proposes improving {} (cycle {cycle})", h.target_metric), + (None, None) => format!("RSI recorded no proposal rationale for cycle {cycle}"), + }; + let mut c = node( + conclusion_id(cycle), + KIND_CONCLUSION, + if ratified { + STATUS_INFERENCE + } else { + STATUS_HYPOTHESIS + }, + statement, + src("RsiCycle", cycle, None), + ); + if let Some(d) = &diag_id { + c.parents.push(edge(d, REL_SUPPORTED_BY)); + } else if let Some((hid, _, _)) = &hyp_ids { + c.parents.push(edge(hid, REL_SUPPORTED_BY)); + } + if let Some((_, pid, fid)) = &hyp_ids { + c.parents.push(edge(pid, REL_SUPPORTED_BY)); + c.parents.push(edge(fid, REL_SUPPORTED_BY)); + } + if let Some((r, s)) = &receipt_ids { + c.parents.push(edge(r, REL_SUPPORTED_BY)); + c.parents.push(edge(s, REL_SUPPORTED_BY)); + } + if let Some(r) = &rat_id { + c.parents.push(edge(r, REL_SUPPORTED_BY)); + } + match (receipt, hypothesis) { + (Some(r), Some(h)) => c.missing.push(MissingDoc { + expected: format!( + "an artifact linking candidate {} to hypothesis {}", + r.candidate_id, h.id + ), + reason: format!( + "both belong to cycle {}, but no RSI artifact records that the candidate was \ + generated from this hypothesis, so the evaluation is not shown as testing it", + r.cycle_id + ), + }), + (None, _) => c.missing.push(MissingDoc { + expected: format!("an evaluation receipt for cycle {cycle}"), + reason: "none was supplied; the evaluation is incomplete".into(), + }), + _ => {} + } + c.missing.extend(foreign); + if hypothesis.is_none() { + c.missing.push(MissingDoc { + expected: "a hypothesis contract".into(), + reason: "none was supplied for this cycle".into(), + }); + } + c.notes.push( + "this explanation is observational; it does not authorize promotion or any change".into(), + ); + nodes.push(c); + + EvidenceGraphDoc { + format: FORMAT.into(), + version: VERSION, + producer: PRODUCER.into(), + nodes, + truncated_at: Vec::new(), + } +} diff --git a/src/lib.rs b/src/lib.rs index 5b76fdd..6ef76b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ pub mod canary_observation; pub mod config; pub mod daemon; pub mod evaluator; +pub mod explain; pub mod graph; pub mod isolation; pub mod ledger; diff --git a/tests/fixtures/rsi_kv_cycle.evidence.json b/tests/fixtures/rsi_kv_cycle.evidence.json new file mode 100644 index 0000000..842cd55 --- /dev/null +++ b/tests/fixtures/rsi_kv_cycle.evidence.json @@ -0,0 +1,590 @@ +{ + "format": "aien.explain.evidence-graph", + "version": 1, + "producer": "spark-rsi/explain", + "nodes": [ + { + "id": "rsi:capability:kv_allocator", + "kind": 2, + "status": 0, + "statement": "'Unified LPDDR5x KV Allocator' (memory) has p95 latency 4200.0 us, error rate 8.00%, resident memory 32768 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "kv_allocator" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "4200.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.080000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "32768", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Unified LPDDR5x KV Allocator' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:mojo_kernel", + "kind": 2, + "status": 0, + "statement": "'Mojo Blackwell GEMM Kernel' (compute) has p95 latency 1800.0 us, error rate 1.00%, resident memory 16384 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "mojo_kernel" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "1800.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.010000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "16384", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Mojo Blackwell GEMM Kernel' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:req_gateway", + "kind": 2, + "status": 0, + "statement": "'Request Gateway' (network) has p95 latency 120.0 us, error rate 0.00%, resident memory 1024 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "req_gateway" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "120.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "1024", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Request Gateway' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:sampler", + "kind": 2, + "status": 0, + "statement": "'Greedy Token Sampler' (inference) has p95 latency 150.0 us, error rate 0.00%, resident memory 1024 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "sampler" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "150.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "1024", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Greedy Token Sampler' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:scheduler", + "kind": 2, + "status": 0, + "statement": "'Batch Scheduler' (scheduling) has p95 latency 340.0 us, error rate 0.00%, resident memory 2048 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "scheduler" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "340.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "2048", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Batch Scheduler' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:bottleneck:cycle-kv-0001", + "kind": 3, + "status": 3, + "statement": "The capability graph ranks 'Unified LPDDR5x KV Allocator' (memory) as bottleneck #1 of 5 (Centrality=0.333, LatencyRatio=3.18x, ErrorRate=8.0%)", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "kv_allocator" + }, + "parents": [ + { + "to": "rsi:capability:kv_allocator", + "relation": 1 + }, + { + "to": "rsi:capability:mojo_kernel", + "relation": 1 + }, + { + "to": "rsi:capability:req_gateway", + "relation": 1 + }, + { + "to": "rsi:capability:sampler", + "relation": 1 + }, + { + "to": "rsi:capability:scheduler", + "relation": 1 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "1.4841", + "unit": "" + }, + { + "name": "centrality", + "value": "0.3333", + "unit": "" + }, + { + "name": "latency_p95_us", + "value": "4200.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.080000", + "unit": "fraction" + } + ], + "missing": [], + "notes": [ + "ranking computed by CapabilityGraph::rank_bottlenecks" + ] + }, + { + "id": "rsi:alternative:cycle-kv-0001:mojo_kernel", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #2: 'Mojo Blackwell GEMM Kernel' (compute), score 0.6546", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "mojo_kernel" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.6546", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:alternative:cycle-kv-0001:scheduler", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #3: 'Batch Scheduler' (scheduling), score 0.2029", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "scheduler" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.2029", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:alternative:cycle-kv-0001:sampler", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #4: 'Greedy Token Sampler' (inference), score 0.0454", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "sampler" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.0454", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001", + "kind": 5, + "status": 4, + "statement": "Suspected root cause: High latency on 'Unified LPDDR5x KV Allocator': Centrality=0.333, LatencyRatio=3.18x, ErrorRate=8.0%. Observed problem: System throughput limited by bottleneck node 'Unified LPDDR5x KV Allocator' (centrality=0.3333)", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "confidence_permille": 850, + "confidence_basis": "declared in the HypothesisContract, not measured", + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 6 + } + ], + "measurements": [], + "missing": [ + { + "expected": "a recorded reference from the hypothesis to the bottleneck ranking", + "reason": "linked only because the hypothesis text names 'Unified LPDDR5x KV Allocator' and its baseline equals that bottleneck's p95 latency" + } + ], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001:prediction", + "kind": 6, + "status": 4, + "statement": "Predicts latency_us improves by 15.0% from baseline 4200.000", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "target_metric", + "value": "latency_us", + "unit": "" + }, + { + "name": "baseline_value", + "value": "4200.000", + "unit": "" + }, + { + "name": "predicted_delta_pct", + "value": "15.000", + "unit": "%" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001:falsification", + "kind": 7, + "status": 4, + "statement": "Refuted if this check fails: assert!(receipt.passed_all_hard_invariants). Protected metrics: p95_latency may degrade at most 1.0%; p99_latency may degrade at most 1.0%; max_rss_kb may degrade at most 2.0%; correctness may degrade at most 0.0%", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "protected.p95_latency.max_degradation_pct", + "value": "1.000", + "unit": "%" + }, + { + "name": "protected.p99_latency.max_degradation_pct", + "value": "1.000", + "unit": "%" + }, + { + "name": "protected.max_rss_kb.max_degradation_pct", + "value": "2.000", + "unit": "%" + }, + { + "name": "protected.correctness.max_degradation_pct", + "value": "0.000", + "unit": "%" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:diagnostic:cycle-kv-0001", + "kind": 4, + "status": 3, + "statement": "Diagnosis for src/kv_allocator.rs: primary defect PerformanceRegression; Bottleneck identified at Unified LPDDR5x KV Allocator", + "source": { + "system": "spark-rsi", + "artifact": "DiagnosticContext", + "reference": "cycle-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [], + "notes": [ + "1 recalled lesson(s) from the outside memory service were left out: they are free text, not evidence" + ] + }, + { + "id": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "kind": 8, + "status": 2, + "statement": "Evaluation of candidate cand-kv-0001 (parent parent): admitted=true, 2 evaluation layer result(s)", + "source": { + "system": "spark-rsi", + "artifact": "EvaluationReceipt", + "reference": "cand-kv-0001", + "digest": "c0cae9f3e257ef2f7b46f5cd3770f9fe1c21f8b6dfb2ee2e2449714b0c7e99d0" + }, + "parents": [], + "measurements": [ + { + "name": "layer.Correctness.passed", + "value": "true", + "unit": "" + }, + { + "name": "layer.Correctness.score", + "value": "1.0000", + "unit": "" + }, + { + "name": "layer.Performance.passed", + "value": "true", + "unit": "" + }, + { + "name": "layer.Performance.score", + "value": "0.8200", + "unit": "" + } + ], + "missing": [], + "notes": [ + "receipt is unsigned" + ] + }, + { + "id": "rsi:receipt:cycle-kv-0001:cand-kv-0001:summary", + "kind": 8, + "status": 0, + "statement": "The evaluator reports: hard invariants passed=true, statistical gates passed=true", + "source": { + "system": "spark-rsi", + "artifact": "EvaluationReceipt", + "reference": "cand-kv-0001" + }, + "parents": [ + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "latency_delta_pct", + "value": "-17.500", + "unit": "%" + }, + { + "name": "p_value", + "value": "0.004000", + "unit": "" + }, + { + "name": "p95_ci_upper_degradation_pct", + "value": "-9.000", + "unit": "%" + }, + { + "name": "p99_ci_upper_degradation_pct", + "value": "-4.000", + "unit": "%" + }, + { + "name": "rss_growth_pct", + "value": "0.500", + "unit": "%" + } + ], + "missing": [], + "notes": [ + "these fields are not covered by the receipt digest, so they are reported, not verified" + ] + }, + { + "id": "rsi:ratification:cand-kv-0001", + "kind": 9, + "status": 1, + "statement": "Ratification record for proposal cand-kv-0001: status Ratified (test record)", + "source": { + "system": "spark-rsi", + "artifact": "RatificationRecord", + "reference": "cand-kv-0001" + }, + "parents": [ + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [], + "notes": [] + }, + { + "id": "rsi:conclusion:cycle-kv-0001", + "kind": 12, + "status": 3, + "statement": "RSI proposes changing src/kv_allocator.rs to address PerformanceRegression (cycle cycle-kv-0001)", + "source": { + "system": "spark-rsi", + "artifact": "RsiCycle", + "reference": "cycle-kv-0001" + }, + "parents": [ + { + "to": "rsi:diagnostic:cycle-kv-0001", + "relation": 1 + }, + { + "to": "rsi:hypothesis:hypo-kv-0001:prediction", + "relation": 1 + }, + { + "to": "rsi:hypothesis:hypo-kv-0001:falsification", + "relation": 1 + }, + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 1 + }, + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001:summary", + "relation": 1 + }, + { + "to": "rsi:ratification:cand-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [ + { + "expected": "an artifact linking candidate cand-kv-0001 to hypothesis hypo-kv-0001", + "reason": "both belong to cycle cycle-kv-0001, but no RSI artifact records that the candidate was generated from this hypothesis, so the evaluation is not shown as testing it" + } + ], + "notes": [ + "this explanation is observational; it does not authorize promotion or any change" + ] + } + ], + "truncated_at": [] +} diff --git a/tests/test_explain_evidence_graph.rs b/tests/test_explain_evidence_graph.rs new file mode 100644 index 0000000..d7a6148 --- /dev/null +++ b/tests/test_explain_evidence_graph.rs @@ -0,0 +1,356 @@ +//! RSI -> explanation evidence graph (contract aien.explain.evidence-graph v1). +//! +//! Builds one RSI cycle from the real types (capability graph, bottleneck ranking, +//! hypothesis contract built the way the daemon builds it, diagnostic context, +//! evaluation receipt, ratification record) and checks the emitted document. The +//! golden file tests/fixtures/rsi_kv_cycle.evidence.json is shared byte for byte with +//! aien-dev/aienos crates/aienos-explain, which builds and renders the explanation. +//! Regenerate with EXPLAIN_BLESS=1 and copy it to aienos. + +use sha2::{Digest, Sha256}; +use spark_rsi::evaluator::{EvaluationMetricsSummary, EvaluationReceipt, LayerResult}; +use spark_rsi::explain::{ + conclusion_id, evidence_graph, hypothesis_derived_from, EvidenceGraphDoc, MetricsOrigin, + RsiCycleEvidence, FORMAT, KIND_HYPOTHESIS, REL_REFERENCES, STATUS_HYPOTHESIS, + STATUS_UNCLASSIFIED, STATUS_VERIFIED_FACT, VERSION, +}; +use spark_rsi::graph::{CapabilityGraph, CapabilityNode}; +use spark_rsi::models::RatificationRecord; +use spark_rsi::propose::diagnose::{DefectCategory, DiagnosticContext}; +use spark_rsi::propose::hypothesis::HypothesisContract; + +const CYCLE: &str = "cycle-kv-0001"; +const FIXTURE: &str = "tests/fixtures/rsi_kv_cycle.evidence.json"; +/// sha256 of the fixture; the aienos side asserts the same value. +const FIXTURE_SHA256: &str = "0c04376ca36d95d677942d7e97c0a3eef3728ef72dc3cdf070494174e6a6cc31"; + +fn kv_graph() -> CapabilityGraph { + let mut g = CapabilityGraph::new(); + g.add_node( + CapabilityNode::new("req_gateway", "Request Gateway", "network") + .with_resource_metrics(120.0, 1024, 0.0), + ); + g.add_node( + CapabilityNode::new("scheduler", "Batch Scheduler", "scheduling") + .with_resource_metrics(340.0, 2048, 0.0), + ); + g.add_node( + CapabilityNode::new("kv_allocator", "Unified LPDDR5x KV Allocator", "memory") + .with_resource_metrics(4200.0, 32768, 0.08), + ); + g.add_node( + CapabilityNode::new("mojo_kernel", "Mojo Blackwell GEMM Kernel", "compute") + .with_resource_metrics(1800.0, 16384, 0.01), + ); + g.add_node( + CapabilityNode::new("sampler", "Greedy Token Sampler", "inference") + .with_resource_metrics(150.0, 1024, 0.0), + ); + g.add_edge("req_gateway", "scheduler", 100.0, 1.0); + g.add_edge("scheduler", "kv_allocator", 500.0, 1.0); + g.add_edge("kv_allocator", "mojo_kernel", 1200.0, 1.0); + g.add_edge("mojo_kernel", "sampler", 200.0, 1.0); + g +} + +/// Same construction as RsiEngine::run_cycle in src/daemon.rs (step 5). +fn daemon_style_hypothesis(b: &spark_rsi::graph::BottleneckRank) -> HypothesisContract { + HypothesisContract::new( + "hypo-kv-0001", + CYCLE, + &format!( + "System throughput limited by bottleneck node '{}' (centrality={:.4})", + b.node_name, b.centrality + ), + &format!( + "High latency on '{}': {}", + b.node_name, b.causal_explanation + ), + "latency_us", + b.latency_p95_us, + 15.0, + ) + .with_protected_metric("correctness", 0.0) + .with_falsification_test("assert!(receipt.passed_all_hard_invariants)") +} + +fn receipt() -> EvaluationReceipt { + let layers = vec![ + LayerResult { + layer_name: "Correctness".into(), + is_hard_invariant: true, + passed: true, + score: 1.0, + summary: "all holdouts pass".into(), + violations: vec![], + }, + LayerResult { + layer_name: "Performance".into(), + is_hard_invariant: false, + passed: true, + score: 0.82, + summary: "p95 improved".into(), + violations: vec![], + }, + ]; + let digest = EvaluationReceipt::compute_digest(CYCLE, "cand-kv-0001", "parent", true, &layers); + EvaluationReceipt { + cycle_id: CYCLE.into(), + candidate_id: "cand-kv-0001".into(), + parent_id: "parent".into(), + evaluated_at: "2026-10-01T00:00:00Z".into(), + evaluator_version: "test".into(), + passed_all_hard_invariants: true, + passed_statistical_gates: true, + admitted: true, + layer_results: layers, + metrics_summary: Some(EvaluationMetricsSummary { + latency_delta_pct: -17.5, + p_value: 0.004, + p95_ci_upper_degradation_pct: -9.0, + p99_ci_upper_degradation_pct: -4.0, + rss_growth_pct: 0.5, + candidate_resident_mb: 512, + }), + receipt_digest: digest, + signature: None, + } +} + +fn ratification() -> RatificationRecord { + RatificationRecord { + proposal_id: "cand-kv-0001".into(), + commit_hash: None, + author: "test".into(), + cortex_receipt_id: None, + cortex_recorded: false, + timestamp: "2026-10-01T00:00:01Z".into(), + status: "Ratified".into(), + message: "test record".into(), + } +} + +fn kv_cycle_doc() -> EvidenceGraphDoc { + let g = kv_graph(); + let ranks = g.rank_bottlenecks(); + let h = daemon_style_hypothesis(&ranks[0]); + let diag = DiagnosticContext::from_violations( + CYCLE, + "src/kv_allocator.rs", + "SOURCE TEXT MUST NOT APPEAR IN EVIDENCE", + DefectCategory::PerformanceRegression, + vec![format!("Bottleneck identified at {}", ranks[0].node_name)], + vec!["LESSON TEXT MUST NOT APPEAR IN EVIDENCE".into()], + ) + .with_hypothesis(h.clone()); + let r = receipt(); + let rat = ratification(); + evidence_graph(&RsiCycleEvidence { + cycle_id: CYCLE, + graph: Some(&g), + metrics_origin: MetricsOrigin::Declared, + bottlenecks: &ranks, + hypothesis: Some(&h), + diagnostic: Some(&diag), + receipt: Some(&r), + ratification: Some(&rat), + }) +} + +fn find<'a>(d: &'a EvidenceGraphDoc, id: &str) -> &'a spark_rsi::explain::NodeDoc { + d.nodes + .iter() + .find(|n| n.id == id) + .unwrap_or_else(|| panic!("node {id}")) +} + +#[test] +fn rsi_cycle_emits_contract_v1_with_explicit_links_only() { + let d = kv_cycle_doc(); + assert_eq!(d.format, FORMAT); + assert_eq!(d.version, VERSION); + + // Observed: five capability nodes, declared (not measured) metrics. + let caps: Vec<_> = d + .nodes + .iter() + .filter(|n| n.id.starts_with("rsi:capability:")) + .collect(); + assert_eq!(caps.len(), 5); + assert!(caps.iter().all(|n| n.status == STATUS_UNCLASSIFIED)); + assert!(caps + .iter() + .all(|n| n.notes.iter().any(|t| t.contains("not measured")))); + + // System analysis rests on the metrics; alternatives are AlternativeTo, not support. + let a = find(&d, &format!("rsi:bottleneck:{CYCLE}")); + assert_eq!(a.parents.len(), 5); + assert!(a.statement.contains("Unified LPDDR5x KV Allocator")); + let alts: Vec<_> = d + .nodes + .iter() + .filter(|n| n.id.starts_with("rsi:alternative:")) + .collect(); + assert_eq!(alts.len(), 3); + assert!(alts + .iter() + .all(|n| n.parents.len() == 1 && n.parents[0].relation == 5)); + + // Hypothesis keeps its status and declared confidence, and links to the analysis. + let h = find(&d, "rsi:hypothesis:hypo-kv-0001"); + assert_eq!(h.kind, KIND_HYPOTHESIS); + assert_eq!(h.status, STATUS_HYPOTHESIS); + assert_eq!(h.confidence_permille, Some(850)); + assert!(h + .confidence_basis + .as_deref() + .unwrap() + .contains("not measured")); + // Matched by text and baseline only: a weak "references" link plus a declared gap. + assert_eq!(h.parents.len(), 1); + assert_eq!(h.parents[0].relation, REL_REFERENCES); + assert_eq!(h.missing.len(), 1); + assert!(h.missing[0].reason.contains("linked only because")); + + // Receipt digest verifies -> VerifiedFact; no fabricated Evaluates edge anywhere. + let r = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001")); + assert_eq!(r.status, STATUS_VERIFIED_FACT); + assert!(r.source.digest.is_some()); + assert!(!r.statement.contains("hard invariants")); + // Fields outside the receipt digest are reported, not verified. + let s = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001:summary")); + assert_eq!(s.status, STATUS_UNCLASSIFIED); + assert!(s.statement.contains("hard invariants passed=true")); + assert!(s + .notes + .iter() + .any(|t| t.contains("not covered by the receipt digest"))); + assert!(d + .nodes + .iter() + .all(|n| n.parents.iter().all(|e| e.relation != 2))); + + // The candidate-to-hypothesis gap is declared, not bridged. + let c = find(&d, &conclusion_id(CYCLE)); + assert!(c + .missing + .iter() + .any(|m| m.expected.contains("linking candidate cand-kv-0001"))); + assert!(c.notes.iter().any(|t| t.contains("does not authorize"))); + + // Source code and outside free-text lessons never enter the evidence. + let json = String::from_utf8(d.to_json()).unwrap(); + assert!(!json.contains("SOURCE TEXT MUST NOT APPEAR")); + assert!(!json.contains("LESSON TEXT MUST NOT APPEAR")); +} + +#[test] +fn hypothesis_not_from_bottleneck_is_declared_missing() { + let g = kv_graph(); + let ranks = g.rank_bottlenecks(); + let unrelated = HypothesisContract::new( + "hypo-other", + CYCLE, + "Problem elsewhere", + "Some other cause", + "p95", + 1.0, + 5.0, + ); + assert!(!hypothesis_derived_from(&unrelated, &ranks[0])); + let d = evidence_graph(&RsiCycleEvidence { + cycle_id: CYCLE, + graph: Some(&g), + metrics_origin: MetricsOrigin::Measured, + bottlenecks: &ranks, + hypothesis: Some(&unrelated), + diagnostic: None, + receipt: None, + ratification: None, + }); + let h = find(&d, "rsi:hypothesis:hypo-other"); + assert!(h.parents.is_empty()); + assert_eq!(h.missing.len(), 1); + let c = find(&d, &conclusion_id(CYCLE)); + assert!(c + .missing + .iter() + .any(|m| m.expected.contains("evaluation receipt"))); + // Measured metrics are observations. + assert!(d + .nodes + .iter() + .filter(|n| n.id.starts_with("rsi:capability:")) + .all(|n| n.status == 1)); +} + +#[test] +fn tampered_receipt_is_not_a_verified_fact() { + let g = kv_graph(); + let ranks = g.rank_bottlenecks(); + let mut r = receipt(); + r.admitted = false; // digest no longer matches + let d = evidence_graph(&RsiCycleEvidence { + cycle_id: CYCLE, + graph: Some(&g), + metrics_origin: MetricsOrigin::Declared, + bottlenecks: &ranks, + hypothesis: None, + diagnostic: None, + receipt: Some(&r), + ratification: None, + }); + let n = find(&d, &format!("rsi:receipt:{CYCLE}:cand-kv-0001")); + assert_eq!(n.status, STATUS_UNCLASSIFIED); + assert!(n.notes.iter().any(|t| t.contains("does not match"))); +} + +#[test] +fn rsi_evidence_graph_is_deterministic_and_matches_shared_fixture() { + let a = kv_cycle_doc().to_json_pretty(); + let b = kv_cycle_doc().to_json_pretty(); + assert_eq!(a, b, "same artifacts must give the same document"); + let bytes = format!("{a}\n"); + if std::env::var("EXPLAIN_BLESS").as_deref() == Ok("1") { + std::fs::write(FIXTURE, &bytes).unwrap(); + } + let on_disk = std::fs::read_to_string(FIXTURE).expect("fixture present"); + assert_eq!( + on_disk, bytes, + "fixture drifted; rerun with EXPLAIN_BLESS=1 and copy to aienos" + ); + let digest = hex::encode(Sha256::digest(on_disk.as_bytes())); + assert_eq!(digest, FIXTURE_SHA256, "update the pin here and in aienos"); +} + +#[test] +fn artifacts_from_another_cycle_are_not_attached() { + let g = kv_graph(); + let ranks = g.rank_bottlenecks(); + let mut r = receipt(); + r.cycle_id = "cycle-other".into(); + r.receipt_digest = EvaluationReceipt::compute_digest( + &r.cycle_id, + &r.candidate_id, + &r.parent_id, + r.admitted, + &r.layer_results, + ); + let h = daemon_style_hypothesis(&ranks[0]); + let d = evidence_graph(&RsiCycleEvidence { + cycle_id: CYCLE, + graph: Some(&g), + metrics_origin: MetricsOrigin::Declared, + bottlenecks: &ranks, + hypothesis: Some(&h), + diagnostic: None, + receipt: Some(&r), + ratification: None, + }); + assert!(d.nodes.iter().all(|n| !n.id.starts_with("rsi:receipt:"))); + let c = find(&d, &conclusion_id(CYCLE)); + assert!(c + .missing + .iter() + .any(|m| m.reason.contains("belongs to cycle cycle-other"))); +}