interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / graph / mod.rs

514 lines · 18672 bytes Raw Blame History
1use serde::{Deserialize, Serialize};
2use std::collections::{HashMap, VecDeque};
3
4/// Whether a node carries a measurement. Unavailable is an explicit state; zero never means missing.
5#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
6#[serde(rename_all = "snake_case")]
7pub enum Measurement {
8 Measured,
9 #[default]
10 Unavailable,
11}
12
13/// What the bottleneck score was computed from.
14#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
15#[serde(rename_all = "snake_case")]
16pub enum RankingBasis {
17 /// Betweenness centrality only: at least one node has no measurement (cold start).
18 #[default]
19 Structural,
20 /// Centrality, measured median latency and measured error rate. Every node is measured.
21 Measured,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
25pub struct CapabilityNode {
26 pub id: String,
27 pub name: String,
28 pub subsystem: String,
29 /// Legacy compatibility field. Ranking and explanation never read it; they read `measurement`.
30 pub latency_p95_us: f64,
31 pub memory_rss_kb: u64,
32 /// Legacy compatibility field. Ranking and explanation read `error_rate_measured`.
33 pub error_rate: f64,
34 pub weight: f64,
35 #[serde(default)]
36 pub measurement: Measurement,
37 #[serde(default)]
38 pub latency_median_us: Option<f64>,
39 #[serde(default)]
40 pub latency_p95_us_measured: Option<f64>,
41 #[serde(default)]
42 pub error_rate_measured: Option<f64>,
43 #[serde(default)]
44 pub sample_count: usize,
45 /// Why the node is unavailable (or why p95 is unavailable), in plain words.
46 #[serde(default)]
47 pub unavailable_reason: Option<String>,
48}
49
50fn check_finite_nonneg(name: &str, v: f64) -> Result<(), String> {
51 if v.is_finite() && v >= 0.0 {
52 Ok(())
53 } else {
54 Err(format!("{name} must be finite and not negative, got {v}"))
55 }
56}
57
58impl CapabilityNode {
59 pub fn new(id: &str, name: &str, subsystem: &str) -> Self {
60 Self {
61 id: id.to_string(),
62 name: name.to_string(),
63 subsystem: subsystem.to_string(),
64 latency_p95_us: 0.0,
65 memory_rss_kb: 0,
66 error_rate: 0.0,
67 weight: 1.0,
68 measurement: Measurement::Unavailable,
69 latency_median_us: None,
70 latency_p95_us_measured: None,
71 error_rate_measured: None,
72 sample_count: 0,
73 unavailable_reason: Some("no measurement was supplied for this node".to_string()),
74 }
75 }
76
77 /// Fills the legacy compatibility fields only. The node stays unavailable: a caller-supplied
78 /// number is not a measurement, so the ranking does not read it.
79 pub fn with_resource_metrics(mut self, p95_us: f64, rss_kb: u64, error_rate: f64) -> Self {
80 self.latency_p95_us = p95_us;
81 self.memory_rss_kb = rss_kb;
82 self.error_rate = error_rate;
83 self
84 }
85
86 /// Marks the node measured. Non-finite or negative values are rejected, never clamped.
87 pub fn with_measured_latency(
88 mut self,
89 median_us: f64,
90 p95_us: Option<f64>,
91 error_rate: f64,
92 sample_count: usize,
93 ) -> Result<Self, String> {
94 check_finite_nonneg("latency_median_us", median_us)?;
95 if let Some(p) = p95_us {
96 check_finite_nonneg("latency_p95_us_measured", p)?;
97 }
98 check_finite_nonneg("error_rate_measured", error_rate)?;
99 if error_rate > 1.0 {
100 return Err(format!(
101 "error_rate_measured must be at most 1, got {error_rate}"
102 ));
103 }
104 self.measurement = Measurement::Measured;
105 self.latency_median_us = Some(median_us);
106 self.latency_p95_us_measured = p95_us;
107 self.error_rate_measured = Some(error_rate);
108 self.sample_count = sample_count;
109 self.unavailable_reason = if p95_us.is_some() {
110 None
111 } else {
112 Some("p95 is unavailable: too few valid compatible samples".to_string())
113 };
114 Ok(self)
115 }
116
117 /// Marks the node unavailable with the reason in plain words.
118 pub fn with_unavailable(mut self, reason: &str, sample_count: usize) -> Self {
119 self.measurement = Measurement::Unavailable;
120 self.latency_median_us = None;
121 self.latency_p95_us_measured = None;
122 self.error_rate_measured = None;
123 self.sample_count = sample_count;
124 self.unavailable_reason = Some(reason.to_string());
125 self
126 }
127
128 /// The measured values the ranking may read, or the reason there are none.
129 fn scoring_inputs(&self) -> Result<(f64, f64), String> {
130 if self.measurement != Measurement::Measured {
131 return Err(self
132 .unavailable_reason
133 .clone()
134 .unwrap_or_else(|| "no measurement".to_string()));
135 }
136 let (Some(median), Some(err)) = (self.latency_median_us, self.error_rate_measured) else {
137 return Err("measured state without a median latency or error rate".to_string());
138 };
139 check_finite_nonneg("latency_median_us", median)?;
140 check_finite_nonneg("error_rate_measured", err)?;
141 if err > 1.0 {
142 return Err(format!("error_rate_measured must be at most 1, got {err}"));
143 }
144 Ok((median, err))
145 }
146}
147
148/// A call-order link between two nodes. In the pipeline graph the edges carry topology only;
149/// `latency_impact_us` is not a measurement and no score reads it.
150#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
151pub struct CapabilityEdge {
152 pub from: String,
153 pub to: String,
154 pub latency_impact_us: f64,
155 pub call_frequency: f64,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
159pub struct BottleneckRank {
160 pub rank: usize,
161 pub node_id: String,
162 pub node_name: String,
163 pub subsystem: String,
164 pub bottleneck_score: f64,
165 pub centrality: f64,
166 /// Legacy compatibility field, copied from the node. Not a measurement.
167 pub latency_p95_us: f64,
168 /// Legacy compatibility field, copied from the node. Not a measurement.
169 pub error_rate: f64,
170 pub causal_explanation: String,
171 #[serde(default)]
172 pub measurement: Measurement,
173 #[serde(default)]
174 pub latency_median_us: Option<f64>,
175 #[serde(default)]
176 pub latency_p95_us_measured: Option<f64>,
177 #[serde(default)]
178 pub error_rate_measured: Option<f64>,
179 #[serde(default)]
180 pub sample_count: usize,
181 #[serde(default)]
182 pub unavailable_reason: Option<String>,
183 #[serde(default)]
184 pub ranking_basis: RankingBasis,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize, Default)]
188pub struct CapabilityGraph {
189 pub nodes: HashMap<String, CapabilityNode>,
190 pub edges: Vec<CapabilityEdge>,
191}
192
193impl CapabilityGraph {
194 pub fn new() -> Self {
195 Self::default()
196 }
197
198 pub fn add_node(&mut self, node: CapabilityNode) {
199 self.nodes.insert(node.id.clone(), node);
200 }
201
202 pub fn add_edge(&mut self, from: &str, to: &str, latency_impact_us: f64, call_frequency: f64) {
203 self.edges.push(CapabilityEdge {
204 from: from.to_string(),
205 to: to.to_string(),
206 latency_impact_us,
207 call_frequency,
208 });
209 }
210
211 pub fn adjacency_list(&self) -> HashMap<String, Vec<String>> {
212 let mut adj: HashMap<String, Vec<String>> = HashMap::new();
213 for id in self.nodes.keys() {
214 adj.insert(id.clone(), Vec::new());
215 }
216 for edge in &self.edges {
217 if let Some(neighbors) = adj.get_mut(&edge.from) {
218 neighbors.push(edge.to.clone());
219 }
220 }
221 adj
222 }
223
224 /// Computes shortest-path betweenness centrality for all nodes
225 pub fn calculate_betweenness_centrality(&self) -> HashMap<String, f64> {
226 let mut centrality: HashMap<String, f64> = HashMap::new();
227 for id in self.nodes.keys() {
228 centrality.insert(id.clone(), 0.0);
229 }
230
231 let n = self.nodes.len();
232 if n <= 2 {
233 return centrality;
234 }
235
236 let adj = self.adjacency_list();
237
238 // Sorted so float accumulation order, and so every score, is the same on every run.
239 let mut sources: Vec<&String> = self.nodes.keys().collect();
240 sources.sort();
241 for s in sources {
242 let mut stack: Vec<String> = Vec::new();
243 let mut pred: HashMap<String, Vec<String>> = HashMap::new();
244 let mut sigma: HashMap<String, f64> = HashMap::new();
245 let mut dist: HashMap<String, i64> = HashMap::new();
246
247 for id in self.nodes.keys() {
248 pred.insert(id.clone(), Vec::new());
249 sigma.insert(id.clone(), 0.0);
250 dist.insert(id.clone(), -1);
251 }
252
253 sigma.insert(s.clone(), 1.0);
254 dist.insert(s.clone(), 0);
255
256 let mut queue: VecDeque<String> = VecDeque::new();
257 queue.push_back(s.clone());
258
259 while let Some(v) = queue.pop_front() {
260 stack.push(v.clone());
261 let d_v = dist[&v];
262
263 if let Some(neighbors) = adj.get(&v) {
264 for w in neighbors {
265 if dist[w] < 0 {
266 dist.insert(w.clone(), d_v + 1);
267 queue.push_back(w.clone());
268 }
269 if dist[w] == d_v + 1 {
270 let sigma_v = sigma[&v];
271 *sigma.get_mut(w).unwrap() += sigma_v;
272 pred.get_mut(w).unwrap().push(v.clone());
273 }
274 }
275 }
276 }
277
278 let mut delta: HashMap<String, f64> = HashMap::new();
279 for id in self.nodes.keys() {
280 delta.insert(id.clone(), 0.0);
281 }
282
283 while let Some(w) = stack.pop() {
284 for v in &pred[&w] {
285 let c = (sigma[v] / sigma[&w]) * (1.0 + delta[&w]);
286 *delta.get_mut(v).unwrap() += c;
287 }
288 if &w != s {
289 *centrality.get_mut(&w).unwrap() += delta[&w];
290 }
291 }
292 }
293
294 // Normalize betweenness centrality by (N-1)(N-2)
295 let scale = 1.0 / (((n - 1) * (n - 2)) as f64);
296 for val in centrality.values_mut() {
297 *val *= scale;
298 }
299
300 centrality
301 }
302
303 /// Ranks system capabilities by composite bottleneck severity score.
304 ///
305 /// When every node is measured the score combines centrality, the measured median latency
306 /// ratio and the measured error rate. If any node is unavailable (cold start) the score is the
307 /// betweenness centrality alone and the latency and error terms are unavailable. Missing is
308 /// never read as zero. Order: score descending, then node id ascending (byte order). Scores
309 /// are compared at 1e-9 resolution so float rounding cannot override the id tie-break.
310 pub fn rank_bottlenecks(&self) -> Vec<BottleneckRank> {
311 let centrality = self.calculate_betweenness_centrality();
312 let inputs: HashMap<&String, Result<(f64, f64), String>> = self
313 .nodes
314 .iter()
315 .map(|(id, n)| (id, n.scoring_inputs()))
316 .collect();
317 let measured_basis = !self.nodes.is_empty() && inputs.values().all(|r| r.is_ok());
318 let basis = if measured_basis {
319 RankingBasis::Measured
320 } else {
321 RankingBasis::Structural
322 };
323
324 let avg_latency = if measured_basis {
325 let mut ids: Vec<&String> = self.nodes.keys().collect();
326 ids.sort();
327 let sum: f64 = ids
328 .iter()
329 .filter_map(|id| inputs[*id].as_ref().ok().map(|(m, _)| *m))
330 .sum();
331 (sum / (self.nodes.len() as f64)).max(1.0)
332 } else {
333 1.0
334 };
335
336 let mut ranks = Vec::new();
337 for (id, node) in &self.nodes {
338 let c = centrality.get(id).copied().unwrap_or(0.0);
339 let (score, explanation) = match (&inputs[id], measured_basis) {
340 (Ok((median, err)), true) => {
341 let lat_ratio = (median / avg_latency).clamp(0.0, 10.0);
342 let err_factor = (err * 5.0).clamp(0.0, 5.0);
343 // Composite bottleneck score combining network centrality, latency, and defects
344 let score = (c * 0.4) + (lat_ratio * 0.4) + (err_factor * 0.2);
345 (
346 score,
347 format!(
348 "Centrality={:.3}, LatencyRatio={:.2}x (median), ErrorRate={:.1}%",
349 c,
350 lat_ratio,
351 err * 100.0
352 ),
353 )
354 }
355 _ => (
356 c,
357 format!(
358 "Centrality={:.3}; latency and error terms unavailable (structural ranking)",
359 c
360 ),
361 ),
362 };
363
364 ranks.push(BottleneckRank {
365 rank: 0,
366 node_id: id.clone(),
367 node_name: node.name.clone(),
368 subsystem: node.subsystem.clone(),
369 bottleneck_score: score,
370 centrality: c,
371 latency_p95_us: node.latency_p95_us,
372 error_rate: node.error_rate,
373 causal_explanation: explanation,
374 measurement: if inputs[id].is_ok() {
375 Measurement::Measured
376 } else {
377 Measurement::Unavailable
378 },
379 latency_median_us: node.latency_median_us.filter(|_| inputs[id].is_ok()),
380 latency_p95_us_measured: node
381 .latency_p95_us_measured
382 .filter(|_| inputs[id].is_ok()),
383 error_rate_measured: node.error_rate_measured.filter(|_| inputs[id].is_ok()),
384 sample_count: node.sample_count,
385 unavailable_reason: match &inputs[id] {
386 Err(reason) => Some(reason.clone()),
387 Ok(_) => node.unavailable_reason.clone(),
388 },
389 ranking_basis: basis,
390 });
391 }
392
393 let quantize = |s: f64| (s * 1e9).round() as i64;
394 ranks.sort_by(|a, b| {
395 quantize(b.bottleneck_score)
396 .cmp(&quantize(a.bottleneck_score))
397 .then_with(|| a.node_id.as_bytes().cmp(b.node_id.as_bytes()))
398 });
399
400 for (idx, item) in ranks.iter_mut().enumerate() {
401 item.rank = idx + 1;
402 }
403
404 ranks
405 }
406
407 pub fn top_bottleneck(&self) -> Option<BottleneckRank> {
408 self.rank_bottlenecks().into_iter().next()
409 }
410
411 /// Exports graph topology in Graphviz DOT format for visual analysis
412 pub fn to_dot(&self) -> String {
413 let mut dot =
414 String::from("digraph CapabilityGraph {\n node [shape=box, style=rounded];\n");
415 let mut ids: Vec<&String> = self.nodes.keys().collect();
416 ids.sort();
417 for id in ids {
418 let node = &self.nodes[id];
419 let label = match (node.measurement, node.latency_median_us) {
420 (Measurement::Measured, Some(median)) => format!("median {:.0}us", median),
421 _ => "unavailable".to_string(),
422 };
423 dot.push_str(&format!(
424 " \"{}\" [label=\"{}\\n{}\"];\n",
425 id, node.name, label
426 ));
427 }
428 for edge in &self.edges {
429 dot.push_str(&format!(" \"{}\" -> \"{}\";\n", edge.from, edge.to));
430 }
431 dot.push_str("}\n");
432 dot
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 #[test]
441 fn test_capability_graph_bottleneck_detection() {
442 let mut graph = CapabilityGraph::new();
443 graph.add_node(
444 CapabilityNode::new("sched", "Inference Scheduler", "runtime")
445 .with_measured_latency(500.0, None, 0.0, 5)
446 .unwrap(),
447 );
448 graph.add_node(
449 CapabilityNode::new("kv", "KV Cache Allocator", "memory")
450 .with_measured_latency(2500.0, None, 0.05, 5)
451 .unwrap(),
452 );
453 graph.add_node(
454 CapabilityNode::new("kernel", "Balance Kernel", "compute")
455 .with_measured_latency(100.0, None, 0.0, 5)
456 .unwrap(),
457 );
458
459 graph.add_edge("sched", "kv", 2000.0, 1.0);
460 graph.add_edge("kv", "kernel", 100.0, 1.0);
461
462 let ranks = graph.rank_bottlenecks();
463 assert_eq!(ranks.len(), 3);
464 assert_eq!(
465 ranks[0].node_id, "kv",
466 "KV Cache Allocator should be detected as top bottleneck"
467 );
468 assert!(ranks[0].bottleneck_score > ranks[1].bottleneck_score);
469
470 let dot = graph.to_dot();
471 assert!(dot.contains("KV Cache Allocator"));
472 assert!(dot.contains("sched\" -> \"kv"));
473 }
474
475 #[test]
476 fn unavailable_nodes_rank_structurally_and_ties_break_by_id() {
477 let mut graph = CapabilityGraph::new();
478 for id in ["b", "a", "c", "d"] {
479 graph.add_node(CapabilityNode::new(id, id, "s").with_resource_metrics(9999.0, 1, 0.9));
480 }
481 graph.add_edge("a", "b", 0.0, 1.0);
482 graph.add_edge("a", "c", 0.0, 1.0);
483 graph.add_edge("b", "d", 0.0, 1.0);
484 graph.add_edge("c", "d", 0.0, 1.0);
485 let first = graph.rank_bottlenecks();
486 assert!(first
487 .iter()
488 .all(|r| r.ranking_basis == RankingBasis::Structural));
489 assert!(first
490 .iter()
491 .all(|r| r.measurement == Measurement::Unavailable));
492 // b and c tie on centrality, so id order decides.
493 assert_eq!(first[0].node_id, "b");
494 assert_eq!(first[1].node_id, "c");
495 for _ in 0..20 {
496 assert_eq!(graph.rank_bottlenecks(), first);
497 }
498 }
499
500 #[test]
501 fn non_finite_and_negative_measurements_are_rejected() {
502 let n = CapabilityNode::new("x", "x", "s");
503 assert!(n
504 .clone()
505 .with_measured_latency(f64::NAN, None, 0.0, 3)
506 .is_err());
507 assert!(n.clone().with_measured_latency(-1.0, None, 0.0, 3).is_err());
508 assert!(n
509 .clone()
510 .with_measured_latency(1.0, Some(f64::INFINITY), 0.0, 3)
511 .is_err());
512 assert!(n.with_measured_latency(1.0, None, 1.5, 3).is_err());
513 }
514}