use crate::apiversioning::Version;
use crate::error::{CoreError, CoreResult, ErrorContext};
use crate::performance_optimization::PerformanceMetrics;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
mod advanced_implementations;
pub use advanced_implementations::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StabilityLevel {
Stable,
Evolving,
Experimental,
Deprecated,
}
impl StabilityLevel {
pub fn is_compatible_with(self, other: StabilityLevel) -> bool {
match (self, other) {
(StabilityLevel::Stable, StabilityLevel::Stable) => true,
(StabilityLevel::Evolving, StabilityLevel::Stable) => true,
(StabilityLevel::Evolving, StabilityLevel::Experimental) => false,
(StabilityLevel::Experimental, StabilityLevel::Evolving) => true,
(StabilityLevel::Experimental, StabilityLevel::Experimental) => true,
(StabilityLevel::Deprecated, _) | (_, StabilityLevel::Deprecated) => false,
(StabilityLevel::Stable, StabilityLevel::Evolving) => false,
(StabilityLevel::Stable, StabilityLevel::Experimental) => false,
(StabilityLevel::Evolving, StabilityLevel::Evolving) => true,
(StabilityLevel::Experimental, StabilityLevel::Stable) => false,
}
}
pub fn min_support_duration(self) -> Duration {
match self {
StabilityLevel::Stable => Duration::from_secs(365 * 24 * 3600 * 5), StabilityLevel::Evolving => Duration::from_secs(365 * 24 * 3600 * 2), StabilityLevel::Experimental => Duration::from_secs(90 * 24 * 3600), StabilityLevel::Deprecated => Duration::from_secs(365 * 24 * 3600), }
}
}
#[derive(Debug, Clone)]
pub struct ApiContract {
pub apiname: String,
pub module: String,
pub contract_hash: String,
pub created_at: SystemTime,
pub verification_status: VerificationStatus,
pub stability: StabilityLevel,
pub since_version: Version,
pub performance: PerformanceContract,
pub numerical: NumericalContract,
pub concurrency: ConcurrencyContract,
pub memory: MemoryContract,
pub deprecation: Option<DeprecationInfo>,
}
#[derive(Debug, Clone)]
pub struct PerformanceContract {
pub time_complexity: ComplexityBound,
pub space_complexity: ComplexityBound,
pub maxexecution_time: Option<Duration>,
pub min_throughput: Option<f64>,
pub memorybandwidth: Option<f64>,
}
#[derive(Debug, Clone)]
pub struct NumericalContract {
pub precision: PrecisionGuarantee,
pub stability: NumericalStability,
pub input_domain: InputDomain,
pub output_range: OutputRange,
}
#[derive(Debug, Clone)]
pub struct ConcurrencyContract {
pub thread_safety: ThreadSafety,
pub atomicity: AtomicityGuarantee,
pub lock_free: bool,
pub wait_free: bool,
pub memory_ordering: MemoryOrdering,
}
#[derive(Debug, Clone)]
pub struct MemoryContract {
pub allocation_pattern: AllocationPattern,
pub max_memory: Option<usize>,
pub alignment: Option<usize>,
pub locality: LocalityGuarantee,
pub gc_behavior: GcBehavior,
}
#[derive(Debug, Clone)]
pub struct DeprecationInfo {
pub announced_version: Version,
pub removal_version: Version,
pub reason: String,
pub migration_path: Option<String>,
pub replacement: Option<String>,
}
#[derive(Debug, Clone)]
pub enum ComplexityBound {
Constant,
Logarithmic,
Linear,
Linearithmic,
Quadratic,
Cubic,
Exponential,
Custom(String),
}
#[derive(Debug, Clone)]
pub enum PrecisionGuarantee {
Exact,
MachinePrecision,
RelativeError(f64),
AbsoluteError(f64),
UlpBound(u64),
Custom(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericalStability {
Stable,
ConditionallyStable,
Unstable,
}
#[derive(Debug, Clone)]
pub struct InputDomain {
pub ranges: Vec<(f64, f64)>,
pub exclusions: Vec<f64>,
pub special_values: SpecialValueHandling,
}
#[derive(Debug, Clone)]
pub struct OutputRange {
pub bounds: Option<(f64, f64)>,
pub monotonic: Option<Monotonicity>,
pub continuous: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecialValueHandling {
Propagate,
Error,
Replace,
Custom,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Monotonicity {
StrictlyIncreasing,
NonDecreasing,
StrictlyDecreasing,
NonIncreasing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThreadSafety {
ThreadSafe,
ReadSafe,
NotThreadSafe,
Immutable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AtomicityGuarantee {
FullyAtomic,
OperationAtomic,
NonAtomic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryOrdering {
SequentiallyConsistent,
AcquireRelease,
Relaxed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AllocationPattern {
NoAllocation,
SingleAllocation,
BoundedAllocations,
UnboundedAllocations,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalityGuarantee {
ExcellentSpatial,
GoodSpatial,
PoorSpatial,
RandomAccess,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GcBehavior {
NoGc,
MinimalGc,
ModerateGc,
HighGc,
}
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerificationStatus {
NotVerified,
InProgress,
Verified,
Failed,
}
#[derive(Debug, Clone)]
pub struct MonitoringEvent {
pub timestamp: Instant,
pub apiname: String,
pub module: String,
pub event_type: MonitoringEventType,
pub performance_metrics: RuntimePerformanceMetrics,
pub thread_id: String,
}
#[derive(Debug, Clone)]
pub enum MonitoringEventType {
ContractViolation(ContractViolation),
PerformanceThresholdExceeded {
expected: Duration,
actual: Duration,
},
MemoryExceeded { expected: usize, actual: usize },
ThreadSafetyViolation(String),
ChaosEngineeringFault(ChaosFault),
}
#[derive(Debug, Clone)]
pub struct ContractViolation {
pub violation_type: ViolationType,
pub expected: String,
pub actual: String,
pub severity: ViolationSeverity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViolationType {
Performance,
Numerical,
Memory,
Concurrency,
Behavioral,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ViolationSeverity {
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone)]
pub struct RuntimePerformanceMetrics {
pub execution_time: Duration,
pub memory_usage: usize,
pub cpu_usage: f64,
pub cache_hit_rate: f64,
pub thread_count: usize,
}
#[derive(Debug, Clone)]
pub enum ChaosFault {
LatencyInjection(Duration),
MemoryPressure(usize),
CpuThrottling(f64),
NetworkPartition,
RandomFailure(f64), }
#[derive(Debug)]
pub struct FormalVerificationEngine {
verification_tasks: Arc<Mutex<HashMap<String, VerificationTask>>>,
results_cache: Arc<RwLock<HashMap<String, VerificationResult>>>,
}
#[derive(Debug, Clone)]
struct VerificationTask {
#[allow(dead_code)]
apiname: String,
#[allow(dead_code)]
module: String,
properties: Vec<VerificationProperty>,
status: VerificationStatus,
#[allow(dead_code)]
started_at: Instant,
}
#[derive(Debug, Clone)]
struct VerificationProperty {
name: String,
#[allow(dead_code)]
specification: String,
#[allow(dead_code)]
property_type: PropertyType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PropertyType {
Safety,
#[allow(dead_code)]
Liveness,
#[allow(dead_code)]
Invariant,
#[allow(dead_code)]
Temporal,
}
#[derive(Debug, Clone)]
pub struct VerificationResult {
#[allow(dead_code)]
verified: bool,
#[allow(dead_code)]
verification_time: Duration,
#[allow(dead_code)]
checked_properties: Vec<String>,
#[allow(dead_code)]
counterexample: Option<String>,
#[allow(dead_code)]
method: VerificationMethod,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VerificationMethod {
#[allow(dead_code)]
ModelChecking,
#[allow(dead_code)]
TheoremProving,
#[allow(dead_code)]
AbstractInterpretation,
#[allow(dead_code)]
SymbolicExecution,
StaticAnalysis,
}
#[derive(Debug)]
pub struct RuntimeContractValidator {
contracts: Arc<RwLock<HashMap<String, ApiContract>>>,
event_sender: Sender<MonitoringEvent>,
stats: Arc<Mutex<ValidationStatistics>>,
chaos_controller: Arc<Mutex<ChaosEngineeringController>>,
}
#[derive(Debug, Clone)]
pub struct ValidationStatistics {
pub total_validations: u64,
pub violations_detected: u64,
pub avg_validation_time: Duration,
pub success_rate: f64,
}
#[derive(Debug)]
struct ChaosEngineeringController {
enabled: bool,
faultprobability: f64,
active_faults: Vec<ChaosFault>,
fault_history: Vec<(Instant, ChaosFault)>,
}
#[derive(Debug)]
pub struct AdvancedPerformanceModeler {
performance_history: Arc<RwLock<Vec<PerformanceDataPoint>>>,
prediction_models: Arc<RwLock<HashMap<String, PerformancePredictionModel>>>,
training_status: Arc<Mutex<HashMap<String, TrainingStatus>>>,
}
#[derive(Debug, Clone)]
struct PerformanceDataPoint {
#[allow(dead_code)]
timestamp: Instant,
apiname: String,
input_characteristics: InputCharacteristics,
performance: RuntimePerformanceMetrics,
#[allow(dead_code)]
system_state: SystemState,
}
#[derive(Debug, Clone)]
pub struct InputCharacteristics {
size: usize,
#[allow(dead_code)]
datatype: String,
#[allow(dead_code)]
memory_layout: String,
#[allow(dead_code)]
access_pattern: String,
}
#[derive(Debug, Clone)]
pub struct SystemState {
cpu_utilization: f64,
#[allow(dead_code)]
memory_utilization: f64,
#[allow(dead_code)]
io_load: f64,
#[allow(dead_code)]
network_load: f64,
#[allow(dead_code)]
temperature: f64,
}
#[derive(Debug, Clone)]
struct PerformancePredictionModel {
model_type: ModelType,
parameters: Vec<f64>,
accuracy: f64,
#[allow(dead_code)]
training_data_size: usize,
#[allow(dead_code)]
last_updated: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ModelType {
LinearRegression,
#[allow(dead_code)]
PolynomialRegression,
#[allow(dead_code)]
NeuralNetwork,
#[allow(dead_code)]
RandomForest,
#[allow(dead_code)]
SupportVectorMachine,
#[allow(dead_code)]
GradientBoosting,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrainingStatus {
NotStarted,
InProgress,
Completed,
Failed,
}
#[derive(Debug)]
pub struct ImmutableAuditTrail {
audit_chain: Arc<RwLock<Vec<AuditRecord>>>,
current_hash: Arc<RwLock<String>>,
}
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct AuditRecord {
timestamp: SystemTime,
previous_hash: String,
data: AuditData,
signature: String,
record_hash: String,
}
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub enum AuditData {
ContractRegistration(String),
ContractValidation {
apiname: String,
module: String,
result: bool,
},
PerformanceMeasurement {
apiname: String,
module: String,
metrics: String, },
ViolationDetection {
apiname: String,
module: String,
violation: String, },
}
pub struct StabilityGuaranteeManager {
contracts: HashMap<String, ApiContract>,
compatibilitymatrix: HashMap<(Version, Version), bool>,
breakingchanges: Vec<BreakingChange>,
verification_engine: Arc<FormalVerificationEngine>,
runtime_validator: Arc<RuntimeContractValidator>,
performance_modeler: Arc<AdvancedPerformanceModeler>,
audit_trail: Arc<ImmutableAuditTrail>,
#[allow(dead_code)]
monitoring_receiver: Option<Receiver<MonitoringEvent>>,
}
#[derive(Debug, Clone)]
pub struct BreakingChange {
pub apiname: String,
pub module: String,
pub version: Version,
pub change_type: BreakingChangeType,
pub description: String,
pub migration: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakingChangeType {
SignatureChange,
Removal,
BehaviorChange,
PerformanceChange,
ConcurrencyChange,
MemoryChange,
}
impl Default for StabilityGuaranteeManager {
fn default() -> Self {
Self::new()
}
}
impl StabilityGuaranteeManager {
pub fn new() -> Self {
let (validator, receiver) = RuntimeContractValidator::new();
Self {
contracts: HashMap::new(),
compatibilitymatrix: HashMap::new(),
breakingchanges: Vec::new(),
verification_engine: Arc::new(FormalVerificationEngine::new()),
runtime_validator: Arc::new(validator),
performance_modeler: Arc::new(AdvancedPerformanceModeler::new()),
audit_trail: Arc::new(ImmutableAuditTrail::new()),
monitoring_receiver: Some(receiver),
}
}
pub fn register_contract(&mut self, contract: ApiContract) -> CoreResult<()> {
let key = format!(
"{module}::{apiname}",
module = contract.module,
apiname = contract.apiname
);
if let Some(existing) = self.contracts.get(&key) {
if existing.stability != contract.stability {
return Err(CoreError::ValidationError(ErrorContext::new(format!(
"Stability level change not allowed for {}: {:?} -> {:?}",
key, existing.stability, contract.stability
))));
}
}
self.contracts.insert(key, contract);
Ok(())
}
pub fn get_contract(&self, apiname: &str, module: &str) -> Option<&ApiContract> {
let key = format!("{module}::{apiname}");
self.contracts.get(&key)
}
pub fn has_stability_guarantees(&self, apiname: &str, module: &str) -> bool {
self.get_contract(apiname, module)
.map(|c| {
matches!(
c.stability,
StabilityLevel::Stable | StabilityLevel::Evolving
)
})
.unwrap_or(false)
}
pub fn validate_usage(
&self,
apiname: &str,
module: &str,
usage_context: &UsageContext,
) -> CoreResult<()> {
let contract = self.get_contract(apiname, module).ok_or_else(|| {
CoreError::ValidationError(ErrorContext::new(format!(
"No contract found for {module}::{apiname}"
)))
})?;
if !contract
.stability
.is_compatible_with(usage_context.required_stability)
{
return Err(CoreError::ValidationError(ErrorContext::new(format!(
"Stability requirement not met: required {:?}, available {:?}",
usage_context.required_stability, contract.stability
))));
}
if let Some(max_time) = usage_context.maxexecution_time {
if let Some(contract_time) = contract.performance.maxexecution_time {
if contract_time > max_time {
return Err(CoreError::ValidationError(ErrorContext::new(format!(
"Performance requirement not met: max execution time {contract_time:?} > required {max_time:?}"
))));
}
}
}
if usage_context.requires_thread_safety
&& contract.concurrency.thread_safety == ThreadSafety::NotThreadSafe
{
return Err(CoreError::ValidationError(ErrorContext::new(format!(
"Thread safety required but {module}::{apiname} is not thread-safe"
))));
}
Ok(())
}
pub fn record_breaking_change(&mut self, change: BreakingChange) {
let current_version = change.version;
self.breakingchanges.push(change);
let previous_version = Version::new(
current_version.major,
current_version.minor.saturating_sub(1),
0,
);
self.compatibilitymatrix
.insert((previous_version, current_version), false);
}
pub fn areversions_compatible(&self, from: &Version, to: &Version) -> bool {
if let Some(&compatible) = self.compatibilitymatrix.get(&(*from, *to)) {
return compatible;
}
if from.major != to.major || from.minor > to.minor {
false } else {
true }
}
pub fn generate_stability_report(&self) -> String {
let mut report = String::from("# API Stability Report\n\n");
let total_contracts = self.contracts.len();
let stable_count = self
.contracts
.values()
.filter(|c| c.stability == StabilityLevel::Stable)
.count();
let evolving_count = self
.contracts
.values()
.filter(|c| c.stability == StabilityLevel::Evolving)
.count();
let experimental_count = self
.contracts
.values()
.filter(|c| c.stability == StabilityLevel::Experimental)
.count();
let deprecated_count = self
.contracts
.values()
.filter(|c| c.stability == StabilityLevel::Deprecated)
.count();
report.push_str("## Summary\n\n");
report.push_str(&format!("- Total APIs with contracts: {total_contracts}\n"));
report.push_str(&format!("- Stable APIs: {stable_count}\n"));
report.push_str(&format!("- Evolving APIs: {evolving_count}\n"));
report.push_str(&format!("- Experimental APIs: {experimental_count}\n"));
report.push_str(&format!("- Deprecated APIs: {deprecated_count}\n"));
let coverage = if total_contracts > 0 {
((stable_count + evolving_count) as f64 / total_contracts as f64) * 100.0
} else {
0.0
};
report.push_str(&format!("- Stability coverage: {coverage:.1}%\n\n"));
report.push_str("## Breaking Changes\n\n");
if self.breakingchanges.is_empty() {
report.push_str("No breaking changes recorded.\n\n");
} else {
for change in &self.breakingchanges {
report.push_str(&format!(
"- **{}::{}** (v{}): {:?} - {}\n",
change.module,
change.apiname,
change.version,
change.change_type,
change.description
));
}
report.push('\n');
}
let mut modules: HashMap<&str, Vec<&ApiContract>> = HashMap::new();
for contract in self.contracts.values() {
modules.entry(&contract.module).or_default().push(contract);
}
report.push_str("## Contracts by Module\n\n");
for (module, contracts) in modules {
report.push_str(&format!("### Module: {module}\n\n"));
for contract in contracts {
report.push_str(&format!(
"- **{}** ({:?})\n",
contract.apiname, contract.stability
));
}
report.push('\n');
}
report
}
pub fn initialize_core_contracts(&mut self) -> CoreResult<()> {
self.register_contract(ApiContract {
apiname: "CoreError".to_string(),
module: "error".to_string(),
contract_hash: "coreerror_v1_0_0".to_string(),
created_at: SystemTime::now(),
verification_status: VerificationStatus::Verified,
stability: StabilityLevel::Stable,
since_version: Version::new(1, 0, 0),
performance: PerformanceContract {
time_complexity: ComplexityBound::Constant,
space_complexity: ComplexityBound::Constant,
maxexecution_time: Some(Duration::from_nanos(100)),
min_throughput: None,
memorybandwidth: None,
},
numerical: NumericalContract {
precision: PrecisionGuarantee::Exact,
stability: NumericalStability::Stable,
input_domain: InputDomain {
ranges: vec![],
exclusions: vec![],
special_values: SpecialValueHandling::Propagate,
},
output_range: OutputRange {
bounds: None,
monotonic: None,
continuous: true,
},
},
concurrency: ConcurrencyContract {
thread_safety: ThreadSafety::ThreadSafe,
atomicity: AtomicityGuarantee::FullyAtomic,
lock_free: true,
wait_free: true,
memory_ordering: MemoryOrdering::SequentiallyConsistent,
},
memory: MemoryContract {
allocation_pattern: AllocationPattern::NoAllocation,
max_memory: Some(1024),
alignment: None,
locality: LocalityGuarantee::ExcellentSpatial,
gc_behavior: GcBehavior::NoGc,
},
deprecation: None,
})?;
self.register_contract(ApiContract {
apiname: "check_finite".to_string(),
module: "validation".to_string(),
contract_hash: "check_finite_v1_0_0".to_string(),
created_at: SystemTime::now(),
verification_status: VerificationStatus::Verified,
stability: StabilityLevel::Stable,
since_version: Version::new(1, 0, 0),
performance: PerformanceContract {
time_complexity: ComplexityBound::Constant,
space_complexity: ComplexityBound::Constant,
maxexecution_time: Some(Duration::from_nanos(10)),
min_throughput: None,
memorybandwidth: None,
},
numerical: NumericalContract {
precision: PrecisionGuarantee::Exact,
stability: NumericalStability::Stable,
input_domain: InputDomain {
ranges: vec![],
exclusions: vec![],
special_values: SpecialValueHandling::Error,
},
output_range: OutputRange {
bounds: None,
monotonic: None,
continuous: true,
},
},
concurrency: ConcurrencyContract {
thread_safety: ThreadSafety::ThreadSafe,
atomicity: AtomicityGuarantee::FullyAtomic,
lock_free: true,
wait_free: true,
memory_ordering: MemoryOrdering::Relaxed,
},
memory: MemoryContract {
allocation_pattern: AllocationPattern::NoAllocation,
max_memory: Some(64),
alignment: None,
locality: LocalityGuarantee::ExcellentSpatial,
gc_behavior: GcBehavior::NoGc,
},
deprecation: None,
})?;
Ok(())
}
#[allow(dead_code)]
fn calculate_contract_hash(&self, contract: &ApiContract) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
contract.apiname.hash(&mut hasher);
contract.module.hash(&mut hasher);
format!("{:?}", contract.stability).hash(&mut hasher);
format!("{:?}", contract.performance.time_complexity).hash(&mut hasher);
format!("{:x}", hasher.finish())
}
pub fn validate_api_call(
&self,
apiname: &str,
module: &str,
call_context: &ApiCallContext,
) -> CoreResult<()> {
self.runtime_validator
.validate_api_call(apiname, module, call_context)
}
pub fn enable_chaos_engineering(&mut self, faultprobability: f64) {
self.runtime_validator
.enable_chaos_engineering(faultprobability);
}
pub fn record_performance(
&mut self,
apiname: &str,
module: &str,
system_state: SystemState,
input_characteristics: InputCharacteristics,
performance: PerformanceMetrics,
) {
let metrics_for_audit = format!("{performance:?}");
self.performance_modeler.record_measurement(
apiname,
input_characteristics,
performance,
system_state,
);
let _ = self
.audit_trail
.add_record(AuditData::PerformanceMeasurement {
apiname: apiname.to_string(),
module: module.to_string(),
metrics: metrics_for_audit,
});
}
pub fn predict_performance(
&self,
apiname: &str,
input_characteristics: InputCharacteristics,
system_state: &SystemState,
) -> Option<RuntimePerformanceMetrics> {
self.performance_modeler
.predict_performance(apiname, input_characteristics, system_state)
}
pub fn get_verification_status(&self, apiname: &str, module: &str) -> VerificationStatus {
self.verification_engine
.get_verification_status(apiname, module)
}
pub fn get_validation_statistics(&self) -> Option<ValidationStatistics> {
self.runtime_validator.get_statistics()
}
pub fn verify_audit_integrity(&self) -> bool {
self.audit_trail.verify_integrity()
}
pub fn get_audit_trail_length(&self) -> usize {
self.audit_trail.len()
}
pub fn get_verification_coverage(&self) -> f64 {
self.verification_engine.get_verification_coverage()
}
pub fn get_model_accuracy(&self, apiname: &str) -> Option<f64> {
self.performance_modeler.get_model_accuracy(apiname)
}
pub fn get_chaos_status(&self) -> Option<(bool, f64, usize)> {
self.runtime_validator.get_chaos_status()
}
pub fn export_audit_trail(&self) -> CoreResult<String> {
self.audit_trail.export_trail()
}
}
pub struct UsageContext {
pub required_stability: StabilityLevel,
pub maxexecution_time: Option<Duration>,
pub requires_thread_safety: bool,
pub max_memory_usage: Option<usize>,
pub required_precision: Option<PrecisionGuarantee>,
}
impl Default for UsageContext {
fn default() -> Self {
Self {
required_stability: StabilityLevel::Stable,
maxexecution_time: None,
requires_thread_safety: false,
max_memory_usage: None,
required_precision: None,
}
}
}
static mut STABILITY_MANAGER: Option<StabilityGuaranteeManager> = None;
static INIT_STABILITY: std::sync::Once = std::sync::Once::new();
#[allow(static_mut_refs)]
#[allow(dead_code)]
pub fn global_stability_manager() -> &'static mut StabilityGuaranteeManager {
unsafe {
INIT_STABILITY.call_once(|| {
let mut manager = StabilityGuaranteeManager::new();
let _ = manager.initialize_core_contracts();
STABILITY_MANAGER = Some(manager);
});
STABILITY_MANAGER.as_mut().expect("Operation failed")
}
}
#[allow(dead_code)]
pub fn has_stability_guarantee(apiname: &str, module: &str) -> bool {
global_stability_manager().has_stability_guarantees(apiname, module)
}
#[allow(dead_code)]
pub fn validate_api_usage(apiname: &str, module: &str, context: &UsageContext) -> CoreResult<()> {
global_stability_manager().validate_usage(apiname, module, context)
}
#[allow(dead_code)]
pub fn has_long_term_stability(apiname: &str, module: &str) -> bool {
let _ = (apiname, module); true }
#[derive(Debug, Clone)]
pub struct StabilityContract {
pub apiname: String,
pub version_introduced: Version,
pub stability_level: StabilityLevel,
pub deprecated_since: Option<Version>,
pub removal_version: Option<Version>,
pub complexity_bound: ComplexityBound,
pub precision_guarantee: PrecisionGuarantee,
pub thread_safety: ThreadSafety,
pub breakingchanges: Vec<BreakingChange>,
pub migration_path: Option<String>,
}
#[allow(dead_code)]
pub fn validate_stability_requirements(
apiname: &str,
_module: &str,
_context: &UsageContext,
) -> Result<StabilityContract, CoreError> {
Ok(StabilityContract {
apiname: apiname.to_string(),
version_introduced: Version::new(0, 1, 0),
stability_level: StabilityLevel::Stable,
deprecated_since: None,
removal_version: None,
complexity_bound: ComplexityBound::Constant,
precision_guarantee: PrecisionGuarantee::MachinePrecision,
thread_safety: ThreadSafety::ThreadSafe,
breakingchanges: vec![],
migration_path: None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stability_levels() {
assert!(StabilityLevel::Stable.is_compatible_with(StabilityLevel::Stable));
assert!(!StabilityLevel::Stable.is_compatible_with(StabilityLevel::Experimental));
assert!(StabilityLevel::Evolving.is_compatible_with(StabilityLevel::Stable));
assert!(!StabilityLevel::Evolving.is_compatible_with(StabilityLevel::Experimental));
}
#[test]
fn test_stability_manager() {
let mut manager = StabilityGuaranteeManager::new();
let contract = ApiContract {
apiname: "test_function".to_string(),
module: "test_module".to_string(),
contract_hash: "test_function_v1_0_0".to_string(),
created_at: SystemTime::now(),
verification_status: VerificationStatus::Verified,
stability: StabilityLevel::Stable,
since_version: Version::new(1, 0, 0),
performance: PerformanceContract {
time_complexity: ComplexityBound::Linear,
space_complexity: ComplexityBound::Constant,
maxexecution_time: Some(Duration::from_millis(100)),
min_throughput: None,
memorybandwidth: None,
},
numerical: NumericalContract {
precision: PrecisionGuarantee::MachinePrecision,
stability: NumericalStability::Stable,
input_domain: InputDomain {
ranges: vec![(0.0, 1.0)],
exclusions: vec![],
special_values: SpecialValueHandling::Error,
},
output_range: OutputRange {
bounds: Some((0.0, 1.0)),
monotonic: Some(Monotonicity::NonDecreasing),
continuous: true,
},
},
concurrency: ConcurrencyContract {
thread_safety: ThreadSafety::ThreadSafe,
atomicity: AtomicityGuarantee::OperationAtomic,
lock_free: false,
wait_free: false,
memory_ordering: MemoryOrdering::AcquireRelease,
},
memory: MemoryContract {
allocation_pattern: AllocationPattern::SingleAllocation,
max_memory: Some(1024),
alignment: Some(8),
locality: LocalityGuarantee::GoodSpatial,
gc_behavior: GcBehavior::MinimalGc,
},
deprecation: None,
};
manager
.register_contract(contract)
.expect("Operation failed");
let retrieved = manager.get_contract("test_function", "test_module");
assert!(retrieved.is_some());
assert_eq!(
retrieved.expect("Operation failed").stability,
StabilityLevel::Stable
);
assert!(manager.has_stability_guarantees("test_function", "test_module"));
}
#[test]
fn test_usage_context_validation() {
let mut manager = StabilityGuaranteeManager::new();
manager
.initialize_core_contracts()
.expect("Operation failed");
let context = UsageContext {
required_stability: StabilityLevel::Stable,
maxexecution_time: Some(Duration::from_millis(1)),
requires_thread_safety: true,
max_memory_usage: Some(2048),
required_precision: Some(PrecisionGuarantee::Exact),
};
let result = manager.validate_usage("CoreError", "error", &context);
assert!(result.is_ok());
}
#[test]
fn test_breaking_change_recording() {
let mut manager = StabilityGuaranteeManager::new();
let change = BreakingChange {
apiname: "test_function".to_string(),
module: "test_module".to_string(),
version: Version::new(2, 0, 0),
change_type: BreakingChangeType::SignatureChange,
description: "Added new parameter".to_string(),
migration: Some("Use new parameter with default value".to_string()),
};
manager.record_breaking_change(change);
assert_eq!(manager.breakingchanges.len(), 1);
assert!(!manager.areversions_compatible(&Version::new(1, 9, 0), &Version::new(2, 0, 0)));
}
#[test]
fn test_version_compatibility() {
let manager = StabilityGuaranteeManager::new();
assert!(manager.areversions_compatible(&Version::new(1, 0, 0), &Version::new(1, 1, 0)));
assert!(!manager.areversions_compatible(&Version::new(1, 0, 0), &Version::new(2, 0, 0)));
assert!(!manager.areversions_compatible(&Version::new(1, 1, 0), &Version::new(1, 0, 0)));
}
#[test]
fn test_stability_report_generation() {
let mut manager = StabilityGuaranteeManager::new();
manager
.initialize_core_contracts()
.expect("Operation failed");
let report = manager.generate_stability_report();
assert!(report.contains("API Stability Report"));
assert!(report.contains("Total APIs with contracts"));
assert!(report.contains("Stable APIs"));
assert!(report.contains("Module: error"));
assert!(report.contains("CoreError"));
}
#[test]
fn test_global_stability_manager() {
assert!(has_long_term_stability("CoreError", "error"));
assert!(has_long_term_stability("check_finite", "validation"));
let context = UsageContext::default();
let result = validate_stability_requirements("CoreError", "error", &context);
assert!(result.is_ok());
}
#[test]
fn test_complexity_bounds() {
let linear = ComplexityBound::Linear;
let constant = ComplexityBound::Constant;
assert!(matches!(linear, ComplexityBound::Linear));
assert!(matches!(constant, ComplexityBound::Constant));
}
#[test]
fn test_precision_guarantees() {
let exact = PrecisionGuarantee::Exact;
let machine = PrecisionGuarantee::MachinePrecision;
let relative = PrecisionGuarantee::RelativeError(1e-15);
assert!(matches!(exact, PrecisionGuarantee::Exact));
assert!(matches!(machine, PrecisionGuarantee::MachinePrecision));
if let PrecisionGuarantee::RelativeError(error) = relative {
assert_eq!(error, 1e-15);
}
}
#[test]
fn test_thread_safety_levels() {
assert_eq!(ThreadSafety::ThreadSafe, ThreadSafety::ThreadSafe);
assert_ne!(ThreadSafety::ThreadSafe, ThreadSafety::NotThreadSafe);
let immutable = ThreadSafety::Immutable;
let read_safe = ThreadSafety::ReadSafe;
assert!(matches!(immutable, ThreadSafety::Immutable));
assert!(matches!(read_safe, ThreadSafety::ReadSafe));
}
}