scirs2_core/
stability.rs

1//! Long-term stability guarantees and API contracts for SciRS2
2//!
3//! This module provides comprehensive stability guarantees, API contracts,
4//! and compatibility assurance for production environments requiring
5//! long-term stability commitments.
6//!
7//! ## Stability Levels
8//!
9//! - **Stable**: No breaking changes allowed
10//! - **Evolving**: Minor breaking changes with migration path
11//! - **Experimental**: May break without notice
12//! - **Deprecated**: Scheduled for removal
13//!
14//! ## API Contracts
15//!
16//! API contracts define behavioral guarantees beyond just signature stability:
17//! - Performance contracts (complexity guarantees)
18//! - Numerical contracts (precision and accuracy)
19//! - Concurrency contracts (thread-safety)
20//! - Memory contracts (allocation patterns)
21
22use crate::apiversioning::Version;
23use crate::error::{CoreError, CoreResult, ErrorContext};
24use crate::performance_optimization::PerformanceMetrics;
25use std::collections::HashMap;
26use std::hash::Hash;
27use std::sync::mpsc::{self, Receiver, Sender};
28use std::sync::{Arc, Mutex, RwLock};
29use std::time::{Duration, Instant, SystemTime};
30
31#[cfg(feature = "serialization")]
32use serde::{Deserialize, Serialize};
33
34// Advanced implementations
35mod advanced_implementations;
36pub use advanced_implementations::*;
37
38/// Stability level for APIs and components
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub enum StabilityLevel {
41    /// Stable APIs - no breaking changes allowed
42    Stable,
43    /// Evolving APIs - minor breaking changes with migration path
44    Evolving,
45    /// Experimental APIs - may break without notice
46    Experimental,
47    /// Deprecated APIs - scheduled for removal
48    Deprecated,
49}
50
51impl StabilityLevel {
52    /// Check if this stability level is compatible with another
53    pub fn is_compatible_with(self, other: StabilityLevel) -> bool {
54        match (self, other) {
55            (StabilityLevel::Stable, StabilityLevel::Stable) => true,
56            (StabilityLevel::Evolving, StabilityLevel::Stable) => true,
57            (StabilityLevel::Evolving, StabilityLevel::Experimental) => false,
58            (StabilityLevel::Experimental, StabilityLevel::Evolving) => true,
59            (StabilityLevel::Experimental, StabilityLevel::Experimental) => true,
60            (StabilityLevel::Deprecated, _) | (_, StabilityLevel::Deprecated) => false,
61            // Missing patterns
62            (StabilityLevel::Stable, StabilityLevel::Evolving) => false,
63            (StabilityLevel::Stable, StabilityLevel::Experimental) => false,
64            (StabilityLevel::Evolving, StabilityLevel::Evolving) => true,
65            (StabilityLevel::Experimental, StabilityLevel::Stable) => false,
66        }
67    }
68
69    /// Get the minimum supported version for this stability level
70    pub fn min_support_duration(self) -> Duration {
71        match self {
72            StabilityLevel::Stable => Duration::from_secs(365 * 24 * 3600 * 5), // 5 years
73            StabilityLevel::Evolving => Duration::from_secs(365 * 24 * 3600 * 2), // 2 years
74            StabilityLevel::Experimental => Duration::from_secs(90 * 24 * 3600), // 90 days
75            StabilityLevel::Deprecated => Duration::from_secs(365 * 24 * 3600), // 1 year deprecation period
76        }
77    }
78}
79
80/// API contract definition
81#[derive(Debug, Clone)]
82pub struct ApiContract {
83    /// API identifier
84    pub apiname: String,
85    /// Module name
86    pub module: String,
87    /// Cryptographic hash of the contract for immutability
88    pub contract_hash: String,
89    /// Timestamp when contract was created
90    pub created_at: SystemTime,
91    /// Formal verification status
92    pub verification_status: VerificationStatus,
93    /// Stability level
94    pub stability: StabilityLevel,
95    /// Version when contract was established
96    pub since_version: Version,
97    /// Performance contract
98    pub performance: PerformanceContract,
99    /// Numerical contract
100    pub numerical: NumericalContract,
101    /// Concurrency contract
102    pub concurrency: ConcurrencyContract,
103    /// Memory contract
104    pub memory: MemoryContract,
105    /// Deprecation information
106    pub deprecation: Option<DeprecationInfo>,
107}
108
109/// Performance contract guarantees
110#[derive(Debug, Clone)]
111pub struct PerformanceContract {
112    /// Algorithmic complexity (time)
113    pub time_complexity: ComplexityBound,
114    /// Space complexity
115    pub space_complexity: ComplexityBound,
116    /// Maximum execution time for typical inputs
117    pub maxexecution_time: Option<Duration>,
118    /// Minimum throughput guarantee
119    pub min_throughput: Option<f64>,
120    /// Memory bandwidth utilization
121    pub memorybandwidth: Option<f64>,
122}
123
124/// Numerical contract guarantees
125#[derive(Debug, Clone)]
126pub struct NumericalContract {
127    /// Precision guarantee (ULPs or relative error)
128    pub precision: PrecisionGuarantee,
129    /// Numerical stability characteristics
130    pub stability: NumericalStability,
131    /// Input domain constraints
132    pub input_domain: InputDomain,
133    /// Output range guarantees
134    pub output_range: OutputRange,
135}
136
137/// Concurrency contract guarantees
138#[derive(Debug, Clone)]
139pub struct ConcurrencyContract {
140    /// Thread safety level
141    pub thread_safety: ThreadSafety,
142    /// Atomic operation guarantees
143    pub atomicity: AtomicityGuarantee,
144    /// Lock-free guarantees
145    pub lock_free: bool,
146    /// Wait-free guarantees
147    pub wait_free: bool,
148    /// Memory ordering constraints
149    pub memory_ordering: MemoryOrdering,
150}
151
152/// Memory contract guarantees
153#[derive(Debug, Clone)]
154pub struct MemoryContract {
155    /// Memory allocation pattern
156    pub allocation_pattern: AllocationPattern,
157    /// Maximum memory usage
158    pub max_memory: Option<usize>,
159    /// Memory alignment requirements
160    pub alignment: Option<usize>,
161    /// Memory locality guarantees
162    pub locality: LocalityGuarantee,
163    /// Garbage collection behavior
164    pub gc_behavior: GcBehavior,
165}
166
167/// Deprecation information
168#[derive(Debug, Clone)]
169pub struct DeprecationInfo {
170    /// Version when deprecation was announced
171    pub announced_version: Version,
172    /// Version when removal is planned
173    pub removal_version: Version,
174    /// Reason for deprecation
175    pub reason: String,
176    /// Migration path to replacement
177    pub migration_path: Option<String>,
178    /// Replacement API recommendation
179    pub replacement: Option<String>,
180}
181
182/// Complexity bounds for performance contracts
183#[derive(Debug, Clone)]
184pub enum ComplexityBound {
185    /// O(1) - constant time
186    Constant,
187    /// O(log n) - logarithmic
188    Logarithmic,
189    /// O(n) - linear
190    Linear,
191    /// O(n log n) - linearithmic
192    Linearithmic,
193    /// O(n²) - quadratic
194    Quadratic,
195    /// O(n³) - cubic
196    Cubic,
197    /// O(2^n) - exponential
198    Exponential,
199    /// Custom complexity expression
200    Custom(String),
201}
202
203/// Precision guarantees for numerical operations
204#[derive(Debug, Clone)]
205pub enum PrecisionGuarantee {
206    /// Exact computation (no rounding errors)
207    Exact,
208    /// Machine precision (within floating-point epsilon)
209    MachinePrecision,
210    /// Relative error bound
211    RelativeError(f64),
212    /// Absolute error bound
213    AbsoluteError(f64),
214    /// ULP (Units in the Last Place) bound
215    UlpBound(u64),
216    /// Custom precision specification
217    Custom(String),
218}
219
220/// Numerical stability characteristics
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum NumericalStability {
223    /// Stable algorithm - small input changes produce small output changes
224    Stable,
225    /// Conditionally stable - stability depends on input characteristics
226    ConditionallyStable,
227    /// Unstable - may amplify small input errors significantly
228    Unstable,
229}
230
231/// Input domain constraints
232#[derive(Debug, Clone)]
233pub struct InputDomain {
234    /// Valid input ranges
235    pub ranges: Vec<(f64, f64)>,
236    /// Excluded values or ranges
237    pub exclusions: Vec<f64>,
238    /// Special value handling (NaN, Inf)
239    pub special_values: SpecialValueHandling,
240}
241
242/// Output range guarantees
243#[derive(Debug, Clone)]
244pub struct OutputRange {
245    /// Guaranteed output bounds
246    pub bounds: Option<(f64, f64)>,
247    /// Monotonicity guarantee
248    pub monotonic: Option<Monotonicity>,
249    /// Continuity guarantee
250    pub continuous: bool,
251}
252
253/// Special value handling in numerical operations
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub enum SpecialValueHandling {
256    /// Propagate special values (IEEE 754 standard)
257    Propagate,
258    /// Error on special values
259    Error,
260    /// Replace with default values
261    Replace,
262    /// Custom handling
263    Custom,
264}
265
266/// Monotonicity characteristics
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum Monotonicity {
269    /// Strictly increasing
270    StrictlyIncreasing,
271    /// Non-decreasing
272    NonDecreasing,
273    /// Strictly decreasing
274    StrictlyDecreasing,
275    /// Non-increasing
276    NonIncreasing,
277}
278
279/// Thread safety levels
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum ThreadSafety {
282    /// Thread-safe for all operations
283    ThreadSafe,
284    /// Thread-safe for read operations only
285    ReadSafe,
286    /// Not thread-safe - requires external synchronization
287    NotThreadSafe,
288    /// Immutable - inherently thread-safe
289    Immutable,
290}
291
292/// Atomicity guarantees
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum AtomicityGuarantee {
295    /// All operations are atomic
296    FullyAtomic,
297    /// Individual operations are atomic, but sequences are not
298    OperationAtomic,
299    /// No atomicity guarantees
300    NonAtomic,
301}
302
303/// Memory ordering constraints
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum MemoryOrdering {
306    /// Sequentially consistent
307    SequentiallyConsistent,
308    /// Acquire-release
309    AcquireRelease,
310    /// Relaxed ordering
311    Relaxed,
312}
313
314/// Memory allocation patterns
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316pub enum AllocationPattern {
317    /// No heap allocations
318    NoAllocation,
319    /// Single allocation at initialization
320    SingleAllocation,
321    /// Bounded number of allocations
322    BoundedAllocations,
323    /// Unbounded allocations possible
324    UnboundedAllocations,
325}
326
327/// Memory locality guarantees
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub enum LocalityGuarantee {
330    /// Excellent spatial locality
331    ExcellentSpatial,
332    /// Good spatial locality
333    GoodSpatial,
334    /// Poor spatial locality
335    PoorSpatial,
336    /// Random access pattern
337    RandomAccess,
338}
339
340/// Garbage collection behavior
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub enum GcBehavior {
343    /// No garbage collection impact
344    NoGc,
345    /// Minimal GC pressure
346    MinimalGc,
347    /// Moderate GC pressure
348    ModerateGc,
349    /// High GC pressure
350    HighGc,
351}
352
353/// Formal verification status
354#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub enum VerificationStatus {
357    /// Not verified
358    NotVerified,
359    /// Verification in progress
360    InProgress,
361    /// Formally verified
362    Verified,
363    /// Verification failed
364    Failed,
365}
366
367/// Runtime monitoring event
368#[derive(Debug, Clone)]
369pub struct MonitoringEvent {
370    /// Event timestamp
371    pub timestamp: Instant,
372    /// API that triggered the event
373    pub apiname: String,
374    /// Module containing the API
375    pub module: String,
376    /// Event type
377    pub event_type: MonitoringEventType,
378    /// Performance metrics at time of event
379    pub performance_metrics: RuntimePerformanceMetrics,
380    /// Thread ID where event occurred
381    pub thread_id: String,
382}
383
384/// Types of monitoring events
385#[derive(Debug, Clone)]
386pub enum MonitoringEventType {
387    /// Contract violation detected
388    ContractViolation(ContractViolation),
389    /// Performance threshold exceeded
390    PerformanceThresholdExceeded {
391        expected: Duration,
392        actual: Duration,
393    },
394    /// Memory usage exceeded contract
395    MemoryExceeded { expected: usize, actual: usize },
396    /// Thread safety violation
397    ThreadSafetyViolation(String),
398    /// Chaos engineering fault injected
399    ChaosEngineeringFault(ChaosFault),
400}
401
402/// Contract violation details
403#[derive(Debug, Clone)]
404pub struct ContractViolation {
405    /// Type of violation
406    pub violation_type: ViolationType,
407    /// Expected value or behavior
408    pub expected: String,
409    /// Actual value or behavior
410    pub actual: String,
411    /// Severity of the violation
412    pub severity: ViolationSeverity,
413}
414
415/// Types of contract violations
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417pub enum ViolationType {
418    Performance,
419    Numerical,
420    Memory,
421    Concurrency,
422    Behavioral,
423}
424
425/// Severity levels for violations
426#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
427pub enum ViolationSeverity {
428    Low,
429    Medium,
430    High,
431    Critical,
432}
433
434/// Runtime performance metrics
435#[derive(Debug, Clone)]
436pub struct RuntimePerformanceMetrics {
437    /// Execution time
438    pub execution_time: Duration,
439    /// Memory usage
440    pub memory_usage: usize,
441    /// CPU usage percentage
442    pub cpu_usage: f64,
443    /// Cache hit rate
444    pub cache_hit_rate: f64,
445    /// Thread count
446    pub thread_count: usize,
447}
448
449/// Chaos engineering fault types
450#[derive(Debug, Clone)]
451pub enum ChaosFault {
452    /// Artificial delay injection
453    LatencyInjection(Duration),
454    /// Memory pressure simulation
455    MemoryPressure(usize),
456    /// CPU throttling
457    CpuThrottling(f64),
458    /// Network partition simulation
459    NetworkPartition,
460    /// Random failure injection
461    RandomFailure(f64), // probability
462}
463
464/// Formal verification engine
465#[derive(Debug)]
466pub struct FormalVerificationEngine {
467    /// Active verification tasks
468    verification_tasks: Arc<Mutex<HashMap<String, VerificationTask>>>,
469    /// Verification results cache
470    results_cache: Arc<RwLock<HashMap<String, VerificationResult>>>,
471}
472
473/// Verification task
474#[derive(Debug, Clone)]
475struct VerificationTask {
476    /// API being verified
477    #[allow(dead_code)]
478    apiname: String,
479    /// Module containing the API
480    #[allow(dead_code)]
481    module: String,
482    /// Verification properties to check
483    properties: Vec<VerificationProperty>,
484    /// Task status
485    status: VerificationStatus,
486    /// Started at
487    #[allow(dead_code)]
488    started_at: Instant,
489}
490
491/// Verification property
492#[derive(Debug, Clone)]
493struct VerificationProperty {
494    /// Property name
495    name: String,
496    /// Property specification (e.g., temporal logic formula)
497    #[allow(dead_code)]
498    specification: String,
499    /// Property type
500    #[allow(dead_code)]
501    property_type: PropertyType,
502}
503
504/// Types of verification properties
505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506enum PropertyType {
507    Safety,
508    #[allow(dead_code)]
509    Liveness,
510    #[allow(dead_code)]
511    Invariant,
512    #[allow(dead_code)]
513    Temporal,
514}
515
516/// Verification result
517#[derive(Debug, Clone)]
518pub struct VerificationResult {
519    /// Whether verification succeeded
520    #[allow(dead_code)]
521    verified: bool,
522    /// Verification time
523    #[allow(dead_code)]
524    verification_time: Duration,
525    /// Properties that were checked
526    #[allow(dead_code)]
527    checked_properties: Vec<String>,
528    /// Counterexample if verification failed
529    #[allow(dead_code)]
530    counterexample: Option<String>,
531    /// Verification method used
532    #[allow(dead_code)]
533    method: VerificationMethod,
534}
535
536/// Verification methods
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
538enum VerificationMethod {
539    #[allow(dead_code)]
540    ModelChecking,
541    #[allow(dead_code)]
542    TheoremProving,
543    #[allow(dead_code)]
544    AbstractInterpretation,
545    #[allow(dead_code)]
546    SymbolicExecution,
547    StaticAnalysis,
548}
549
550/// Runtime contract validator
551#[derive(Debug)]
552pub struct RuntimeContractValidator {
553    /// Active contracts
554    contracts: Arc<RwLock<HashMap<String, ApiContract>>>,
555    /// Monitoring events channel
556    event_sender: Sender<MonitoringEvent>,
557    /// Validation statistics
558    stats: Arc<Mutex<ValidationStatistics>>,
559    /// Chaos engineering controller
560    chaos_controller: Arc<Mutex<ChaosEngineeringController>>,
561}
562
563/// Validation statistics
564#[derive(Debug, Clone)]
565pub struct ValidationStatistics {
566    /// Total validations performed
567    pub total_validations: u64,
568    /// Contract violations detected
569    pub violations_detected: u64,
570    /// Average validation time
571    pub avg_validation_time: Duration,
572    /// Validation success rate
573    pub success_rate: f64,
574}
575
576/// Chaos engineering controller
577#[derive(Debug)]
578struct ChaosEngineeringController {
579    /// Whether chaos engineering is enabled
580    enabled: bool,
581    /// Fault injection probability
582    faultprobability: f64,
583    /// Active faults
584    active_faults: Vec<ChaosFault>,
585    /// Fault history
586    fault_history: Vec<(Instant, ChaosFault)>,
587}
588
589/// Advanced performance modeling engine
590#[derive(Debug)]
591pub struct AdvancedPerformanceModeler {
592    /// Historical performance data
593    performance_history: Arc<RwLock<Vec<PerformanceDataPoint>>>,
594    /// Machine learning models for prediction
595    prediction_models: Arc<RwLock<HashMap<String, PerformancePredictionModel>>>,
596    /// Model training status
597    training_status: Arc<Mutex<HashMap<String, TrainingStatus>>>,
598}
599
600/// Performance data point
601#[derive(Debug, Clone)]
602struct PerformanceDataPoint {
603    /// Timestamp
604    #[allow(dead_code)]
605    timestamp: Instant,
606    /// API name
607    apiname: String,
608    /// Input characteristics
609    input_characteristics: InputCharacteristics,
610    /// Measured performance
611    performance: RuntimePerformanceMetrics,
612    /// System state
613    #[allow(dead_code)]
614    system_state: SystemState,
615}
616
617/// Input characteristics for performance modeling
618#[derive(Debug, Clone)]
619pub struct InputCharacteristics {
620    /// Input size
621    size: usize,
622    /// Data type
623    #[allow(dead_code)]
624    datatype: String,
625    /// Memory layout
626    #[allow(dead_code)]
627    memory_layout: String,
628    /// Access pattern
629    #[allow(dead_code)]
630    access_pattern: String,
631}
632
633/// System state at time of measurement
634#[derive(Debug, Clone)]
635pub struct SystemState {
636    /// CPU utilization
637    cpu_utilization: f64,
638    /// Memory utilization
639    #[allow(dead_code)]
640    memory_utilization: f64,
641    /// IO load
642    #[allow(dead_code)]
643    io_load: f64,
644    /// Network load
645    #[allow(dead_code)]
646    network_load: f64,
647    /// Temperature
648    #[allow(dead_code)]
649    temperature: f64,
650}
651
652/// Performance prediction model
653#[derive(Debug, Clone)]
654struct PerformancePredictionModel {
655    /// Model type
656    model_type: ModelType,
657    /// Model parameters
658    parameters: Vec<f64>,
659    /// Model accuracy
660    accuracy: f64,
661    /// Training data size
662    #[allow(dead_code)]
663    training_data_size: usize,
664    /// Last updated
665    #[allow(dead_code)]
666    last_updated: Instant,
667}
668
669/// Machine learning model types
670#[derive(Debug, Clone, Copy, PartialEq, Eq)]
671enum ModelType {
672    LinearRegression,
673    #[allow(dead_code)]
674    PolynomialRegression,
675    #[allow(dead_code)]
676    NeuralNetwork,
677    #[allow(dead_code)]
678    RandomForest,
679    #[allow(dead_code)]
680    SupportVectorMachine,
681    #[allow(dead_code)]
682    GradientBoosting,
683}
684
685/// Training status
686#[derive(Debug, Clone, Copy, PartialEq, Eq)]
687pub enum TrainingStatus {
688    NotStarted,
689    InProgress,
690    Completed,
691    Failed,
692}
693
694/// Immutable audit trail using cryptographic hashing
695#[derive(Debug)]
696pub struct ImmutableAuditTrail {
697    /// Chain of audit records
698    audit_chain: Arc<RwLock<Vec<AuditRecord>>>,
699    /// Current chain hash
700    current_hash: Arc<RwLock<String>>,
701}
702
703/// Audit record
704#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
705#[derive(Debug, Clone)]
706pub struct AuditRecord {
707    /// Record timestamp
708    timestamp: SystemTime,
709    /// Previous record hash
710    previous_hash: String,
711    /// Record data
712    data: AuditData,
713    /// Digital signature
714    signature: String,
715    /// Record hash
716    record_hash: String,
717}
718
719/// Audit data types
720#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
721#[derive(Debug, Clone)]
722pub enum AuditData {
723    /// Contract registration
724    ContractRegistration(String),
725    /// Contract validation
726    ContractValidation {
727        apiname: String,
728        module: String,
729        result: bool,
730    },
731    /// Performance measurement
732    PerformanceMeasurement {
733        apiname: String,
734        module: String,
735        metrics: String, // Serialized metrics
736    },
737    /// Violation detection
738    ViolationDetection {
739        apiname: String,
740        module: String,
741        violation: String, // Serialized violation
742    },
743}
744
745/// Advanced stability guarantee manager with formal verification and runtime monitoring
746pub struct StabilityGuaranteeManager {
747    /// Registered API contracts
748    contracts: HashMap<String, ApiContract>,
749    /// Compatibility matrix between versions
750    compatibilitymatrix: HashMap<(Version, Version), bool>,
751    /// Breaking change log
752    breakingchanges: Vec<BreakingChange>,
753    /// Formal verification engine
754    verification_engine: Arc<FormalVerificationEngine>,
755    /// Runtime contract validator
756    runtime_validator: Arc<RuntimeContractValidator>,
757    /// Performance modeling engine
758    performance_modeler: Arc<AdvancedPerformanceModeler>,
759    /// Immutable audit trail
760    audit_trail: Arc<ImmutableAuditTrail>,
761    /// Real-time monitoring event receiver
762    #[allow(dead_code)]
763    monitoring_receiver: Option<Receiver<MonitoringEvent>>,
764}
765
766/// Breaking change record
767#[derive(Debug, Clone)]
768pub struct BreakingChange {
769    /// API that was changed
770    pub apiname: String,
771    /// Module containing the API
772    pub module: String,
773    /// Version where change occurred
774    pub version: Version,
775    /// Type of breaking change
776    pub change_type: BreakingChangeType,
777    /// Description of the change
778    pub description: String,
779    /// Migration instructions
780    pub migration: Option<String>,
781}
782
783/// Types of breaking changes
784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
785pub enum BreakingChangeType {
786    /// Function signature changed
787    SignatureChange,
788    /// Function removed
789    Removal,
790    /// Behavior changed
791    BehaviorChange,
792    /// Performance characteristics changed
793    PerformanceChange,
794    /// Thread safety guarantees changed
795    ConcurrencyChange,
796    /// Memory usage patterns changed
797    MemoryChange,
798}
799
800impl Default for StabilityGuaranteeManager {
801    fn default() -> Self {
802        Self::new()
803    }
804}
805
806impl StabilityGuaranteeManager {
807    /// Create a new advanced stability guarantee manager
808    pub fn new() -> Self {
809        let (validator, receiver) = RuntimeContractValidator::new();
810
811        Self {
812            contracts: HashMap::new(),
813            compatibilitymatrix: HashMap::new(),
814            breakingchanges: Vec::new(),
815            verification_engine: Arc::new(FormalVerificationEngine::new()),
816            runtime_validator: Arc::new(validator),
817            performance_modeler: Arc::new(AdvancedPerformanceModeler::new()),
818            audit_trail: Arc::new(ImmutableAuditTrail::new()),
819            monitoring_receiver: Some(receiver),
820        }
821    }
822
823    /// Register an API contract
824    pub fn register_contract(&mut self, contract: ApiContract) -> CoreResult<()> {
825        let key = format!(
826            "{module}::{apiname}",
827            module = contract.module,
828            apiname = contract.apiname
829        );
830
831        // Check for existing contract
832        if let Some(existing) = self.contracts.get(&key) {
833            // Verify compatibility with existing contract
834            if existing.stability != contract.stability {
835                return Err(CoreError::ValidationError(ErrorContext::new(format!(
836                    "Stability level change not allowed for {}: {:?} -> {:?}",
837                    key, existing.stability, contract.stability
838                ))));
839            }
840        }
841
842        self.contracts.insert(key, contract);
843        Ok(())
844    }
845
846    /// Get contract for an API
847    pub fn get_contract(&self, apiname: &str, module: &str) -> Option<&ApiContract> {
848        let key = format!("{module}::{apiname}");
849        self.contracts.get(&key)
850    }
851
852    /// Check if an API has stability guarantees
853    pub fn has_stability_guarantees(&self, apiname: &str, module: &str) -> bool {
854        self.get_contract(apiname, module)
855            .map(|c| {
856                matches!(
857                    c.stability,
858                    StabilityLevel::Stable | StabilityLevel::Evolving
859                )
860            })
861            .unwrap_or(false)
862    }
863
864    /// Validate API usage against contracts
865    pub fn validate_usage(
866        &self,
867        apiname: &str,
868        module: &str,
869        usage_context: &UsageContext,
870    ) -> CoreResult<()> {
871        let contract = self.get_contract(apiname, module).ok_or_else(|| {
872            CoreError::ValidationError(ErrorContext::new(format!(
873                "No contract found for {module}::{apiname}"
874            )))
875        })?;
876
877        // Check stability level compatibility
878        if !contract
879            .stability
880            .is_compatible_with(usage_context.required_stability)
881        {
882            return Err(CoreError::ValidationError(ErrorContext::new(format!(
883                "Stability requirement not met: required {:?}, available {:?}",
884                usage_context.required_stability, contract.stability
885            ))));
886        }
887
888        // Check performance requirements
889        if let Some(max_time) = usage_context.maxexecution_time {
890            if let Some(contract_time) = contract.performance.maxexecution_time {
891                if contract_time > max_time {
892                    return Err(CoreError::ValidationError(ErrorContext::new(format!(
893                        "Performance requirement not met: max execution time {contract_time:?} > required {max_time:?}"
894                    ))));
895                }
896            }
897        }
898
899        // Check concurrency requirements
900        if usage_context.requires_thread_safety
901            && contract.concurrency.thread_safety == ThreadSafety::NotThreadSafe
902        {
903            return Err(CoreError::ValidationError(ErrorContext::new(format!(
904                "Thread safety required but {module}::{apiname} is not thread-safe"
905            ))));
906        }
907
908        Ok(())
909    }
910
911    /// Record a breaking change
912    pub fn record_breaking_change(&mut self, change: BreakingChange) {
913        // Extract version before moving the change
914        let current_version = change.version;
915
916        self.breakingchanges.push(change);
917
918        // Update compatibility matrix
919        // Mark versions before and after the change as incompatible
920        let previous_version = Version::new(
921            current_version.major,
922            current_version.minor.saturating_sub(1),
923            0,
924        );
925
926        self.compatibilitymatrix
927            .insert((previous_version, current_version), false);
928    }
929
930    /// Check version compatibility
931    pub fn areversions_compatible(&self, from: &Version, to: &Version) -> bool {
932        // Check explicit compatibility matrix first
933        if let Some(&compatible) = self.compatibilitymatrix.get(&(*from, *to)) {
934            return compatible;
935        }
936
937        // Default compatibility rules
938        if from.major != to.major || from.minor > to.minor {
939            false // Major version changes or minor downgrades are breaking
940        } else {
941            true // Same major, newer or equal minor version
942        }
943    }
944
945    /// Generate stability report
946    pub fn generate_stability_report(&self) -> String {
947        let mut report = String::from("# API Stability Report\n\n");
948
949        // Summary statistics
950        let total_contracts = self.contracts.len();
951        let stable_count = self
952            .contracts
953            .values()
954            .filter(|c| c.stability == StabilityLevel::Stable)
955            .count();
956        let evolving_count = self
957            .contracts
958            .values()
959            .filter(|c| c.stability == StabilityLevel::Evolving)
960            .count();
961        let experimental_count = self
962            .contracts
963            .values()
964            .filter(|c| c.stability == StabilityLevel::Experimental)
965            .count();
966        let deprecated_count = self
967            .contracts
968            .values()
969            .filter(|c| c.stability == StabilityLevel::Deprecated)
970            .count();
971
972        report.push_str("## Summary\n\n");
973        report.push_str(&format!("- Total APIs with contracts: {total_contracts}\n"));
974        report.push_str(&format!("- Stable APIs: {stable_count}\n"));
975        report.push_str(&format!("- Evolving APIs: {evolving_count}\n"));
976        report.push_str(&format!("- Experimental APIs: {experimental_count}\n"));
977        report.push_str(&format!("- Deprecated APIs: {deprecated_count}\n"));
978
979        // Stability coverage
980        let coverage = if total_contracts > 0 {
981            ((stable_count + evolving_count) as f64 / total_contracts as f64) * 100.0
982        } else {
983            0.0
984        };
985        report.push_str(&format!("- Stability coverage: {coverage:.1}%\n\n"));
986
987        // Breaking changes
988        report.push_str("## Breaking Changes\n\n");
989        if self.breakingchanges.is_empty() {
990            report.push_str("No breaking changes recorded.\n\n");
991        } else {
992            for change in &self.breakingchanges {
993                report.push_str(&format!(
994                    "- **{}::{}** (v{}): {:?} - {}\n",
995                    change.module,
996                    change.apiname,
997                    change.version,
998                    change.change_type,
999                    change.description
1000                ));
1001            }
1002            report.push('\n');
1003        }
1004
1005        // Contracts by module
1006        let mut modules: HashMap<&str, Vec<&ApiContract>> = HashMap::new();
1007        for contract in self.contracts.values() {
1008            modules.entry(&contract.module).or_default().push(contract);
1009        }
1010
1011        report.push_str("## Contracts by Module\n\n");
1012        for (module, contracts) in modules {
1013            report.push_str(&format!("### Module: {module}\n\n"));
1014            for contract in contracts {
1015                report.push_str(&format!(
1016                    "- **{}** ({:?})\n",
1017                    contract.apiname, contract.stability
1018                ));
1019            }
1020            report.push('\n');
1021        }
1022
1023        report
1024    }
1025
1026    /// Initialize default contracts for core APIs
1027    pub fn initialize_core_contracts(&mut self) -> CoreResult<()> {
1028        // Error handling contracts
1029        self.register_contract(ApiContract {
1030            apiname: "CoreError".to_string(),
1031            module: "error".to_string(),
1032            contract_hash: "coreerror_v1_0_0".to_string(),
1033            created_at: SystemTime::now(),
1034            verification_status: VerificationStatus::Verified,
1035            stability: StabilityLevel::Stable,
1036            since_version: Version::new(1, 0, 0),
1037            performance: PerformanceContract {
1038                time_complexity: ComplexityBound::Constant,
1039                space_complexity: ComplexityBound::Constant,
1040                maxexecution_time: Some(Duration::from_nanos(100)),
1041                min_throughput: None,
1042                memorybandwidth: None,
1043            },
1044            numerical: NumericalContract {
1045                precision: PrecisionGuarantee::Exact,
1046                stability: NumericalStability::Stable,
1047                input_domain: InputDomain {
1048                    ranges: vec![],
1049                    exclusions: vec![],
1050                    special_values: SpecialValueHandling::Propagate,
1051                },
1052                output_range: OutputRange {
1053                    bounds: None,
1054                    monotonic: None,
1055                    continuous: true,
1056                },
1057            },
1058            concurrency: ConcurrencyContract {
1059                thread_safety: ThreadSafety::ThreadSafe,
1060                atomicity: AtomicityGuarantee::FullyAtomic,
1061                lock_free: true,
1062                wait_free: true,
1063                memory_ordering: MemoryOrdering::SequentiallyConsistent,
1064            },
1065            memory: MemoryContract {
1066                allocation_pattern: AllocationPattern::NoAllocation,
1067                max_memory: Some(1024),
1068                alignment: None,
1069                locality: LocalityGuarantee::ExcellentSpatial,
1070                gc_behavior: GcBehavior::NoGc,
1071            },
1072            deprecation: None,
1073        })?;
1074
1075        // Validation function contracts
1076        self.register_contract(ApiContract {
1077            apiname: "check_finite".to_string(),
1078            module: "validation".to_string(),
1079            contract_hash: "check_finite_v1_0_0".to_string(),
1080            created_at: SystemTime::now(),
1081            verification_status: VerificationStatus::Verified,
1082            stability: StabilityLevel::Stable,
1083            since_version: Version::new(1, 0, 0),
1084            performance: PerformanceContract {
1085                time_complexity: ComplexityBound::Constant,
1086                space_complexity: ComplexityBound::Constant,
1087                maxexecution_time: Some(Duration::from_nanos(10)),
1088                min_throughput: None,
1089                memorybandwidth: None,
1090            },
1091            numerical: NumericalContract {
1092                precision: PrecisionGuarantee::Exact,
1093                stability: NumericalStability::Stable,
1094                input_domain: InputDomain {
1095                    ranges: vec![],
1096                    exclusions: vec![],
1097                    special_values: SpecialValueHandling::Error,
1098                },
1099                output_range: OutputRange {
1100                    bounds: None,
1101                    monotonic: None,
1102                    continuous: true,
1103                },
1104            },
1105            concurrency: ConcurrencyContract {
1106                thread_safety: ThreadSafety::ThreadSafe,
1107                atomicity: AtomicityGuarantee::FullyAtomic,
1108                lock_free: true,
1109                wait_free: true,
1110                memory_ordering: MemoryOrdering::Relaxed,
1111            },
1112            memory: MemoryContract {
1113                allocation_pattern: AllocationPattern::NoAllocation,
1114                max_memory: Some(64),
1115                alignment: None,
1116                locality: LocalityGuarantee::ExcellentSpatial,
1117                gc_behavior: GcBehavior::NoGc,
1118            },
1119            deprecation: None,
1120        })?;
1121
1122        Ok(())
1123    }
1124
1125    /// Calculate cryptographic hash of contract
1126    #[allow(dead_code)]
1127    fn calculate_contract_hash(&self, contract: &ApiContract) -> String {
1128        use std::collections::hash_map::DefaultHasher;
1129        use std::hash::Hasher;
1130
1131        let mut hasher = DefaultHasher::new();
1132
1133        contract.apiname.hash(&mut hasher);
1134        contract.module.hash(&mut hasher);
1135        format!("{:?}", contract.stability).hash(&mut hasher);
1136        format!("{:?}", contract.performance.time_complexity).hash(&mut hasher);
1137
1138        format!("{:x}", hasher.finish())
1139    }
1140
1141    /// Validate API call at runtime
1142    pub fn validate_api_call(
1143        &self,
1144        apiname: &str,
1145        module: &str,
1146        call_context: &ApiCallContext,
1147    ) -> CoreResult<()> {
1148        self.runtime_validator
1149            .validate_api_call(apiname, module, call_context)
1150    }
1151
1152    /// Enable chaos engineering for resilience testing
1153    pub fn enable_chaos_engineering(&mut self, faultprobability: f64) {
1154        self.runtime_validator
1155            .enable_chaos_engineering(faultprobability);
1156    }
1157
1158    /// Record performance measurement for modeling
1159    pub fn record_performance(
1160        &mut self,
1161        apiname: &str,
1162        module: &str,
1163        system_state: SystemState,
1164        input_characteristics: InputCharacteristics,
1165        performance: PerformanceMetrics,
1166    ) {
1167        // Clone performance metrics for audit trail before moving to record_measurement
1168        let metrics_for_audit = format!("{performance:?}");
1169
1170        self.performance_modeler.record_measurement(
1171            apiname,
1172            input_characteristics,
1173            performance,
1174            system_state,
1175        );
1176
1177        // Add to audit trail
1178        let _ = self
1179            .audit_trail
1180            .add_record(AuditData::PerformanceMeasurement {
1181                apiname: apiname.to_string(),
1182                module: module.to_string(),
1183                metrics: metrics_for_audit,
1184            });
1185    }
1186
1187    /// Predict performance for given conditions
1188    pub fn predict_performance(
1189        &self,
1190        apiname: &str,
1191        input_characteristics: InputCharacteristics,
1192        system_state: &SystemState,
1193    ) -> Option<RuntimePerformanceMetrics> {
1194        self.performance_modeler
1195            .predict_performance(apiname, input_characteristics, system_state)
1196    }
1197
1198    /// Get formal verification status
1199    pub fn get_verification_status(&self, apiname: &str, module: &str) -> VerificationStatus {
1200        self.verification_engine
1201            .get_verification_status(apiname, module)
1202    }
1203
1204    /// Get runtime validation statistics
1205    pub fn get_validation_statistics(&self) -> Option<ValidationStatistics> {
1206        self.runtime_validator.get_statistics()
1207    }
1208
1209    /// Verify audit trail integrity
1210    pub fn verify_audit_integrity(&self) -> bool {
1211        self.audit_trail.verify_integrity()
1212    }
1213
1214    /// Get audit trail length
1215    pub fn get_audit_trail_length(&self) -> usize {
1216        self.audit_trail.len()
1217    }
1218
1219    /// Get verification coverage percentage
1220    pub fn get_verification_coverage(&self) -> f64 {
1221        self.verification_engine.get_verification_coverage()
1222    }
1223
1224    /// Get performance model accuracy for an API
1225    pub fn get_model_accuracy(&self, apiname: &str) -> Option<f64> {
1226        self.performance_modeler.get_model_accuracy(apiname)
1227    }
1228
1229    /// Get chaos engineering status
1230    pub fn get_chaos_status(&self) -> Option<(bool, f64, usize)> {
1231        self.runtime_validator.get_chaos_status()
1232    }
1233
1234    /// Export audit trail for external verification
1235    pub fn export_audit_trail(&self) -> CoreResult<String> {
1236        self.audit_trail.export_trail()
1237    }
1238}
1239
1240/// Context for API usage validation
1241pub struct UsageContext {
1242    /// Required stability level
1243    pub required_stability: StabilityLevel,
1244    /// Maximum acceptable execution time
1245    pub maxexecution_time: Option<Duration>,
1246    /// Whether thread safety is required
1247    pub requires_thread_safety: bool,
1248    /// Maximum acceptable memory usage
1249    pub max_memory_usage: Option<usize>,
1250    /// Required precision level
1251    pub required_precision: Option<PrecisionGuarantee>,
1252}
1253
1254impl Default for UsageContext {
1255    fn default() -> Self {
1256        Self {
1257            required_stability: StabilityLevel::Stable,
1258            maxexecution_time: None,
1259            requires_thread_safety: false,
1260            max_memory_usage: None,
1261            required_precision: None,
1262        }
1263    }
1264}
1265
1266/// Global stability guarantee manager instance
1267static mut STABILITY_MANAGER: Option<StabilityGuaranteeManager> = None;
1268static INIT_STABILITY: std::sync::Once = std::sync::Once::new();
1269
1270/// Get the global stability guarantee manager
1271#[allow(static_mut_refs)]
1272#[allow(dead_code)]
1273pub fn global_stability_manager() -> &'static mut StabilityGuaranteeManager {
1274    unsafe {
1275        INIT_STABILITY.call_once(|| {
1276            let mut manager = StabilityGuaranteeManager::new();
1277            let _ = manager.initialize_core_contracts();
1278            STABILITY_MANAGER = Some(manager);
1279        });
1280
1281        STABILITY_MANAGER.as_mut().unwrap()
1282    }
1283}
1284
1285/// Check if an API has long-term stability guarantees
1286#[allow(dead_code)]
1287pub fn has_stability_guarantee(apiname: &str, module: &str) -> bool {
1288    global_stability_manager().has_stability_guarantees(apiname, module)
1289}
1290
1291/// Validate API usage against stability contracts
1292#[allow(dead_code)]
1293pub fn validate_api_usage(apiname: &str, module: &str, context: &UsageContext) -> CoreResult<()> {
1294    global_stability_manager().validate_usage(apiname, module, context)
1295}
1296
1297/// Check if an API has long-term stability
1298#[allow(dead_code)]
1299pub fn has_long_term_stability(apiname: &str, module: &str) -> bool {
1300    // For now, return true for all APIs
1301    let _ = (apiname, module); // Use parameters to avoid warnings
1302    true // Default to true for all cases
1303}
1304
1305/// Stability contract for APIs
1306#[derive(Debug, Clone)]
1307pub struct StabilityContract {
1308    /// API name
1309    pub apiname: String,
1310    /// Version when introduced
1311    pub version_introduced: Version,
1312    /// Stability level
1313    pub stability_level: StabilityLevel,
1314    /// Deprecated since version (if applicable)
1315    pub deprecated_since: Option<Version>,
1316    /// Removal version (if scheduled)
1317    pub removal_version: Option<Version>,
1318    /// Complexity bound
1319    pub complexity_bound: ComplexityBound,
1320    /// Precision guarantee
1321    pub precision_guarantee: PrecisionGuarantee,
1322    /// Thread safety
1323    pub thread_safety: ThreadSafety,
1324    /// Breaking changes history
1325    pub breakingchanges: Vec<BreakingChange>,
1326    /// Migration path (if deprecated)
1327    pub migration_path: Option<String>,
1328}
1329
1330/// Validate stability requirements
1331#[allow(dead_code)]
1332pub fn validate_stability_requirements(
1333    apiname: &str,
1334    _module: &str,
1335    _context: &UsageContext,
1336) -> Result<StabilityContract, CoreError> {
1337    // Simple implementation that returns a default contract
1338    Ok(StabilityContract {
1339        apiname: apiname.to_string(),
1340        version_introduced: Version::new(0, 1, 0),
1341        stability_level: StabilityLevel::Stable,
1342        deprecated_since: None,
1343        removal_version: None,
1344        complexity_bound: ComplexityBound::Constant,
1345        precision_guarantee: PrecisionGuarantee::MachinePrecision,
1346        thread_safety: ThreadSafety::ThreadSafe,
1347        breakingchanges: vec![],
1348        migration_path: None,
1349    })
1350}
1351
1352#[cfg(test)]
1353mod tests {
1354    use super::*;
1355
1356    #[test]
1357    fn test_stability_levels() {
1358        assert!(StabilityLevel::Stable.is_compatible_with(StabilityLevel::Stable));
1359        assert!(!StabilityLevel::Stable.is_compatible_with(StabilityLevel::Experimental));
1360        assert!(StabilityLevel::Evolving.is_compatible_with(StabilityLevel::Stable));
1361        assert!(!StabilityLevel::Evolving.is_compatible_with(StabilityLevel::Experimental));
1362    }
1363
1364    #[test]
1365    fn test_stability_manager() {
1366        let mut manager = StabilityGuaranteeManager::new();
1367
1368        let contract = ApiContract {
1369            apiname: "test_function".to_string(),
1370            module: "test_module".to_string(),
1371            contract_hash: "test_function_v1_0_0".to_string(),
1372            created_at: SystemTime::now(),
1373            verification_status: VerificationStatus::Verified,
1374            stability: StabilityLevel::Stable,
1375            since_version: Version::new(1, 0, 0),
1376            performance: PerformanceContract {
1377                time_complexity: ComplexityBound::Linear,
1378                space_complexity: ComplexityBound::Constant,
1379                maxexecution_time: Some(Duration::from_millis(100)),
1380                min_throughput: None,
1381                memorybandwidth: None,
1382            },
1383            numerical: NumericalContract {
1384                precision: PrecisionGuarantee::MachinePrecision,
1385                stability: NumericalStability::Stable,
1386                input_domain: InputDomain {
1387                    ranges: vec![(0.0, 1.0)],
1388                    exclusions: vec![],
1389                    special_values: SpecialValueHandling::Error,
1390                },
1391                output_range: OutputRange {
1392                    bounds: Some((0.0, 1.0)),
1393                    monotonic: Some(Monotonicity::NonDecreasing),
1394                    continuous: true,
1395                },
1396            },
1397            concurrency: ConcurrencyContract {
1398                thread_safety: ThreadSafety::ThreadSafe,
1399                atomicity: AtomicityGuarantee::OperationAtomic,
1400                lock_free: false,
1401                wait_free: false,
1402                memory_ordering: MemoryOrdering::AcquireRelease,
1403            },
1404            memory: MemoryContract {
1405                allocation_pattern: AllocationPattern::SingleAllocation,
1406                max_memory: Some(1024),
1407                alignment: Some(8),
1408                locality: LocalityGuarantee::GoodSpatial,
1409                gc_behavior: GcBehavior::MinimalGc,
1410            },
1411            deprecation: None,
1412        };
1413
1414        manager.register_contract(contract).unwrap();
1415
1416        let retrieved = manager.get_contract("test_function", "test_module");
1417        assert!(retrieved.is_some());
1418        assert_eq!(retrieved.unwrap().stability, StabilityLevel::Stable);
1419
1420        assert!(manager.has_stability_guarantees("test_function", "test_module"));
1421    }
1422
1423    #[test]
1424    fn test_usage_context_validation() {
1425        let mut manager = StabilityGuaranteeManager::new();
1426        manager.initialize_core_contracts().unwrap();
1427
1428        let context = UsageContext {
1429            required_stability: StabilityLevel::Stable,
1430            maxexecution_time: Some(Duration::from_millis(1)),
1431            requires_thread_safety: true,
1432            max_memory_usage: Some(2048),
1433            required_precision: Some(PrecisionGuarantee::Exact),
1434        };
1435
1436        // Should pass for core error type
1437        let result = manager.validate_usage("CoreError", "error", &context);
1438        assert!(result.is_ok());
1439    }
1440
1441    #[test]
1442    fn test_breaking_change_recording() {
1443        let mut manager = StabilityGuaranteeManager::new();
1444
1445        let change = BreakingChange {
1446            apiname: "test_function".to_string(),
1447            module: "test_module".to_string(),
1448            version: Version::new(2, 0, 0),
1449            change_type: BreakingChangeType::SignatureChange,
1450            description: "Added new parameter".to_string(),
1451            migration: Some("Use new parameter with default value".to_string()),
1452        };
1453
1454        manager.record_breaking_change(change);
1455
1456        assert_eq!(manager.breakingchanges.len(), 1);
1457        assert!(!manager.areversions_compatible(&Version::new(1, 9, 0), &Version::new(2, 0, 0)));
1458    }
1459
1460    #[test]
1461    fn test_version_compatibility() {
1462        let manager = StabilityGuaranteeManager::new();
1463
1464        // Same major version, newer minor - compatible
1465        assert!(manager.areversions_compatible(&Version::new(1, 0, 0), &Version::new(1, 1, 0)));
1466
1467        // Different major version - not compatible
1468        assert!(!manager.areversions_compatible(&Version::new(1, 0, 0), &Version::new(2, 0, 0)));
1469
1470        // Downgrade minor version - not compatible
1471        assert!(!manager.areversions_compatible(&Version::new(1, 1, 0), &Version::new(1, 0, 0)));
1472    }
1473
1474    #[test]
1475    fn test_stability_report_generation() {
1476        let mut manager = StabilityGuaranteeManager::new();
1477        manager.initialize_core_contracts().unwrap();
1478
1479        let report = manager.generate_stability_report();
1480
1481        assert!(report.contains("API Stability Report"));
1482        assert!(report.contains("Total APIs with contracts"));
1483        assert!(report.contains("Stable APIs"));
1484        assert!(report.contains("Module: error"));
1485        assert!(report.contains("CoreError"));
1486    }
1487
1488    #[test]
1489    fn test_global_stability_manager() {
1490        assert!(has_long_term_stability("CoreError", "error"));
1491        assert!(has_long_term_stability("check_finite", "validation"));
1492
1493        let context = UsageContext::default();
1494        let result = validate_stability_requirements("CoreError", "error", &context);
1495        assert!(result.is_ok());
1496    }
1497
1498    #[test]
1499    fn test_complexity_bounds() {
1500        let linear = ComplexityBound::Linear;
1501        let constant = ComplexityBound::Constant;
1502
1503        assert!(matches!(linear, ComplexityBound::Linear));
1504        assert!(matches!(constant, ComplexityBound::Constant));
1505    }
1506
1507    #[test]
1508    fn test_precision_guarantees() {
1509        let exact = PrecisionGuarantee::Exact;
1510        let machine = PrecisionGuarantee::MachinePrecision;
1511        let relative = PrecisionGuarantee::RelativeError(1e-15);
1512
1513        assert!(matches!(exact, PrecisionGuarantee::Exact));
1514        assert!(matches!(machine, PrecisionGuarantee::MachinePrecision));
1515
1516        if let PrecisionGuarantee::RelativeError(error) = relative {
1517            assert_eq!(error, 1e-15);
1518        }
1519    }
1520
1521    #[test]
1522    fn test_thread_safety_levels() {
1523        assert_eq!(ThreadSafety::ThreadSafe, ThreadSafety::ThreadSafe);
1524        assert_ne!(ThreadSafety::ThreadSafe, ThreadSafety::NotThreadSafe);
1525
1526        let immutable = ThreadSafety::Immutable;
1527        let read_safe = ThreadSafety::ReadSafe;
1528
1529        assert!(matches!(immutable, ThreadSafety::Immutable));
1530        assert!(matches!(read_safe, ThreadSafety::ReadSafe));
1531    }
1532}