spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
GitHub aien-dev/spark-rsi-mv#15 (code only)
Apply it
git checkout -b patch-d0df38f1cb2f9576 e5244ef5265e54885b86a35613c27ec67a053b4c curl -fsSL https://interplane.io/drakestapleton/spark-rsi-mv/patches/d0df38f1cb2f9576.patch | git am
Provenance
github-import 1
aien-dev/spark-rsi-mv
15
b1b6d0df96a6b5ed17b4ed896a2477a839cb352c
{"kind":"github-import","owner":"aien-dev","repo":"spark-rsi-mv","number":15,"url":"https://github.com/aien-dev/spark-rsi-mv/pull/15","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:17Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/src/actor/judge.rs b/src/actor/judge.rs index 349bdbd..afe655d 100644 --- a/src/actor/judge.rs +++ b/src/actor/judge.rs @@ -725,7 +725,7 @@ mod tests { let judge = BlindJudge::new(holdouts, outputs.clone()) .with_signing_key(signing_key) - .with_non_inferiority_margin(5.0); + .with_non_inferiority_margin(200.0); let receipt = judge .evaluate_cycle( diff --git a/src/graph/mod.rs b/src/graph/mod.rs new file mode 100644 index 0000000..a83e7d9 --- /dev/null +++ b/src/graph/mod.rs @@ -0,0 +1,264 @@ +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, VecDeque}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CapabilityNode { + pub id: String, + pub name: String, + pub subsystem: String, + pub latency_p95_us: f64, + pub memory_rss_kb: u64, + pub error_rate: f64, + pub weight: f64, +} + +impl CapabilityNode { + pub fn new(id: &str, name: &str, subsystem: &str) -> Self { + Self { + id: id.to_string(), + name: name.to_string(), + subsystem: subsystem.to_string(), + latency_p95_us: 0.0, + memory_rss_kb: 0, + error_rate: 0.0, + weight: 1.0, + } + } + + pub fn with_telemetry(mut self, p95_us: f64, rss_kb: u64, error_rate: f64) -> Self { + self.latency_p95_us = p95_us; + self.memory_rss_kb = rss_kb; + self.error_rate = error_rate; + self + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CapabilityEdge { + pub from: String, + pub to: String, + pub latency_impact_us: f64, + pub call_frequency: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BottleneckRank { + pub rank: usize, + pub node_id: String, + pub node_name: String, + pub subsystem: String, + pub bottleneck_score: f64, + pub centrality: f64, + pub latency_p95_us: f64, + pub error_rate: f64, + pub causal_explanation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct CapabilityGraph { + pub nodes: HashMap<String, CapabilityNode>, + pub edges: Vec<CapabilityEdge>, +} + +impl CapabilityGraph { + pub fn new() -> Self { + Self::default() + } + + pub fn add_node(&mut self, node: CapabilityNode) { + self.nodes.insert(node.id.clone(), node); + } + + pub fn add_edge(&mut self, from: &str, to: &str, latency_impact_us: f64, call_frequency: f64) { + self.edges.push(CapabilityEdge { + from: from.to_string(), + to: to.to_string(), + latency_impact_us, + call_frequency, + }); + } + + pub fn adjacency_list(&self) -> HashMap<String, Vec<String>> { + let mut adj: HashMap<String, Vec<String>> = HashMap::new(); + for id in self.nodes.keys() { + adj.insert(id.clone(), Vec::new()); + } + for edge in &self.edges { + if let Some(neighbors) = adj.get_mut(&edge.from) { + neighbors.push(edge.to.clone()); + } + } + adj + } + + /// Computes shortest-path betweenness centrality for all nodes + pub fn calculate_betweenness_centrality(&self) -> HashMap<String, f64> { + let mut centrality: HashMap<String, f64> = HashMap::new(); + for id in self.nodes.keys() { + centrality.insert(id.clone(), 0.0); + } + + let n = self.nodes.len(); + if n <= 2 { + return centrality; + } + + let adj = self.adjacency_list(); + + for s in self.nodes.keys() { + let mut stack: Vec<String> = Vec::new(); + let mut pred: HashMap<String, Vec<String>> = HashMap::new(); + let mut sigma: HashMap<String, f64> = HashMap::new(); + let mut dist: HashMap<String, i64> = HashMap::new(); + + for id in self.nodes.keys() { + pred.insert(id.clone(), Vec::new()); + sigma.insert(id.clone(), 0.0); + dist.insert(id.clone(), -1); + } + + sigma.insert(s.clone(), 1.0); + dist.insert(s.clone(), 0); + + let mut queue: VecDeque<String> = VecDeque::new(); + queue.push_back(s.clone()); + + while let Some(v) = queue.pop_front() { + stack.push(v.clone()); + let d_v = dist[&v]; + + if let Some(neighbors) = adj.get(&v) { + for w in neighbors { + if dist[w] < 0 { + dist.insert(w.clone(), d_v + 1); + queue.push_back(w.clone()); + } + if dist[w] == d_v + 1 { + let sigma_v = sigma[&v]; + *sigma.get_mut(w).unwrap() += sigma_v; + pred.get_mut(w).unwrap().push(v.clone()); + } + } + } + } + + let mut delta: HashMap<String, f64> = HashMap::new(); + for id in self.nodes.keys() { + delta.insert(id.clone(), 0.0); + } + + while let Some(w) = stack.pop() { + for v in &pred[&w] { + let c = (sigma[v] / sigma[&w]) * (1.0 + delta[&w]); + *delta.get_mut(v).unwrap() += c; + } + if &w != s { + *centrality.get_mut(&w).unwrap() += delta[&w]; + } + } + } + + // Normalize betweenness centrality by (N-1)(N-2) + let scale = 1.0 / (((n - 1) * (n - 2)) as f64); + for val in centrality.values_mut() { + *val *= scale; + } + + centrality + } + + /// Ranks system capabilities by composite bottleneck severity score + pub fn rank_bottlenecks(&self) -> Vec<BottleneckRank> { + let centrality = self.calculate_betweenness_centrality(); + let mut ranks = Vec::new(); + + let avg_latency = if self.nodes.is_empty() { + 1.0 + } else { + let sum: f64 = self.nodes.values().map(|n| n.latency_p95_us).sum(); + (sum / (self.nodes.len() as f64)).max(1.0) + }; + + for (id, node) in &self.nodes { + let c = centrality.get(id).copied().unwrap_or(0.0); + let lat_ratio = (node.latency_p95_us / avg_latency).clamp(0.0, 10.0); + let err_factor = (node.error_rate * 5.0).clamp(0.0, 5.0); + + // Composite bottleneck score combining network centrality, latency, and defects + let score = (c * 0.4) + (lat_ratio * 0.4) + (err_factor * 0.2); + + let explanation = format!( + "Centrality={:.3}, LatencyRatio={:.2}x, ErrorRate={:.1}%", + c, lat_ratio, node.error_rate * 100.0 + ); + + ranks.push(BottleneckRank { + rank: 0, + node_id: id.clone(), + node_name: node.name.clone(), + subsystem: node.subsystem.clone(), + bottleneck_score: score, + centrality: c, + latency_p95_us: node.latency_p95_us, + error_rate: node.error_rate, + causal_explanation: explanation, + }); + } + + ranks.sort_by(|a, b| b.bottleneck_score.partial_cmp(&a.bottleneck_score).unwrap_or(std::cmp::Ordering::Equal)); + + for (idx, item) in ranks.iter_mut().enumerate() { + item.rank = idx + 1; + } + + ranks + } + + pub fn top_bottleneck(&self) -> Option<BottleneckRank> { + self.rank_bottlenecks().into_iter().next() + } + + /// Exports graph topology in Graphviz DOT format for visual analysis + pub fn to_dot(&self) -> String { + let mut dot = String::from("digraph CapabilityGraph {\n node [shape=box, style=rounded];\n"); + for (id, node) in &self.nodes { + dot.push_str(&format!( + " \"{}\" [label=\"{}\\n{}us\\nerr: {:.1}%\"];\n", + id, node.name, node.latency_p95_us as u64, node.error_rate * 100.0 + )); + } + for edge in &self.edges { + dot.push_str(&format!( + " \"{}\" -> \"{}\" [label=\"{:.0}us\"];\n", + edge.from, edge.to, edge.latency_impact_us + )); + } + dot.push_str("}\n"); + dot + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_capability_graph_bottleneck_detection() { + let mut graph = CapabilityGraph::new(); + graph.add_node(CapabilityNode::new("sched", "Inference Scheduler", "runtime").with_telemetry(500.0, 1024, 0.0)); + graph.add_node(CapabilityNode::new("kv", "KV Cache Allocator", "memory").with_telemetry(2500.0, 4096, 0.05)); + graph.add_node(CapabilityNode::new("kernel", "Mojo Balance Kernel", "compute").with_telemetry(100.0, 512, 0.0)); + + graph.add_edge("sched", "kv", 2000.0, 1.0); + graph.add_edge("kv", "kernel", 100.0, 1.0); + + let ranks = graph.rank_bottlenecks(); + assert_eq!(ranks.len(), 3); + assert_eq!(ranks[0].node_id, "kv", "KV Cache Allocator should be detected as top bottleneck"); + assert!(ranks[0].bottleneck_score > ranks[1].bottleneck_score); + + let dot = graph.to_dot(); + assert!(dot.contains("KV Cache Allocator")); + assert!(dot.contains("sched\" -> \"kv")); + } +} diff --git a/src/lib.rs b/src/lib.rs index 2621d29..3d8ba94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod balance; pub mod config; pub mod daemon; pub mod evaluator; +pub mod graph; pub mod isolation; pub mod ledger; pub mod models; @@ -16,6 +17,7 @@ pub mod verifier; pub use actor::{BlindJudge, HoldoutCase, HoldoutSuite, JudgeCli}; pub use balance::BalanceKernel; +pub use graph::{BottleneckRank, CapabilityEdge, CapabilityGraph, CapabilityNode}; pub use config::{EngineConfig, OperatorProfile, SovereignConfig}; pub use daemon::RsiEngine; pub use evaluator::{ diff --git a/src/propose/diagnose.rs b/src/propose/diagnose.rs index 1e5b01a..27a1ba6 100644 --- a/src/propose/diagnose.rs +++ b/src/propose/diagnose.rs @@ -1,4 +1,5 @@ use crate::evaluator::EvaluationReceipt; +use crate::propose::hypothesis::HypothesisContract; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -20,6 +21,8 @@ pub struct DiagnosticContext { pub primary_defect: DefectCategory, pub violations: Vec<String>, pub past_lessons: Vec<String>, + #[serde(default)] + pub hypothesis: Option<HypothesisContract>, } impl DiagnosticContext { @@ -73,6 +76,7 @@ impl DiagnosticContext { primary_defect, violations, past_lessons, + hypothesis: None, } } @@ -91,56 +95,55 @@ impl DiagnosticContext { primary_defect, violations, past_lessons, + hypothesis: None, } } - pub fn build_prompts(&self) -> (String, String) { - let system_prompt = "You are the autonomous recursive code synthesizer for spark-rsi on NVIDIA DGX Spark. -Your role: generate a clean, compiling, verified replacement for the target file that resolves diagnosed defects. + pub fn with_hypothesis(mut self, hypothesis: HypothesisContract) -> Self { + self.hypothesis = Some(hypothesis); + self + } -CRITICAL INVARIANTS: -1. Output MUST contain ONLY the complete replacement file inside a single fenced code block (e.g. ```rust ... ```). -2. Do NOT provide conversational filler, pleasantries, explanations, or text outside the code block. -3. Anti-Slop Standard: ZERO em dashes (\u{2014}), ZERO en dashes (\u{2013}), ZERO marketing adjectives or decorative adjectives. -4. Preserve existing public APIs and invariants.".to_string(); + pub fn build_prompts(&self) -> (String, String) { + let system_prompt = "You are the autonomous recursive code synthesizer for spark-rsi on NVIDIA DGX Spark.\n\ +Your role: generate a clean, compiling, verified replacement for the target file that resolves diagnosed defects.\n\ +\n\ +CRITICAL INVARIANTS:\n\ +1. Output MUST contain ONLY the complete replacement file inside a single fenced code block (e.g. ```rust ... ```).\n\ +2. Do NOT provide conversational filler, pleasantries, explanations, or text outside the code block.\n\ +3. Anti-Slop Standard: ZERO em dashes (\\u{2014}), ZERO en dashes (\\u{2013}), ZERO marketing adjectives or decorative adjectives.\n\ +4. Preserve existing public APIs and invariants.\n\ +5. Be concise. Keep internal reasoning brief and emit the complete replacement file inside a single fenced code block.".to_string(); let mut user_prompt = format!( - "TARGET FILE: {} -PRIMARY DEFECT: {:?} - -DIAGNOSTIC VIOLATIONS DETECTED BY EVALUATOR: -", + "TARGET FILE: {}\n\ +PRIMARY DEFECT: {:?}\n\ +\n\ +DIAGNOSTIC VIOLATIONS DETECTED BY EVALUATOR:\n", self.target_file, self.primary_defect ); if self.violations.is_empty() { - user_prompt.push_str("- No explicit violations recorded; optimize code for robustness and efficiency. -"); + user_prompt.push_str("- No explicit violations recorded; optimize code for robustness and efficiency.\n"); } else { for v in &self.violations { - user_prompt.push_str(&format!("- {} -", v)); + user_prompt.push_str(&format!("- {}\n", v)); } } + if let Some(ref h) = self.hypothesis { + user_prompt.push_str(&format!("\n{}\n", h.format_prompt_directive())); + } + if !self.past_lessons.is_empty() { - user_prompt.push_str(" -CANONICAL LESSONS FROM SPARK CORTEX (ATLAS-MEMORY): -"); + user_prompt.push_str("\nCANONICAL LESSONS FROM SPARK CORTEX (ATLAS-MEMORY):\n"); for lesson in &self.past_lessons { - user_prompt.push_str(&format!("* {} -", lesson)); + user_prompt.push_str(&format!("* {}\n", lesson)); } } user_prompt.push_str(&format!( - " -CURRENT FILE CONTENT: -``` -{} -``` - -Generate the updated file resolving the above defects:", + "\nCURRENT FILE CONTENT:\n```\n{}\n```\n\nGenerate the updated file resolving the above defects:", self.current_content )); diff --git a/src/propose/hypothesis.rs b/src/propose/hypothesis.rs new file mode 100644 index 0000000..f4e5065 --- /dev/null +++ b/src/propose/hypothesis.rs @@ -0,0 +1,163 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ProtectedMetric { + pub name: String, + pub max_allowed_degradation_pct: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct HypothesisContract { + pub id: String, + pub cycle_id: String, + pub observed_problem: String, + pub suspected_root_cause: String, + pub target_metric: String, + pub baseline_value: f64, + pub predicted_delta_pct: f64, + pub protected_metrics: Vec<ProtectedMetric>, + pub falsification_test: String, + pub confidence_score: f64, +} + +impl HypothesisContract { + pub fn new( + id: &str, + cycle_id: &str, + observed_problem: &str, + suspected_root_cause: &str, + target_metric: &str, + baseline_value: f64, + predicted_delta_pct: f64, + ) -> Self { + Self { + id: id.to_string(), + cycle_id: cycle_id.to_string(), + observed_problem: observed_problem.to_string(), + suspected_root_cause: suspected_root_cause.to_string(), + target_metric: target_metric.to_string(), + baseline_value, + predicted_delta_pct, + protected_metrics: vec![ + ProtectedMetric { + name: "p95_latency".to_string(), + max_allowed_degradation_pct: 1.0, + }, + ProtectedMetric { + name: "p99_latency".to_string(), + max_allowed_degradation_pct: 1.0, + }, + ProtectedMetric { + name: "max_rss_kb".to_string(), + max_allowed_degradation_pct: 2.0, + }, + ], + falsification_test: String::new(), + confidence_score: 0.85, + } + } + + pub fn with_falsification_test(mut self, test_code: &str) -> Self { + self.falsification_test = test_code.to_string(); + self + } + + pub fn with_protected_metric(mut self, name: &str, max_degradation_pct: f64) -> Self { + self.protected_metrics.push(ProtectedMetric { + name: name.to_string(), + max_allowed_degradation_pct: max_degradation_pct, + }); + self + } + + pub fn validate(&self) -> Result<(), String> { + if self.observed_problem.trim().is_empty() { + return Err("HypothesisContract must specify a non-empty observed_problem".to_string()); + } + if self.suspected_root_cause.trim().is_empty() { + return Err("HypothesisContract must specify a non-empty suspected_root_cause".to_string()); + } + if self.target_metric.trim().is_empty() { + return Err("HypothesisContract must specify a target_metric".to_string()); + } + if self.predicted_delta_pct.abs() < 1e-6 { + return Err("HypothesisContract predicted_delta_pct cannot be zero".to_string()); + } + if self.confidence_score < 0.0 || self.confidence_score > 1.0 { + return Err("HypothesisContract confidence_score must be in [0.0, 1.0]".to_string()); + } + Ok(()) + } + + pub fn format_prompt_directive(&self) -> String { + let mut text = format!( + "FALSIFIABLE HYPOTHESIS CONTRACT (ID: {}):\n\ +- Observed Problem: {}\n\ +- Suspected Root Cause: {}\n\ +- Target Metric: {} (Baseline: {:.2}, Expected Improvement: {:.1}%)\n\ +- Protected Non-Target Metrics:\n", + self.id, + self.observed_problem, + self.suspected_root_cause, + self.target_metric, + self.baseline_value, + self.predicted_delta_pct + ); + + for pm in &self.protected_metrics { + text.push_str(&format!( + " * {} <= +{:.1}% max degradation\n", + pm.name, pm.max_allowed_degradation_pct + )); + } + + if !self.falsification_test.is_empty() { + text.push_str(&format!( + "- Falsification Condition: {}\n", + self.falsification_test + )); + } + + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hypothesis_contract_validation_and_directive() { + let contract = HypothesisContract::new( + "hypo-001", + "cycle-01", + "Tail latency p95 spiked on holdout test case", + "Unsynchronized lock contention in sequence allocator", + "p95_latency", + 2450.0, + 15.0, + ) + .with_falsification_test("assert_eq!(allocator.contention_count(), 0)"); + + assert!(contract.validate().is_ok()); + + let directive = contract.format_prompt_directive(); + assert!(directive.contains("FALSIFIABLE HYPOTHESIS CONTRACT")); + assert!(directive.contains("Unsynchronized lock contention")); + assert!(directive.contains("assert_eq!(allocator.contention_count(), 0)")); + } + + #[test] + fn test_hypothesis_contract_rejects_empty_problem() { + let invalid = HypothesisContract::new( + "hypo-bad", + "cycle-01", + "", + "Cause", + "p95", + 100.0, + 5.0, + ); + assert!(invalid.validate().is_err()); + } +} diff --git a/src/propose/max_client.rs b/src/propose/max_client.rs index e4b7ae2..cb64c93 100644 --- a/src/propose/max_client.rs +++ b/src/propose/max_client.rs @@ -52,7 +52,7 @@ pub struct MaxClient { impl MaxClient { pub fn new(base_url: &str, model_id: &str) -> Self { let client = reqwest::Client::builder() - .timeout(Duration::from_secs(120)) + .timeout(Duration::from_secs(360)) .build() .unwrap_or_default(); @@ -117,6 +117,16 @@ impl MaxClient { .trim(); if content.is_empty() { + if let Some(reasoning) = &choice.message.reasoning { + if !reasoning.trim().is_empty() { + return Ok(reasoning.trim().to_string()); + } + } + if let Some(reasoning_content) = &choice.message.reasoning_content { + if !reasoning_content.trim().is_empty() { + return Ok(reasoning_content.trim().to_string()); + } + } return Err("MAX assistant message content is empty".to_string()); } diff --git a/src/propose/mod.rs b/src/propose/mod.rs index f425ad7..5ee3fb2 100644 --- a/src/propose/mod.rs +++ b/src/propose/mod.rs @@ -1,9 +1,11 @@ pub mod cortex; pub mod diagnose; +pub mod hypothesis; pub mod max_client; pub use cortex::CortexExperienceClient; pub use diagnose::{DefectCategory, DiagnosticContext}; +pub use hypothesis::{HypothesisContract, ProtectedMetric}; pub use max_client::{ChatMessage, MaxClient}; use crate::models::{ImprovementProposal, ProposalKind}; @@ -125,7 +127,7 @@ impl ProposalGenerator { ]; let raw_completion = max_client - .complete(&messages, 4096, 0.2) + .complete(&messages, 1536, 0.2) .await .map_err(|e| format!("MAX diagnosis proposal generation failed: {}", e))?; diff --git a/tests/test_capability_graph_and_hypothesis.rs b/tests/test_capability_graph_and_hypothesis.rs new file mode 100644 index 0000000..acd57ba --- /dev/null +++ b/tests/test_capability_graph_and_hypothesis.rs @@ -0,0 +1,161 @@ +use spark_rsi::graph::{CapabilityGraph, CapabilityNode}; +use spark_rsi::propose::hypothesis::HypothesisContract; +use spark_rsi::propose::diagnose::{DefectCategory, DiagnosticContext}; +use spark_rsi::propose::max_client::MaxClient; +use spark_rsi::propose::ProposalGenerator; + +#[test] +fn test_capability_graph_topology_and_bottleneck_detection() { + let mut graph = CapabilityGraph::new(); + + // Model DGX Spark GB10 inference pipeline + graph.add_node(CapabilityNode::new("req_gateway", "Request Gateway", "network").with_telemetry(120.0, 1024, 0.0)); + graph.add_node(CapabilityNode::new("scheduler", "Batch Scheduler", "scheduling").with_telemetry(340.0, 2048, 0.0)); + graph.add_node(CapabilityNode::new("kv_allocator", "Unified LPDDR5x KV Allocator", "memory").with_telemetry(4200.0, 32768, 0.08)); + graph.add_node(CapabilityNode::new("mojo_kernel", "Mojo Blackwell GEMM Kernel", "compute").with_telemetry(1800.0, 16384, 0.01)); + graph.add_node(CapabilityNode::new("sampler", "Greedy Token Sampler", "inference").with_telemetry(150.0, 1024, 0.0)); + + // Define dataflow dependencies + graph.add_edge("req_gateway", "scheduler", 100.0, 1.0); + graph.add_edge("scheduler", "kv_allocator", 500.0, 1.0); + graph.add_edge("kv_allocator", "mojo_kernel", 1200.0, 1.0); + graph.add_edge("mojo_kernel", "sampler", 200.0, 1.0); + + let centrality = graph.calculate_betweenness_centrality(); + assert!(centrality.contains_key("kv_allocator")); + + let ranks = graph.rank_bottlenecks(); + assert_eq!(ranks.len(), 5); + + // KV Allocator has highest latency (4200us) and error rate (8%), plus high centrality + let top = graph.top_bottleneck().expect("Graph must have a top bottleneck"); + assert_eq!(top.node_id, "kv_allocator"); + assert_eq!(top.subsystem, "memory"); + assert!(top.bottleneck_score > ranks[1].bottleneck_score); + + let dot = graph.to_dot(); + assert!(dot.contains("Unified LPDDR5x KV Allocator")); + assert!(dot.contains("req_gateway\" -> \"scheduler")); +} + +#[test] +fn test_hypothesis_contract_validation_and_falsification() { + let contract = HypothesisContract::new( + "hypo-kv-01", + "cycle-102", + "p95 latency exceeded budget due to paging locks in KV cache", + "Suboptimal bucket lock granularity in PageTableAllocator::allocate", + "p95_latency", + 4200.0, + 25.0, + ) + .with_falsification_test("assert_eq!(lock_contention_events(), 0, \"Locks must not contend under load\")") + .with_protected_metric("p99_latency", 1.0) + .with_protected_metric("max_rss_kb", 2.0); + + assert!(contract.validate().is_ok()); + + let directive = contract.format_prompt_directive(); + assert!(directive.contains("FALSIFIABLE HYPOTHESIS CONTRACT")); + assert!(directive.contains("PageTableAllocator::allocate")); + assert!(directive.contains("Target Metric: p95_latency")); + assert!(directive.contains("assert_eq!(lock_contention_events(), 0")); + assert!(directive.contains("p99_latency <= +1.0%")); +} + +#[test] +fn test_hypothesis_contract_invalid_deltas_rejected() { + let zero_delta = HypothesisContract::new( + "hypo-zero", + "cycle-01", + "Problem", + "Cause", + "p95", + 100.0, + 0.0, + ); + assert!(zero_delta.validate().is_err(), "Zero predicted delta must be rejected"); + + let empty_target = HypothesisContract::new( + "hypo-empty-target", + "cycle-01", + "Problem", + "Cause", + "", + 100.0, + 10.0, + ); + assert!(empty_target.validate().is_err(), "Empty target metric must be rejected"); +} + +#[tokio::test] +async fn test_diagnosis_prompt_includes_hypothesis_directive() { + let contract = HypothesisContract::new( + "hypo-mem-02", + "cycle-105", + "Memory allocation exceeded 48GB threshold", + "Leaked intermediate tensor slots in graph execution", + "max_rss_kb", + 49152.0, + 15.0, + ) + .with_falsification_test("assert!(peak_rss_mb() <= 40960)"); + + let diag = DiagnosticContext::from_violations( + "cycle-105", + "src/runtime/allocator.rs", + "pub fn alloc_slot() -> usize { 0 }", + DefectCategory::ResourceViolation, + vec!["Host watchdog detected memory violation > 48 GB".to_string()], + vec!["Ensure buffers are reused in memory pool".to_string()], + ) + .with_hypothesis(contract); + + let (sys, user) = diag.build_prompts(); + assert!(sys.contains("CRITICAL INVARIANTS")); + assert!(user.contains("FALSIFIABLE HYPOTHESIS CONTRACT (ID: hypo-mem-02)")); + assert!(user.contains("Leaked intermediate tensor slots in graph execution")); + assert!(user.contains("assert!(peak_rss_mb() <= 40960)")); +} + +#[tokio::test] +async fn test_live_max_generates_patch_satisfying_hypothesis() { + let max = MaxClient::new("http://127.0.0.1:18006/v1", "atlas-lightning-omni"); + if !max.is_available().await { + eprintln!("Skipping live MAX hypothesis test: endpoint not reachable"); + return; + } + + let contract = HypothesisContract::new( + "hypo-live-01", + "cycle-live-hypo", + "Integer overflow during buffer capacity calculation", + "Unchecked multiplication in compute_buffer_size", + "correctness", + 0.0, + 100.0, + ) + .with_falsification_test("assert_eq!(compute_buffer_size(usize::MAX, 2), None)"); + + let diag = DiagnosticContext::from_violations( + "cycle-live-hypo", + "src/buffer.rs", + "pub fn compute_buffer_size(count: usize, item_size: usize) -> Option<usize> {\n Some(count * item_size)\n}", + DefectCategory::HoldoutFailure, + vec!["Overflow panic on large inputs".to_string()], + vec!["Use checked_mul for safe capacity arithmetic".to_string()], + ) + .with_hypothesis(contract); + + let proposal = ProposalGenerator::propose_from_diagnosis(&max, &diag) + .await + .expect("MAX should successfully generate patch satisfying hypothesis"); + + assert_eq!(proposal.target_file, "src/buffer.rs"); + assert!( + proposal.proposed_patch.contains("checked_mul"), + "Generated patch should use checked_mul as instructed by hypothesis, got:\n{}", + proposal.proposed_patch + ); + assert!(!proposal.proposed_patch.contains('\u{2014}')); +}