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/measure/select.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 / measure / select.rs` 165 lines ยท 5721 bytes Raw Blame History 1 //! Picks compatible completed samples and turns them into per-stage measurements. 2 3 use super::profile::MeasureContext; 4 use super::stats; 5 use super::{CycleSampleRecord, Stage, StageOutcome}; 6 use crate::graph::{CapabilityGraph, CapabilityNode}; 7 use crate::models::RsiConfig; 8 use std::collections::{BTreeMap, HashSet}; 9 10 #[derive(Debug, Clone, PartialEq)] 11 pub enum StageMeasurement { 12 Measured { 13 latency_median_us: f64, 14 /// None until `measure_p95_min_samples` valid compatible samples exist. 15 latency_p95_us: Option, 16 /// Share of compatible samples whose outcome was `failed`. 17 error_rate: f64, 18 sample_count: usize, 19 }, 20 Unavailable { 21 reason: String, 22 sample_count: usize, 23 }, 24 } 25 26 fn node_meta(stage: Stage) -> (&'static str, &'static str) { 27 match stage { 28 Stage::Observe => ("Observe Subsystem", "observe"), 29 Stage::Propose => ("Propose Subsystem", "propose"), 30 Stage::BuildJail => ("Build Jail", "isolation"), 31 Stage::JudgeEvaluation => ("Judge Evaluation", "actor"), 32 Stage::SupervisorCanary => ("Supervisor Canary", "supervisor"), 33 Stage::CortexCommit => ("Cortex Commit", "ratify"), 34 } 35 } 36 37 /// Measurements for all six stages from completed prior cycles. Never reads the current cycle. 38 /// A rejected (non-finite or negative) or unreadable input makes every stage unavailable with 39 /// the reason; nothing is clamped or defaulted. 40 pub fn measure_stages( 41 records: Result, String>, 42 current_cycle_id: &str, 43 ctx: &MeasureContext, 44 config: &RsiConfig, 45 ) -> BTreeMap { 46 let attempt = records.and_then(|r| { 47 try_measure( 48 &r, 49 current_cycle_id, 50 ctx, 51 config.measure_min_samples, 52 config.measure_window_cycles, 53 config.measure_p95_min_samples, 54 ) 55 }); 56 match attempt { 57 Ok(m) => m, 58 Err(e) => Stage::ALL 59 .iter() 60 .map(|s| { 61 ( 62 *s, 63 StageMeasurement::Unavailable { 64 reason: format!("stage samples were rejected: {e}"), 65 sample_count: 0, 66 }, 67 ) 68 }) 69 .collect(), 70 } 71 } 72 73 pub fn try_measure( 74 records: &[CycleSampleRecord], 75 current_cycle_id: &str, 76 ctx: &MeasureContext, 77 min_samples: usize, 78 window_cycles: usize, 79 p95_min_samples: usize, 80 ) -> Result, String> { 81 let mut seen = HashSet::new(); 82 let compatible: Vec<&CycleSampleRecord> = records 83 .iter() 84 .filter(|r| r.cycle_id != current_cycle_id) 85 .filter(|r| r.workload_key == ctx.workload_key) 86 .filter(|r| r.execution_profile_fingerprint == ctx.fingerprint) 87 .filter(|r| seen.insert(r.cycle_id.clone())) 88 .collect(); 89 let start = compatible.len().saturating_sub(window_cycles); 90 let window = &compatible[start..]; 91 92 let mut out = BTreeMap::new(); 93 for stage in Stage::ALL { 94 let mut durations = Vec::new(); 95 let mut failed = 0usize; 96 for rec in window { 97 let mut hits = rec.stages.iter().filter(|s| s.stage == stage); 98 if let Some(sample) = hits.next() { 99 if hits.next().is_some() { 100 return Err(format!( 101 "cycle {} records stage {} twice", 102 rec.cycle_id, 103 stage.id() 104 )); 105 } 106 durations.push(sample.duration_us as f64); 107 if sample.outcome == StageOutcome::Failed { 108 failed += 1; 109 } 110 } 111 } 112 let n = durations.len(); 113 let m = if n < min_samples { 114 StageMeasurement::Unavailable { 115 reason: format!( 116 "fewer than {min_samples} compatible completed samples in the last {window_cycles} cycles (found {n})" 117 ), 118 sample_count: n, 119 } 120 } else { 121 StageMeasurement::Measured { 122 latency_median_us: stats::median(&durations)?, 123 latency_p95_us: stats::p95_if_sufficient(&durations, p95_min_samples)?, 124 error_rate: failed as f64 / n as f64, 125 sample_count: n, 126 } 127 }; 128 out.insert(stage, m); 129 } 130 Ok(out) 131 } 132 133 /// The six-node pipeline graph. Edges are topology only; no edge latency feeds any score. 134 pub fn build_capability_graph( 135 measurements: &BTreeMap, 136 ) -> Result { 137 let mut graph = CapabilityGraph::new(); 138 for stage in Stage::ALL { 139 let (name, subsystem) = node_meta(stage); 140 let node = CapabilityNode::new(stage.id(), name, subsystem); 141 let node = match measurements.get(&stage) { 142 Some(StageMeasurement::Measured { 143 latency_median_us, 144 latency_p95_us, 145 error_rate, 146 sample_count, 147 }) => node.with_measured_latency( 148 *latency_median_us, 149 *latency_p95_us, 150 *error_rate, 151 *sample_count, 152 )?, 153 Some(StageMeasurement::Unavailable { 154 reason, 155 sample_count, 156 }) => node.with_unavailable(reason, *sample_count), 157 None => node.with_unavailable("stage was not measured", 0), 158 }; 159 graph.add_node(node); 160 } 161 for pair in Stage::ALL.windows(2) { 162 graph.add_edge(pair[0].id(), pair[1].id(), 0.0, 1.0); 163 } 164 Ok(graph) 165 }