1use crate::{verification::*, GpuCliffordAlgebra};
8use std::time::{Duration, Instant};
9use thiserror::Error;
10
11#[derive(Error, Debug)]
12pub enum AdaptiveVerificationError {
13 #[error("Platform detection failed: {0}")]
14 PlatformDetection(String),
15
16 #[error("GPU verification failed: {0}")]
17 GpuVerification(#[from] GpuVerificationError),
18
19 #[error("No suitable verification strategy available")]
20 NoSuitableStrategy,
21
22 #[error("Performance constraint violation: {constraint}")]
23 PerformanceConstraint { constraint: String },
24}
25
26#[derive(Debug, Clone, PartialEq)]
28pub enum VerificationPlatform {
29 NativeCpu { features: CpuFeatures },
31 Gpu {
33 backend: GpuBackend,
34 memory_mb: u64,
35 compute_units: u32,
36 },
37 Wasm { env: WasmEnvironment },
39}
40
41#[derive(Debug, Clone, PartialEq)]
42pub struct CpuFeatures {
43 pub supports_simd: bool,
44 pub core_count: usize,
45 pub cache_size_kb: u64,
46}
47
48#[derive(Debug, Clone, PartialEq)]
49pub enum GpuBackend {
50 Vulkan,
51 Metal,
52 Dx12,
53 OpenGL,
54 WebGpu,
55}
56
57#[derive(Debug, Clone, PartialEq)]
58pub enum WasmEnvironment {
59 Browser { engine: String },
60 NodeJs { version: String },
61 Standalone,
62}
63
64#[derive(Debug, Clone, PartialEq)]
66pub enum AdaptiveVerificationLevel {
67 Maximum,
69 High,
71 Balanced,
73 Minimal,
75 Debug,
77}
78
79pub struct AdaptiveVerifier {
81 platform: VerificationPlatform,
82 verification_level: AdaptiveVerificationLevel,
83 performance_budget: Duration,
84 boundary_verifier: Option<GpuBoundaryVerifier>,
85 gpu_instance: Option<GpuCliffordAlgebra>,
86}
87
88impl AdaptiveVerifier {
89 pub async fn new() -> Result<Self, AdaptiveVerificationError> {
91 let platform = Self::detect_platform().await?;
92 let verification_level = Self::determine_verification_level(&platform);
93 let performance_budget = Self::determine_performance_budget(&platform);
94
95 let (boundary_verifier, gpu_instance) = match &platform {
96 VerificationPlatform::Gpu { .. } => {
97 let config = Self::create_gpu_verification_config(&platform, &verification_level);
98 let verifier = GpuBoundaryVerifier::new(config);
99 let gpu = GpuCliffordAlgebra::new::<3, 0, 0>().await.ok();
100 (Some(verifier), gpu)
101 }
102 _ => (None, None),
103 };
104
105 Ok(Self {
106 platform,
107 verification_level,
108 performance_budget,
109 boundary_verifier,
110 gpu_instance,
111 })
112 }
113
114 pub async fn with_config(
116 level: AdaptiveVerificationLevel,
117 budget: Duration,
118 ) -> Result<Self, AdaptiveVerificationError> {
119 let platform = Self::detect_platform().await?;
120
121 let (boundary_verifier, gpu_instance) = match &platform {
122 VerificationPlatform::Gpu { .. } => {
123 let config = Self::create_gpu_verification_config(&platform, &level);
124 let verifier = GpuBoundaryVerifier::new(config);
125 let gpu = GpuCliffordAlgebra::new::<3, 0, 0>().await.ok();
126 (Some(verifier), gpu)
127 }
128 _ => (None, None),
129 };
130
131 Ok(Self {
132 platform,
133 verification_level: level,
134 performance_budget: budget,
135 boundary_verifier,
136 gpu_instance,
137 })
138 }
139
140 pub async fn verified_geometric_product<const P: usize, const Q: usize, const R: usize>(
142 &mut self,
143 a: &VerifiedMultivector<P, Q, R>,
144 b: &VerifiedMultivector<P, Q, R>,
145 ) -> Result<VerifiedMultivector<P, Q, R>, AdaptiveVerificationError> {
146 let start_time = Instant::now();
147
148 let result = match &self.platform {
149 VerificationPlatform::NativeCpu { .. } => {
150 self.cpu_verification(a, b).await?
152 }
153 VerificationPlatform::Gpu { .. } => {
154 self.cpu_verification(a, b).await?
156 }
157 VerificationPlatform::Wasm { .. } => {
158 self.wasm_runtime_verification(a, b).await?
160 }
161 };
162
163 let elapsed = start_time.elapsed();
164 if elapsed > self.performance_budget {
165 return Err(AdaptiveVerificationError::PerformanceConstraint {
166 constraint: format!(
167 "Operation exceeded budget: {:?} > {:?}",
168 elapsed, self.performance_budget
169 ),
170 });
171 }
172
173 Ok(result)
174 }
175
176 pub async fn verified_batch_geometric_product<
178 const P: usize,
179 const Q: usize,
180 const R: usize,
181 >(
182 &mut self,
183 a_batch: &[VerifiedMultivector<P, Q, R>],
184 b_batch: &[VerifiedMultivector<P, Q, R>],
185 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
186 if a_batch.is_empty() {
187 return Ok(Vec::new());
188 }
189
190 match &self.platform {
191 VerificationPlatform::NativeCpu { .. } => {
192 self.cpu_batch_verification(a_batch, b_batch).await
194 }
195 VerificationPlatform::Gpu { .. } => {
196 self.gpu_batch_verification(a_batch, b_batch).await
198 }
199 VerificationPlatform::Wasm { .. } => {
200 self.wasm_batch_verification(a_batch, b_batch).await
202 }
203 }
204 }
205
206 pub fn platform(&self) -> &VerificationPlatform {
208 &self.platform
209 }
210
211 pub fn verification_level(&self) -> &AdaptiveVerificationLevel {
213 &self.verification_level
214 }
215
216 pub fn performance_budget(&self) -> Duration {
218 self.performance_budget
219 }
220
221 pub fn should_use_gpu(&self, batch_size: usize) -> bool {
223 match &self.platform {
224 VerificationPlatform::Gpu {
225 compute_units,
226 memory_mb,
227 ..
228 } => {
229 let min_batch_size = match &self.verification_level {
231 AdaptiveVerificationLevel::Maximum => 500,
232 AdaptiveVerificationLevel::High => 200,
233 AdaptiveVerificationLevel::Balanced => 100,
234 AdaptiveVerificationLevel::Minimal => 50,
235 AdaptiveVerificationLevel::Debug => 1000, };
237
238 let capability_factor = (*compute_units as f64 / 16.0).clamp(0.5, 4.0);
240 let memory_factor = (*memory_mb as f64 / 1024.0).clamp(0.5, 2.0);
241 let adjusted_threshold =
242 (min_batch_size as f64 / (capability_factor * memory_factor)) as usize;
243
244 batch_size >= adjusted_threshold
245 }
246 _ => false,
247 }
248 }
249
250 pub fn set_verification_level(&mut self, level: AdaptiveVerificationLevel) {
252 if let Some(ref mut verifier) = self.boundary_verifier {
254 let new_config = Self::create_gpu_verification_config(&self.platform, &level);
255 *verifier = GpuBoundaryVerifier::new(new_config);
256 }
257
258 self.verification_level = level;
259 }
260
261 async fn detect_platform() -> Result<VerificationPlatform, AdaptiveVerificationError> {
265 let gpu_available = {
267 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
269 pollster::block_on(async { GpuCliffordAlgebra::new::<3, 0, 0>().await.is_ok() })
271 }));
272
273 panic_result.unwrap_or_default()
275 };
276
277 if gpu_available {
278 let backend = Self::detect_gpu_backend();
279 let (memory_mb, compute_units) = Self::estimate_gpu_capabilities().await;
280
281 return Ok(VerificationPlatform::Gpu {
282 backend,
283 memory_mb,
284 compute_units,
285 });
286 }
287
288 if cfg!(target_arch = "wasm32") {
290 let env = Self::detect_wasm_environment();
291 return Ok(VerificationPlatform::Wasm { env });
292 }
293
294 let features = Self::detect_cpu_features();
296 Ok(VerificationPlatform::NativeCpu { features })
297 }
298
299 fn detect_gpu_backend() -> GpuBackend {
301 if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
303 GpuBackend::Metal
304 } else if cfg!(target_os = "windows") {
305 GpuBackend::Dx12
306 } else if cfg!(target_arch = "wasm32") {
307 GpuBackend::WebGpu
308 } else {
309 GpuBackend::Vulkan
310 }
311 }
312
313 async fn estimate_gpu_capabilities() -> (u64, u32) {
315 (1024, 16) }
319
320 fn detect_wasm_environment() -> WasmEnvironment {
322 WasmEnvironment::Browser {
324 engine: "Unknown".to_string(),
325 }
326 }
327
328 fn detect_cpu_features() -> CpuFeatures {
330 CpuFeatures {
331 supports_simd: true, core_count: std::thread::available_parallelism()
333 .map(|n| n.get())
334 .unwrap_or(4),
335 cache_size_kb: 8192, }
337 }
338
339 fn determine_verification_level(platform: &VerificationPlatform) -> AdaptiveVerificationLevel {
341 match platform {
342 VerificationPlatform::NativeCpu { features } => {
343 if features.core_count >= 8 {
344 AdaptiveVerificationLevel::High
345 } else {
346 AdaptiveVerificationLevel::Balanced
347 }
348 }
349 VerificationPlatform::Gpu { compute_units, .. } => {
350 if *compute_units >= 32 {
351 AdaptiveVerificationLevel::Balanced
352 } else {
353 AdaptiveVerificationLevel::Minimal
354 }
355 }
356 VerificationPlatform::Wasm { .. } => {
357 AdaptiveVerificationLevel::Minimal
359 }
360 }
361 }
362
363 fn determine_performance_budget(platform: &VerificationPlatform) -> Duration {
365 match platform {
366 VerificationPlatform::NativeCpu { .. } => Duration::from_millis(50),
367 VerificationPlatform::Gpu { .. } => Duration::from_millis(20),
368 VerificationPlatform::Wasm { .. } => Duration::from_millis(100),
369 }
370 }
371
372 fn create_gpu_verification_config(
374 platform: &VerificationPlatform,
375 level: &AdaptiveVerificationLevel,
376 ) -> VerificationConfig {
377 let strategy = match level {
378 AdaptiveVerificationLevel::Maximum => VerificationStrategy::Strict,
379 AdaptiveVerificationLevel::High => {
380 VerificationStrategy::Statistical { sample_rate: 0.2 }
381 }
382 AdaptiveVerificationLevel::Balanced => {
383 VerificationStrategy::Statistical { sample_rate: 0.1 }
384 }
385 AdaptiveVerificationLevel::Minimal => VerificationStrategy::Boundary,
386 AdaptiveVerificationLevel::Debug => VerificationStrategy::Strict,
387 };
388
389 let budget = Self::determine_performance_budget(platform);
390
391 VerificationConfig {
392 strategy,
393 performance_budget: budget,
394 tolerance: 1e-12,
395 enable_invariant_checking: !matches!(level, AdaptiveVerificationLevel::Minimal),
396 }
397 }
398
399 async fn cpu_verification<const P: usize, const Q: usize, const R: usize>(
401 &self,
402 a: &VerifiedMultivector<P, Q, R>,
403 b: &VerifiedMultivector<P, Q, R>,
404 ) -> Result<VerifiedMultivector<P, Q, R>, AdaptiveVerificationError> {
405 let result = a.inner().geometric_product(b.inner());
407 let verified_result = VerifiedMultivector::new(result);
408
409 match self.verification_level {
411 AdaptiveVerificationLevel::Maximum | AdaptiveVerificationLevel::Debug => {
412 verified_result.verify_invariants()?;
413 self.verify_geometric_product_properties(a, b, &verified_result)?;
415 }
416 AdaptiveVerificationLevel::High => {
417 verified_result.verify_invariants()?;
418 }
419 _ => {
420 }
422 }
423
424 Ok(verified_result)
425 }
426
427 async fn cpu_batch_verification<const P: usize, const Q: usize, const R: usize>(
429 &self,
430 a_batch: &[VerifiedMultivector<P, Q, R>],
431 b_batch: &[VerifiedMultivector<P, Q, R>],
432 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
433 let mut results = Vec::with_capacity(a_batch.len());
434
435 for (a, b) in a_batch.iter().zip(b_batch.iter()) {
436 let result = self.cpu_verification(a, b).await?;
437 results.push(result);
438 }
439
440 Ok(results)
441 }
442
443 async fn gpu_batch_verification<const P: usize, const Q: usize, const R: usize>(
445 &mut self,
446 a_batch: &[VerifiedMultivector<P, Q, R>],
447 b_batch: &[VerifiedMultivector<P, Q, R>],
448 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
449 if !self.should_use_gpu(a_batch.len()) {
450 return self.cpu_batch_verification(a_batch, b_batch).await;
451 }
452
453 if let (Some(ref mut verifier), Some(ref gpu)) =
454 (&mut self.boundary_verifier, &self.gpu_instance)
455 {
456 verifier
457 .verified_batch_geometric_product(gpu, a_batch, b_batch)
458 .await
459 .map_err(AdaptiveVerificationError::GpuVerification)
460 } else {
461 self.cpu_batch_verification(a_batch, b_batch).await
463 }
464 }
465
466 async fn wasm_runtime_verification<const P: usize, const Q: usize, const R: usize>(
468 &self,
469 a: &VerifiedMultivector<P, Q, R>,
470 b: &VerifiedMultivector<P, Q, R>,
471 ) -> Result<VerifiedMultivector<P, Q, R>, AdaptiveVerificationError> {
472 if VerifiedMultivector::<P, Q, R>::signature() != (P, Q, R) {
474 return Err(AdaptiveVerificationError::GpuVerification(
475 GpuVerificationError::SignatureMismatch {
476 expected: (P, Q, R),
477 actual: VerifiedMultivector::<P, Q, R>::signature(),
478 },
479 ));
480 }
481
482 let result = a.inner().geometric_product(b.inner());
484 let verified_result = VerifiedMultivector::new(result);
485
486 if !verified_result.inner().magnitude().is_finite() {
488 return Err(AdaptiveVerificationError::GpuVerification(
489 GpuVerificationError::InvariantViolation {
490 invariant: "Result magnitude must be finite".to_string(),
491 },
492 ));
493 }
494
495 Ok(verified_result)
496 }
497
498 async fn wasm_batch_verification<const P: usize, const Q: usize, const R: usize>(
500 &self,
501 a_batch: &[VerifiedMultivector<P, Q, R>],
502 b_batch: &[VerifiedMultivector<P, Q, R>],
503 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
504 let mut results = Vec::with_capacity(a_batch.len());
505
506 for (a, b) in a_batch.iter().zip(b_batch.iter()) {
507 let result = self.wasm_runtime_verification(a, b).await?;
508 results.push(result);
509 }
510
511 Ok(results)
512 }
513
514 fn verify_geometric_product_properties<const P: usize, const Q: usize, const R: usize>(
516 &self,
517 a: &VerifiedMultivector<P, Q, R>,
518 b: &VerifiedMultivector<P, Q, R>,
519 result: &VerifiedMultivector<P, Q, R>,
520 ) -> Result<(), AdaptiveVerificationError> {
521 let result_mag = result.inner().magnitude();
523 let a_mag = a.inner().magnitude();
524 let b_mag = b.inner().magnitude();
525
526 if result_mag > a_mag * b_mag + 1e-12 {
527 return Err(AdaptiveVerificationError::GpuVerification(
528 GpuVerificationError::InvariantViolation {
529 invariant: format!(
530 "Magnitude inequality violated: {} > {} * {}",
531 result_mag, a_mag, b_mag
532 ),
533 },
534 ));
535 }
536
537 Ok(())
538 }
539}
540
541pub trait PlatformCapabilities {
543 fn max_batch_size(&self) -> usize;
545
546 fn optimal_strategy(&self, workload_size: usize) -> VerificationStrategy;
548
549 fn supports_concurrent_verification(&self) -> bool;
551
552 fn performance_characteristics(&self) -> PlatformPerformanceProfile;
554}
555
556#[derive(Debug, Clone)]
557pub struct PlatformPerformanceProfile {
558 pub verification_overhead_percent: f64,
559 pub memory_bandwidth_gbps: f64,
560 pub compute_throughput_gflops: f64,
561 pub latency_microseconds: f64,
562}
563
564impl PlatformCapabilities for VerificationPlatform {
565 fn max_batch_size(&self) -> usize {
566 match self {
567 VerificationPlatform::NativeCpu { features } => features.core_count * 1000,
568 VerificationPlatform::Gpu { memory_mb, .. } => {
569 (*memory_mb as usize * 1024 * 1024) / (8 * 64) }
571 VerificationPlatform::Wasm { .. } => {
572 10000 }
574 }
575 }
576
577 fn optimal_strategy(&self, workload_size: usize) -> VerificationStrategy {
578 match self {
579 VerificationPlatform::NativeCpu { .. } => {
580 if workload_size < 100 {
581 VerificationStrategy::Strict
582 } else {
583 VerificationStrategy::Statistical { sample_rate: 0.1 }
584 }
585 }
586 VerificationPlatform::Gpu { .. } => {
587 if workload_size < 50 {
588 VerificationStrategy::Boundary
589 } else {
590 VerificationStrategy::Statistical { sample_rate: 0.05 }
591 }
592 }
593 VerificationPlatform::Wasm { .. } => {
594 VerificationStrategy::Statistical { sample_rate: 0.02 }
595 }
596 }
597 }
598
599 fn supports_concurrent_verification(&self) -> bool {
600 match self {
601 VerificationPlatform::NativeCpu { features } => features.core_count > 1,
602 VerificationPlatform::Gpu { .. } => true,
603 VerificationPlatform::Wasm { .. } => false, }
605 }
606
607 fn performance_characteristics(&self) -> PlatformPerformanceProfile {
608 match self {
609 VerificationPlatform::NativeCpu { features } => PlatformPerformanceProfile {
610 verification_overhead_percent: 5.0,
611 memory_bandwidth_gbps: 50.0,
612 compute_throughput_gflops: features.core_count as f64 * 100.0,
613 latency_microseconds: 1.0,
614 },
615 VerificationPlatform::Gpu { compute_units, .. } => PlatformPerformanceProfile {
616 verification_overhead_percent: 15.0,
617 memory_bandwidth_gbps: 200.0,
618 compute_throughput_gflops: *compute_units as f64 * 50.0,
619 latency_microseconds: 100.0,
620 },
621 VerificationPlatform::Wasm { .. } => PlatformPerformanceProfile {
622 verification_overhead_percent: 25.0,
623 memory_bandwidth_gbps: 10.0,
624 compute_throughput_gflops: 10.0,
625 latency_microseconds: 1000.0,
626 },
627 }
628 }
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 #[test]
636 fn test_cpu_features_detection() {
637 let features = AdaptiveVerifier::detect_cpu_features();
638 assert!(features.core_count > 0);
639 assert!(features.cache_size_kb > 0);
640 }
641
642 #[test]
643 fn test_verification_level_determination() {
644 let cpu_platform = VerificationPlatform::NativeCpu {
645 features: CpuFeatures {
646 supports_simd: true,
647 core_count: 8,
648 cache_size_kb: 8192,
649 },
650 };
651
652 let level = AdaptiveVerifier::determine_verification_level(&cpu_platform);
653 assert_eq!(level, AdaptiveVerificationLevel::High);
654
655 let gpu_platform = VerificationPlatform::Gpu {
656 backend: GpuBackend::Vulkan,
657 memory_mb: 2048,
658 compute_units: 16,
659 };
660
661 let level = AdaptiveVerifier::determine_verification_level(&gpu_platform);
662 assert_eq!(level, AdaptiveVerificationLevel::Minimal);
663 }
664
665 #[test]
666 fn test_platform_capabilities() {
667 let platform = VerificationPlatform::NativeCpu {
668 features: CpuFeatures {
669 supports_simd: true,
670 core_count: 4,
671 cache_size_kb: 8192,
672 },
673 };
674
675 assert_eq!(platform.max_batch_size(), 4000);
676 assert!(platform.supports_concurrent_verification());
677
678 let profile = platform.performance_characteristics();
679 assert_eq!(profile.verification_overhead_percent, 5.0);
680 assert_eq!(profile.compute_throughput_gflops, 400.0);
681 }
682
683 #[tokio::test]
684 async fn test_adaptive_verifier_creation() {
685 match AdaptiveVerifier::new().await {
687 Ok(verifier) => {
688 assert!(verifier.performance_budget() > Duration::ZERO);
689 }
690 Err(AdaptiveVerificationError::PlatformDetection(_)) => {
691 }
693 Err(e) => panic!("Unexpected error: {:?}", e),
694 }
695 }
696
697 #[tokio::test]
698 async fn test_verification_with_config() {
699 match AdaptiveVerifier::with_config(
701 AdaptiveVerificationLevel::Minimal,
702 Duration::from_millis(5),
703 )
704 .await
705 {
706 Ok(verifier) => {
707 assert_eq!(
709 *verifier.verification_level(),
710 AdaptiveVerificationLevel::Minimal
711 );
712 assert_eq!(verifier.performance_budget(), Duration::from_millis(5));
713
714 match verifier.platform() {
716 VerificationPlatform::Gpu { .. } => {
717 println!("✅ GPU verification platform detected");
718 }
719 VerificationPlatform::NativeCpu { .. } => {
720 println!("✅ CPU verification platform detected (GPU not available)");
721 }
722 VerificationPlatform::Wasm { .. } => {
723 println!("✅ WASM verification platform detected");
724 }
725 }
726 }
727 Err(e) => {
728 panic!("Adaptive verifier should not fail, but got: {:?}", e);
730 }
731 }
732 }
733}