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_platform = {
267 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
269 pollster::block_on(async {
271 if GpuCliffordAlgebra::new::<3, 0, 0>().await.is_ok() {
273 let backend = Self::detect_gpu_backend();
274 let (memory_mb, compute_units) = Self::estimate_gpu_capabilities().await;
275 Some(VerificationPlatform::Gpu {
276 backend,
277 memory_mb,
278 compute_units,
279 })
280 } else {
281 None
282 }
283 })
284 }));
285
286 panic_result.unwrap_or(None)
288 };
289
290 if let Some(platform) = gpu_platform {
291 return Ok(platform);
292 }
293
294 if cfg!(target_arch = "wasm32") {
296 let env = Self::detect_wasm_environment();
297 return Ok(VerificationPlatform::Wasm { env });
298 }
299
300 let features = Self::detect_cpu_features();
302 Ok(VerificationPlatform::NativeCpu { features })
303 }
304
305 fn detect_gpu_backend() -> GpuBackend {
307 if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
309 GpuBackend::Metal
310 } else if cfg!(target_os = "windows") {
311 GpuBackend::Dx12
312 } else if cfg!(target_arch = "wasm32") {
313 GpuBackend::WebGpu
314 } else {
315 GpuBackend::Vulkan
316 }
317 }
318
319 async fn estimate_gpu_capabilities() -> (u64, u32) {
321 (1024, 16) }
325
326 fn detect_wasm_environment() -> WasmEnvironment {
328 WasmEnvironment::Browser {
330 engine: "Unknown".to_string(),
331 }
332 }
333
334 fn detect_cpu_features() -> CpuFeatures {
336 CpuFeatures {
337 supports_simd: true, core_count: std::thread::available_parallelism()
339 .map(|n| n.get())
340 .unwrap_or(4),
341 cache_size_kb: 8192, }
343 }
344
345 fn determine_verification_level(platform: &VerificationPlatform) -> AdaptiveVerificationLevel {
347 match platform {
348 VerificationPlatform::NativeCpu { features } => {
349 if features.core_count >= 8 {
350 AdaptiveVerificationLevel::High
351 } else {
352 AdaptiveVerificationLevel::Balanced
353 }
354 }
355 VerificationPlatform::Gpu { compute_units, .. } => {
356 if *compute_units >= 32 {
357 AdaptiveVerificationLevel::Balanced
358 } else {
359 AdaptiveVerificationLevel::Minimal
360 }
361 }
362 VerificationPlatform::Wasm { .. } => {
363 AdaptiveVerificationLevel::Minimal
365 }
366 }
367 }
368
369 fn determine_performance_budget(platform: &VerificationPlatform) -> Duration {
371 match platform {
372 VerificationPlatform::NativeCpu { .. } => Duration::from_millis(50),
373 VerificationPlatform::Gpu { .. } => Duration::from_millis(20),
374 VerificationPlatform::Wasm { .. } => Duration::from_millis(100),
375 }
376 }
377
378 fn create_gpu_verification_config(
380 platform: &VerificationPlatform,
381 level: &AdaptiveVerificationLevel,
382 ) -> VerificationConfig {
383 let strategy = match level {
384 AdaptiveVerificationLevel::Maximum => VerificationStrategy::Strict,
385 AdaptiveVerificationLevel::High => {
386 VerificationStrategy::Statistical { sample_rate: 0.2 }
387 }
388 AdaptiveVerificationLevel::Balanced => {
389 VerificationStrategy::Statistical { sample_rate: 0.1 }
390 }
391 AdaptiveVerificationLevel::Minimal => VerificationStrategy::Boundary,
392 AdaptiveVerificationLevel::Debug => VerificationStrategy::Strict,
393 };
394
395 let budget = Self::determine_performance_budget(platform);
396
397 VerificationConfig {
398 strategy,
399 performance_budget: budget,
400 tolerance: 1e-12,
401 enable_invariant_checking: !matches!(level, AdaptiveVerificationLevel::Minimal),
402 }
403 }
404
405 async fn cpu_verification<const P: usize, const Q: usize, const R: usize>(
407 &self,
408 a: &VerifiedMultivector<P, Q, R>,
409 b: &VerifiedMultivector<P, Q, R>,
410 ) -> Result<VerifiedMultivector<P, Q, R>, AdaptiveVerificationError> {
411 let result = a.inner().geometric_product(b.inner());
413 let verified_result = VerifiedMultivector::new(result);
414
415 match self.verification_level {
417 AdaptiveVerificationLevel::Maximum | AdaptiveVerificationLevel::Debug => {
418 verified_result.verify_invariants()?;
419 self.verify_geometric_product_properties(a, b, &verified_result)?;
421 }
422 AdaptiveVerificationLevel::High => {
423 verified_result.verify_invariants()?;
424 }
425 _ => {
426 }
428 }
429
430 Ok(verified_result)
431 }
432
433 async fn cpu_batch_verification<const P: usize, const Q: usize, const R: usize>(
435 &self,
436 a_batch: &[VerifiedMultivector<P, Q, R>],
437 b_batch: &[VerifiedMultivector<P, Q, R>],
438 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
439 let mut results = Vec::with_capacity(a_batch.len());
440
441 for (a, b) in a_batch.iter().zip(b_batch.iter()) {
442 let result = self.cpu_verification(a, b).await?;
443 results.push(result);
444 }
445
446 Ok(results)
447 }
448
449 async fn gpu_batch_verification<const P: usize, const Q: usize, const R: usize>(
451 &mut self,
452 a_batch: &[VerifiedMultivector<P, Q, R>],
453 b_batch: &[VerifiedMultivector<P, Q, R>],
454 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
455 if !self.should_use_gpu(a_batch.len()) {
456 return self.cpu_batch_verification(a_batch, b_batch).await;
457 }
458
459 if let (Some(ref mut verifier), Some(ref gpu)) =
460 (&mut self.boundary_verifier, &self.gpu_instance)
461 {
462 verifier
463 .verified_batch_geometric_product(gpu, a_batch, b_batch)
464 .await
465 .map_err(AdaptiveVerificationError::GpuVerification)
466 } else {
467 self.cpu_batch_verification(a_batch, b_batch).await
469 }
470 }
471
472 async fn wasm_runtime_verification<const P: usize, const Q: usize, const R: usize>(
474 &self,
475 a: &VerifiedMultivector<P, Q, R>,
476 b: &VerifiedMultivector<P, Q, R>,
477 ) -> Result<VerifiedMultivector<P, Q, R>, AdaptiveVerificationError> {
478 if VerifiedMultivector::<P, Q, R>::signature() != (P, Q, R) {
480 return Err(AdaptiveVerificationError::GpuVerification(
481 GpuVerificationError::SignatureMismatch {
482 expected: (P, Q, R),
483 actual: VerifiedMultivector::<P, Q, R>::signature(),
484 },
485 ));
486 }
487
488 let result = a.inner().geometric_product(b.inner());
490 let verified_result = VerifiedMultivector::new(result);
491
492 if !verified_result.inner().magnitude().is_finite() {
494 return Err(AdaptiveVerificationError::GpuVerification(
495 GpuVerificationError::InvariantViolation {
496 invariant: "Result magnitude must be finite".to_string(),
497 },
498 ));
499 }
500
501 Ok(verified_result)
502 }
503
504 async fn wasm_batch_verification<const P: usize, const Q: usize, const R: usize>(
506 &self,
507 a_batch: &[VerifiedMultivector<P, Q, R>],
508 b_batch: &[VerifiedMultivector<P, Q, R>],
509 ) -> Result<Vec<VerifiedMultivector<P, Q, R>>, AdaptiveVerificationError> {
510 let mut results = Vec::with_capacity(a_batch.len());
511
512 for (a, b) in a_batch.iter().zip(b_batch.iter()) {
513 let result = self.wasm_runtime_verification(a, b).await?;
514 results.push(result);
515 }
516
517 Ok(results)
518 }
519
520 fn verify_geometric_product_properties<const P: usize, const Q: usize, const R: usize>(
522 &self,
523 a: &VerifiedMultivector<P, Q, R>,
524 b: &VerifiedMultivector<P, Q, R>,
525 result: &VerifiedMultivector<P, Q, R>,
526 ) -> Result<(), AdaptiveVerificationError> {
527 let result_mag = result.inner().magnitude();
529 let a_mag = a.inner().magnitude();
530 let b_mag = b.inner().magnitude();
531
532 if result_mag > a_mag * b_mag + 1e-12 {
533 return Err(AdaptiveVerificationError::GpuVerification(
534 GpuVerificationError::InvariantViolation {
535 invariant: format!(
536 "Magnitude inequality violated: {} > {} * {}",
537 result_mag, a_mag, b_mag
538 ),
539 },
540 ));
541 }
542
543 Ok(())
544 }
545}
546
547pub trait PlatformCapabilities {
549 fn max_batch_size(&self) -> usize;
551
552 fn optimal_strategy(&self, workload_size: usize) -> VerificationStrategy;
554
555 fn supports_concurrent_verification(&self) -> bool;
557
558 fn performance_characteristics(&self) -> PlatformPerformanceProfile;
560}
561
562#[derive(Debug, Clone)]
563pub struct PlatformPerformanceProfile {
564 pub verification_overhead_percent: f64,
565 pub memory_bandwidth_gbps: f64,
566 pub compute_throughput_gflops: f64,
567 pub latency_microseconds: f64,
568}
569
570impl PlatformCapabilities for VerificationPlatform {
571 fn max_batch_size(&self) -> usize {
572 match self {
573 VerificationPlatform::NativeCpu { features } => features.core_count * 1000,
574 VerificationPlatform::Gpu { memory_mb, .. } => {
575 (*memory_mb as usize * 1024 * 1024) / (8 * 64) }
577 VerificationPlatform::Wasm { .. } => {
578 10000 }
580 }
581 }
582
583 fn optimal_strategy(&self, workload_size: usize) -> VerificationStrategy {
584 match self {
585 VerificationPlatform::NativeCpu { .. } => {
586 if workload_size < 100 {
587 VerificationStrategy::Strict
588 } else {
589 VerificationStrategy::Statistical { sample_rate: 0.1 }
590 }
591 }
592 VerificationPlatform::Gpu { .. } => {
593 if workload_size < 50 {
594 VerificationStrategy::Boundary
595 } else {
596 VerificationStrategy::Statistical { sample_rate: 0.05 }
597 }
598 }
599 VerificationPlatform::Wasm { .. } => {
600 VerificationStrategy::Statistical { sample_rate: 0.02 }
601 }
602 }
603 }
604
605 fn supports_concurrent_verification(&self) -> bool {
606 match self {
607 VerificationPlatform::NativeCpu { features } => features.core_count > 1,
608 VerificationPlatform::Gpu { .. } => true,
609 VerificationPlatform::Wasm { .. } => false, }
611 }
612
613 fn performance_characteristics(&self) -> PlatformPerformanceProfile {
614 match self {
615 VerificationPlatform::NativeCpu { features } => PlatformPerformanceProfile {
616 verification_overhead_percent: 5.0,
617 memory_bandwidth_gbps: 50.0,
618 compute_throughput_gflops: features.core_count as f64 * 100.0,
619 latency_microseconds: 1.0,
620 },
621 VerificationPlatform::Gpu { compute_units, .. } => PlatformPerformanceProfile {
622 verification_overhead_percent: 15.0,
623 memory_bandwidth_gbps: 200.0,
624 compute_throughput_gflops: *compute_units as f64 * 50.0,
625 latency_microseconds: 100.0,
626 },
627 VerificationPlatform::Wasm { .. } => PlatformPerformanceProfile {
628 verification_overhead_percent: 25.0,
629 memory_bandwidth_gbps: 10.0,
630 compute_throughput_gflops: 10.0,
631 latency_microseconds: 1000.0,
632 },
633 }
634 }
635}
636
637#[cfg(test)]
638mod tests {
639 use super::*;
640
641 #[test]
642 fn test_cpu_features_detection() {
643 let features = AdaptiveVerifier::detect_cpu_features();
644 assert!(features.core_count > 0);
645 assert!(features.cache_size_kb > 0);
646 }
647
648 #[test]
649 fn test_verification_level_determination() {
650 let cpu_platform = VerificationPlatform::NativeCpu {
651 features: CpuFeatures {
652 supports_simd: true,
653 core_count: 8,
654 cache_size_kb: 8192,
655 },
656 };
657
658 let level = AdaptiveVerifier::determine_verification_level(&cpu_platform);
659 assert_eq!(level, AdaptiveVerificationLevel::High);
660
661 let gpu_platform = VerificationPlatform::Gpu {
662 backend: GpuBackend::Vulkan,
663 memory_mb: 2048,
664 compute_units: 16,
665 };
666
667 let level = AdaptiveVerifier::determine_verification_level(&gpu_platform);
668 assert_eq!(level, AdaptiveVerificationLevel::Minimal);
669 }
670
671 #[test]
672 fn test_platform_capabilities() {
673 let platform = VerificationPlatform::NativeCpu {
674 features: CpuFeatures {
675 supports_simd: true,
676 core_count: 4,
677 cache_size_kb: 8192,
678 },
679 };
680
681 assert_eq!(platform.max_batch_size(), 4000);
682 assert!(platform.supports_concurrent_verification());
683
684 let profile = platform.performance_characteristics();
685 assert_eq!(profile.verification_overhead_percent, 5.0);
686 assert_eq!(profile.compute_throughput_gflops, 400.0);
687 }
688
689 #[tokio::test]
690 #[ignore = "GPU hardware required, may fail in CI/CD environments"]
691 async fn test_adaptive_verifier_creation() {
692 match AdaptiveVerifier::new().await {
694 Ok(verifier) => {
695 assert!(verifier.performance_budget() > Duration::ZERO);
696 }
697 Err(AdaptiveVerificationError::PlatformDetection(_)) => {
698 }
700 Err(e) => panic!("Unexpected error: {:?}", e),
701 }
702 }
703
704 #[tokio::test]
705 async fn test_verification_with_config() {
706 match AdaptiveVerifier::with_config(
708 AdaptiveVerificationLevel::Minimal,
709 Duration::from_millis(5),
710 )
711 .await
712 {
713 Ok(verifier) => {
714 assert_eq!(
716 *verifier.verification_level(),
717 AdaptiveVerificationLevel::Minimal
718 );
719 assert_eq!(verifier.performance_budget(), Duration::from_millis(5));
720
721 match verifier.platform() {
723 VerificationPlatform::Gpu { .. } => {
724 println!("✅ GPU verification platform detected");
725 }
726 VerificationPlatform::NativeCpu { .. } => {
727 println!("✅ CPU verification platform detected (GPU not available)");
728 }
729 VerificationPlatform::Wasm { .. } => {
730 println!("✅ WASM verification platform detected");
731 }
732 }
733 }
734 Err(e) => {
735 panic!("Adaptive verifier should not fail, but got: {:?}", e);
737 }
738 }
739 }
740}