aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
aien-protocols-mv / crates / aien-probe / tests / probe_engine_tests.rs
| 1 | use aien_evaluation_protocol::{ |
| 2 | CanaryRollbackHarness, EvaluationPlan, Evaluator, EvaluatorStatus, SoftwareP256Signer, Verdict, |
| 3 | VerifierIdentity, VerifierSigner, |
| 4 | }; |
| 5 | use aien_probe::{ |
| 6 | Choice, ChoiceOption, DeterministicReferenceBackend, HttpProbeBackend, Noul, Probe, |
| 7 | ProbeBackend, ProbeEngine, ProbeEvaluator, ProbeEvaluatorConfig, ProbeGate, ProbeSet, Score, |
| 8 | }; |
| 9 | use aien_protocol_types::{ArtifactRef, Digest32, EvaluationId, Timestamp}; |
| 10 | use p256::ecdsa::SigningKey; |
| 11 | use serde_json::json; |
| 12 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 13 | use std::sync::Arc; |
| 14 | |
| 15 | fn sample_state() -> serde_json::Value { |
| 16 | json!({ |
| 17 | "diff": "fn add(a: i32, b: i32) -> i32 { a + b }", |
| 18 | "author": "contributor", |
| 19 | "files": ["src/lib.rs"], |
| 20 | }) |
| 21 | } |
| 22 | |
| 23 | fn sample_probes() -> ProbeSet { |
| 24 | ProbeSet::new() |
| 25 | .with( |
| 26 | "telemetry", |
| 27 | Probe::Noul(Noul::new( |
| 28 | "Does this patch introduce covert network telemetry?", |
| 29 | )), |
| 30 | ) |
| 31 | .with( |
| 32 | "quality", |
| 33 | Probe::Score(Score::new( |
| 34 | "Rate the architectural quality.", |
| 35 | ["unacceptable", "needs_rework", "acceptable", "exemplary"], |
| 36 | )), |
| 37 | ) |
| 38 | .with( |
| 39 | "severity", |
| 40 | Probe::Choice(Choice::new( |
| 41 | "Classify the finding.", |
| 42 | [ |
| 43 | ChoiceOption::new("clean").with_description("No issue"), |
| 44 | ChoiceOption::new("advisory").with_description("Minor note"), |
| 45 | ChoiceOption::new("critical").with_description("Blocks merge"), |
| 46 | ], |
| 47 | )), |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | #[tokio::test] |
| 52 | async fn test_deterministic_backend_is_reproducible() { |
| 53 | let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); |
| 54 | let probes = sample_probes(); |
| 55 | |
| 56 | let first = engine.evaluate(&sample_state(), &probes).await.unwrap(); |
| 57 | let second = engine.evaluate(&sample_state(), &probes).await.unwrap(); |
| 58 | |
| 59 | assert_eq!(first.answers, second.answers); |
| 60 | assert_eq!(first.model, "deterministic-reference-oracle"); |
| 61 | assert_eq!(first.answers.len(), 3); |
| 62 | } |
| 63 | |
| 64 | #[tokio::test] |
| 65 | async fn test_deterministic_backend_varies_with_state() { |
| 66 | let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); |
| 67 | let probes = sample_probes(); |
| 68 | |
| 69 | let a = engine |
| 70 | .evaluate(&json!({"diff": "alpha"}), &probes) |
| 71 | .await |
| 72 | .unwrap(); |
| 73 | let b = engine |
| 74 | .evaluate(&json!({"diff": "omega"}), &probes) |
| 75 | .await |
| 76 | .unwrap(); |
| 77 | |
| 78 | let a_noul = a.noul("telemetry").unwrap().noul; |
| 79 | let b_noul = b.noul("telemetry").unwrap().noul; |
| 80 | assert!((a_noul - b_noul).abs() > 1.0e-6); |
| 81 | } |
| 82 | |
| 83 | #[tokio::test] |
| 84 | async fn test_answer_ranges_and_distributions() { |
| 85 | let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); |
| 86 | let probes = sample_probes(); |
| 87 | let response = engine.evaluate(&sample_state(), &probes).await.unwrap(); |
| 88 | |
| 89 | let noul = response.noul("telemetry").unwrap().noul; |
| 90 | assert!((0.0..=1.0).contains(&noul)); |
| 91 | |
| 92 | let score = response.score("quality").unwrap(); |
| 93 | let sum: f64 = score.probabilities.values().sum(); |
| 94 | assert!((sum - 1.0).abs() < 1.0e-9); |
| 95 | assert_eq!(score.legend.len(), 4); |
| 96 | let weighted: f64 = score |
| 97 | .probabilities |
| 98 | .iter() |
| 99 | .map(|(level, probability)| *level as f64 * probability) |
| 100 | .sum(); |
| 101 | assert!((weighted - score.score).abs() < 1.0e-9); |
| 102 | assert!((0.0..=1.0).contains(&score.confidence)); |
| 103 | |
| 104 | let choice = response.choice("severity").unwrap(); |
| 105 | let best = choice |
| 106 | .probabilities |
| 107 | .iter() |
| 108 | .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) |
| 109 | .map(|(id, _)| id.clone()) |
| 110 | .unwrap(); |
| 111 | assert_eq!(choice.choice, best); |
| 112 | } |
| 113 | |
| 114 | #[tokio::test] |
| 115 | async fn test_probe_evaluator_gates_pass() { |
| 116 | let backend = DeterministicReferenceBackend::new(); |
| 117 | let config = ProbeEvaluatorConfig::new(); |
| 118 | let evaluator = ProbeEvaluator::new(ProbeEngine::new(backend), sample_probes(), config); |
| 119 | |
| 120 | let subject = ArtifactRef { |
| 121 | artifact_id: uuid::Uuid::new_v4(), |
| 122 | digest: Digest32([1u8; 32]), |
| 123 | media_type: "application/rust".to_string(), |
| 124 | byte_size: 4096, |
| 125 | }; |
| 126 | let plan = build_plan(&evaluator, subject.clone()); |
| 127 | |
| 128 | let outcome = evaluator.evaluate(&plan, &subject).await.unwrap(); |
| 129 | assert_eq!(outcome.status, EvaluatorStatus::Passed); |
| 130 | assert!(outcome.findings.is_empty()); |
| 131 | assert_eq!(outcome.measurements.len(), 3); |
| 132 | assert_ne!(outcome.execution_digest, Digest32([0u8; 32])); |
| 133 | } |
| 134 | |
| 135 | #[tokio::test] |
| 136 | async fn test_probe_evaluator_gate_fails_closed() { |
| 137 | let backend = DeterministicReferenceBackend::new(); |
| 138 | let config = ProbeEvaluatorConfig::new() |
| 139 | .with_gate(ProbeGate::noul("telemetry", 0.999999)) |
| 140 | .with_gate(ProbeGate::score("quality", 3.999999)) |
| 141 | .with_gate(ProbeGate::choice("severity", ["clean"])); |
| 142 | let evaluator = ProbeEvaluator::new(ProbeEngine::new(backend), sample_probes(), config); |
| 143 | |
| 144 | let subject = ArtifactRef { |
| 145 | artifact_id: uuid::Uuid::new_v4(), |
| 146 | digest: Digest32([2u8; 32]), |
| 147 | media_type: "application/rust".to_string(), |
| 148 | byte_size: 2048, |
| 149 | }; |
| 150 | let plan = build_plan(&evaluator, subject.clone()); |
| 151 | |
| 152 | let outcome = evaluator.evaluate(&plan, &subject).await.unwrap(); |
| 153 | assert_eq!(outcome.status, EvaluatorStatus::Failed); |
| 154 | assert!(outcome |
| 155 | .findings |
| 156 | .iter() |
| 157 | .any(|f| f.rule_id == "probe:noul:telemetry")); |
| 158 | assert!(outcome |
| 159 | .findings |
| 160 | .iter() |
| 161 | .any(|f| f.rule_id == "probe:score:quality")); |
| 162 | } |
| 163 | |
| 164 | #[tokio::test] |
| 165 | async fn test_probe_evaluator_plugs_into_canary_harness() { |
| 166 | let backend = DeterministicReferenceBackend::new(); |
| 167 | let evaluator = ProbeEvaluator::new( |
| 168 | ProbeEngine::new(backend), |
| 169 | sample_probes(), |
| 170 | ProbeEvaluatorConfig::new(), |
| 171 | ); |
| 172 | let descriptor = evaluator.descriptor(); |
| 173 | |
| 174 | let signing_key = SigningKey::from_slice(&[42u8; 32]).unwrap(); |
| 175 | let signer = Arc::new(SoftwareP256Signer::new(signing_key)); |
| 176 | let verifier = VerifierIdentity { |
| 177 | principal_id: "canary-daemon".to_string(), |
| 178 | key_id: signer.key_fingerprint(), |
| 179 | trust_epoch: 1, |
| 180 | trusted_build_digest: Digest32([10u8; 32]), |
| 181 | policy_bundle_digest: Digest32([11u8; 32]), |
| 182 | }; |
| 183 | let harness = CanaryRollbackHarness::new(verifier, signer); |
| 184 | |
| 185 | let subject = ArtifactRef { |
| 186 | artifact_id: uuid::Uuid::new_v4(), |
| 187 | digest: Digest32([12u8; 32]), |
| 188 | media_type: "application/rust".to_string(), |
| 189 | byte_size: 8192, |
| 190 | }; |
| 191 | let mut plan = EvaluationPlan { |
| 192 | evaluation_id: EvaluationId(uuid::Uuid::new_v4()), |
| 193 | subject: subject.clone(), |
| 194 | profile: "canary".to_string(), |
| 195 | evaluators: vec![descriptor], |
| 196 | baseline: None, |
| 197 | sandbox_profile: "default".to_string(), |
| 198 | policy_digest: Digest32([13u8; 32]), |
| 199 | evaluator_manifest_digest: Digest32([14u8; 32]), |
| 200 | plan_digest: Digest32([0u8; 32]), |
| 201 | }; |
| 202 | plan.plan_digest = plan.compute_plan_digest(); |
| 203 | |
| 204 | let rollback = Arc::new(AtomicBool::new(false)); |
| 205 | let rollback_flag = rollback.clone(); |
| 206 | let evaluators: Vec<Box<dyn Evaluator>> = vec![Box::new(evaluator)]; |
| 207 | |
| 208 | let (receipt, outcomes) = harness |
| 209 | .evaluate_and_enforce( |
| 210 | &plan, |
| 211 | &subject, |
| 212 | &evaluators, |
| 213 | Timestamp(1000), |
| 214 | || async move { |
| 215 | rollback_flag.store(true, Ordering::SeqCst); |
| 216 | Ok(()) |
| 217 | }, |
| 218 | ) |
| 219 | .await |
| 220 | .unwrap(); |
| 221 | |
| 222 | assert_eq!(receipt.receipt.verdict, Verdict::Pass); |
| 223 | assert_eq!(outcomes[0].status, EvaluatorStatus::Passed); |
| 224 | assert!(!rollback.load(Ordering::SeqCst)); |
| 225 | } |
| 226 | |
| 227 | #[tokio::test] |
| 228 | async fn test_probe_evaluator_triggers_rollback_on_gate_failure() { |
| 229 | let backend = DeterministicReferenceBackend::new(); |
| 230 | let evaluator = ProbeEvaluator::new( |
| 231 | ProbeEngine::new(backend), |
| 232 | sample_probes(), |
| 233 | ProbeEvaluatorConfig::new().with_gate(ProbeGate::noul("telemetry", 0.999999)), |
| 234 | ); |
| 235 | let descriptor = evaluator.descriptor(); |
| 236 | |
| 237 | let signing_key = SigningKey::from_slice(&[7u8; 32]).unwrap(); |
| 238 | let signer = Arc::new(SoftwareP256Signer::new(signing_key)); |
| 239 | let verifier = VerifierIdentity { |
| 240 | principal_id: "canary-daemon".to_string(), |
| 241 | key_id: signer.key_fingerprint(), |
| 242 | trust_epoch: 1, |
| 243 | trusted_build_digest: Digest32([20u8; 32]), |
| 244 | policy_bundle_digest: Digest32([21u8; 32]), |
| 245 | }; |
| 246 | let harness = CanaryRollbackHarness::new(verifier, signer); |
| 247 | |
| 248 | let subject = ArtifactRef { |
| 249 | artifact_id: uuid::Uuid::new_v4(), |
| 250 | digest: Digest32([22u8; 32]), |
| 251 | media_type: "application/rust".to_string(), |
| 252 | byte_size: 512, |
| 253 | }; |
| 254 | let mut plan = EvaluationPlan { |
| 255 | evaluation_id: EvaluationId(uuid::Uuid::new_v4()), |
| 256 | subject: subject.clone(), |
| 257 | profile: "canary".to_string(), |
| 258 | evaluators: vec![descriptor], |
| 259 | baseline: None, |
| 260 | sandbox_profile: "default".to_string(), |
| 261 | policy_digest: Digest32([23u8; 32]), |
| 262 | evaluator_manifest_digest: Digest32([24u8; 32]), |
| 263 | plan_digest: Digest32([0u8; 32]), |
| 264 | }; |
| 265 | plan.plan_digest = plan.compute_plan_digest(); |
| 266 | |
| 267 | let rollback = Arc::new(AtomicBool::new(false)); |
| 268 | let rollback_flag = rollback.clone(); |
| 269 | let evaluators: Vec<Box<dyn Evaluator>> = vec![Box::new(evaluator)]; |
| 270 | |
| 271 | let (receipt, outcomes) = harness |
| 272 | .evaluate_and_enforce( |
| 273 | &plan, |
| 274 | &subject, |
| 275 | &evaluators, |
| 276 | Timestamp(2000), |
| 277 | || async move { |
| 278 | rollback_flag.store(true, Ordering::SeqCst); |
| 279 | Ok(()) |
| 280 | }, |
| 281 | ) |
| 282 | .await |
| 283 | .unwrap(); |
| 284 | |
| 285 | assert_eq!(receipt.receipt.verdict, Verdict::Fail); |
| 286 | assert_eq!(outcomes[0].status, EvaluatorStatus::Failed); |
| 287 | assert!(rollback.load(Ordering::SeqCst)); |
| 288 | } |
| 289 | |
| 290 | #[tokio::test] |
| 291 | async fn test_http_backend_wire_lifecycle() { |
| 292 | let body = json!({ |
| 293 | "model": "atlas-lightning-omni", |
| 294 | "answers": [ |
| 295 | ["telemetry", {"type": "noul", "noul": 0.02}], |
| 296 | ["quality", { |
| 297 | "type": "score", |
| 298 | "score": 3.1, |
| 299 | "confidence": 0.9, |
| 300 | "legend": {"0": "unacceptable", "1": "needs_rework", "2": "acceptable", "3": "exemplary"}, |
| 301 | "probabilities": {"0": 0.0, "1": 0.02, "2": 0.08, "3": 0.9} |
| 302 | }] |
| 303 | ] |
| 304 | }) |
| 305 | .to_string(); |
| 306 | |
| 307 | let endpoint = spawn_mock_probe_server(body).await; |
| 308 | let backend = HttpProbeBackend::with_endpoint(endpoint, "atlas-lightning-omni"); |
| 309 | let probes = ProbeSet::new() |
| 310 | .with("telemetry", Probe::Noul(Noul::new("telemetry?"))) |
| 311 | .with( |
| 312 | "quality", |
| 313 | Probe::Score(Score::new("quality?", ["a", "b", "c", "d"])), |
| 314 | ); |
| 315 | |
| 316 | let response = backend.evaluate(&sample_state(), &probes).await.unwrap(); |
| 317 | assert_eq!(response.model, "atlas-lightning-omni"); |
| 318 | assert!((response.noul("telemetry").unwrap().noul - 0.02).abs() < 1.0e-9); |
| 319 | assert!((response.score("quality").unwrap().score - 3.1).abs() < 1.0e-9); |
| 320 | } |
| 321 | |
| 322 | fn build_plan<E: Evaluator>(evaluator: &E, subject: ArtifactRef) -> EvaluationPlan { |
| 323 | let mut plan = EvaluationPlan { |
| 324 | evaluation_id: EvaluationId(uuid::Uuid::new_v4()), |
| 325 | subject, |
| 326 | profile: "sovereign-audit".to_string(), |
| 327 | evaluators: vec![evaluator.descriptor()], |
| 328 | baseline: None, |
| 329 | sandbox_profile: "isolated".to_string(), |
| 330 | policy_digest: Digest32([2u8; 32]), |
| 331 | evaluator_manifest_digest: Digest32([3u8; 32]), |
| 332 | plan_digest: Digest32([0u8; 32]), |
| 333 | }; |
| 334 | plan.plan_digest = plan.compute_plan_digest(); |
| 335 | plan |
| 336 | } |
| 337 | |
| 338 | async fn spawn_mock_probe_server(body: String) -> String { |
| 339 | use axum::{routing::post, Router}; |
| 340 | |
| 341 | let app = Router::new().route( |
| 342 | "/v1/probe", |
| 343 | post(move || { |
| 344 | let body = body.clone(); |
| 345 | async move { body } |
| 346 | }), |
| 347 | ); |
| 348 | |
| 349 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 350 | let addr = listener.local_addr().unwrap(); |
| 351 | tokio::spawn(async move { |
| 352 | let _ = axum::serve(listener, app).await; |
| 353 | }); |
| 354 | format!("http://{}", addr) |
| 355 | } |