optirs-tpu 0.3.1

OptiRS TPU coordination and pod management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// Clock Synchronization Module
//
// This module provides comprehensive clock synchronization capabilities for TPU pod coordination.
// The module is organized into focused sub-modules that handle different aspects of time synchronization:
//
// - [`core`] - Main synchronization manager and coordination logic
// - [`protocols`] - Synchronization protocols (NTP, PTP, GPS, etc.)
// - [`sources`] - Time source management and selection algorithms
// - [`gps`] - GPS signal processing and error correction
// - [`network`] - Network synchronization, messaging, and load balancing
// - [`quality`] - Quality monitoring and assessment
// - [`drift`] - Drift compensation and prediction
// - [`health`] - Health monitoring and recovery
// - [`statistics`] - Performance tracking and reporting
//
// # Architecture
//
// The clock synchronization system follows a modular architecture where each component
// has a specific responsibility but can work together to provide robust time synchronization:
//
// ```text
// ┌─────────────────────────────────────────────────────────────────┐
// │                    ClockSynchronizationManager                  │
// │                         (core module)                          │
// └─────────────────────────┬───────────────────────────────────────┘
//// ┌─────────────────────────┼───────────────────────────────────────┐
// │         TimeSourceManager        │        ProtocolManager        │
// │         (sources module)         │       (protocols module)      │
// └─────────────────────────┬───────┴───────┬───────────────────────┘
//                           │               │
// ┌─────────────────────────┼───────────────┼───────────────────────┐
// │      GPS Processing     │   Network     │    Quality & Health   │
// │      (gps module)       │  (network)    │  (quality & health)   │
// └─────────────────────────┼───────────────┼───────────────────────┘
//                           │               │
// ┌─────────────────────────┼───────────────┼───────────────────────┐
// │   Drift Compensation    │  Statistics   │      Reporting        │
// │     (drift module)      │ (statistics)  │    (statistics)       │
// └─────────────────────────┴───────────────┴───────────────────────┘
// ```
//
// # Usage
//
// Basic usage of the clock synchronization system:
//
// ```rust
// use crate::pod_coordination::synchronization::clocks::{
//     ClockSynchronizationManager, ClockSynchronizationConfig
// };
//
// # fn example() -> Result<(), Box<dyn std::error::Error>> {
// // Create synchronization manager with default configuration
// let mut sync_manager = ClockSynchronizationManager::new(
//     ClockSynchronizationConfig::default()
// )?;
//
// // Start synchronization
// sync_manager.start_synchronization()?;
//
// // Perform synchronization
// sync_manager.synchronize()?;
//
// // Get synchronization status
// let status = sync_manager.get_synchronization_status();
// println!("Sync status: {:?}", status);
//
// // Stop synchronization
// sync_manager.stop_synchronization()?;
// # Ok(())
// # }
// ```
//
// # Performance Considerations
//
// The clock synchronization system is designed for high-performance operation with:
// - Minimal latency overhead
// - Efficient memory usage
// - Scalable to large TPU clusters
// - Real-time operation capabilities
// - Adaptive algorithms for varying network conditions

// Core synchronization components
pub mod core;
pub mod protocols;
pub mod sources;

// Specialized synchronization modules
pub mod gps;
pub mod network;

// Monitoring and analysis modules
pub mod drift;
pub mod health;
pub mod quality;
pub mod statistics;

// Re-export main types from core module
pub use core::{
    ClockOffset, ClockSynchronizationConfig, ClockSynchronizationManager,
    ClockSynchronizationState, ClockSynchronizationStatus, ClockSynchronizer, SynchronizationEvent,
    SynchronizationResult,
};

// Re-export protocol types
pub use protocols::{
    BerkeleyConfig, ClockSyncProtocol, CristianConfig, CustomProtocolConfig, NtpConfig,
    NtpSynchronizer, ProtocolError, ProtocolManager, PtpConfig, PtpSynchronizer, SntpConfig,
    SntpSynchronizer,
};

// Re-export source management types
pub use sources::{
    AtomicClockType, ClockSource, RadioTimeStation, SourceSelectionAlgorithm,
    SourceSelectionCriteria, SourceValidation, SystemClockConfig, TimeSource, TimeSourceConfig,
    TimeSourceManager,
};

// Re-export GPS synchronization types
pub use gps::{
    AntennaConfig, GpsConfig, GpsError, GpsErrorCorrection, GpsReceiverType, GpsSignalProcessing,
    GpsSynchronizationManager, GpsTime, IonosphericCorrection, SatelliteClockCorrection,
    TroposphericCorrection,
};

// Re-export network synchronization types
pub use network::{
    LoadBalancingAlgorithm, MessagePassingConfig, MessagePriority, NetworkFaultTolerance,
    NetworkLoadBalancing, NetworkSyncConfig, NetworkSyncError, NetworkSynchronizationManager,
    NetworkTopology, SyncMessageType,
};

// Re-export quality monitoring types
pub use quality::{
    ClockAccuracyRequirements, ClockQualityMonitor, QualityAssessment, QualityGrade, QualityMetric,
    QualityMonitoringConfig, QualityRequirements, QualitySnapshot, QualityThresholds,
    SourceQualityMonitoring,
};

// Re-export drift compensation types
pub use drift::{
    DriftCompensationAlgorithm, DriftCompensationConfig, DriftCompensationError,
    DriftCompensationStatus, DriftCompensator, DriftMeasurement, DriftMeasurementConfig,
    DriftModel, DriftPredictionConfig, DriftPredictionEngine,
};

// Re-export health monitoring types
pub use health::{
    AlertConfiguration, AlertSeverity, HealthAlert, HealthCheck, HealthCheckType,
    HealthMonitorConfig, HealthMonitorError, HealthStatus, HealthThresholds, RecoveryConfiguration,
    SourceFailoverConfig, SourceHealthMonitor,
};

// Re-export statistics and reporting types
pub use statistics::{
    ClockStatistics, PerformanceHistory, PerformanceMeasurement, PerformanceReport,
    PerformanceTracking, QualityReporting, ReliabilityStatistics, ReportGeneration,
    StatisticsCollector, StatisticsError, TrendDirection,
};

// Convenience type aliases
pub type Result<T> = std::result::Result<T, ClockSynchronizationError>;
pub type Duration = std::time::Duration;
pub type Instant = std::time::Instant;

/// Main error type for clock synchronization operations
#[derive(Debug)]
pub enum ClockSynchronizationError {
    /// Core synchronization error
    CoreError(core::ClockSynchronizationError),
    /// Protocol error
    ProtocolError(protocols::ProtocolError),
    /// Source management error
    SourceError(sources::SourceManagementError),
    /// GPS synchronization error
    GpsError(gps::GpsError),
    /// Network synchronization error
    NetworkError(network::NetworkSyncError),
    /// Quality monitoring error
    QualityError(quality::QualityMonitorError),
    /// Drift compensation error
    DriftError(drift::DriftCompensationError),
    /// Health monitoring error
    HealthError(health::HealthMonitorError),
    /// Statistics error
    StatisticsError(statistics::StatisticsError),
    /// Configuration error
    ConfigurationError(String),
    /// System error
    SystemError(String),
}

impl std::fmt::Display for ClockSynchronizationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClockSynchronizationError::CoreError(e) => {
                write!(f, "Core synchronization error: {}", e)
            }
            ClockSynchronizationError::ProtocolError(e) => write!(f, "Protocol error: {}", e),
            ClockSynchronizationError::SourceError(e) => {
                write!(f, "Source management error: {}", e)
            }
            ClockSynchronizationError::GpsError(e) => write!(f, "GPS synchronization error: {}", e),
            ClockSynchronizationError::NetworkError(e) => {
                write!(f, "Network synchronization error: {}", e)
            }
            ClockSynchronizationError::QualityError(e) => {
                write!(f, "Quality monitoring error: {}", e)
            }
            ClockSynchronizationError::DriftError(e) => {
                write!(f, "Drift compensation error: {}", e)
            }
            ClockSynchronizationError::HealthError(e) => {
                write!(f, "Health monitoring error: {}", e)
            }
            ClockSynchronizationError::StatisticsError(e) => write!(f, "Statistics error: {}", e),
            ClockSynchronizationError::ConfigurationError(msg) => {
                write!(f, "Configuration error: {}", msg)
            }
            ClockSynchronizationError::SystemError(msg) => write!(f, "System error: {}", msg),
        }
    }
}

impl std::error::Error for ClockSynchronizationError {}

// Error conversions for seamless error handling
impl From<core::ClockSynchronizationError> for ClockSynchronizationError {
    fn from(err: core::ClockSynchronizationError) -> Self {
        ClockSynchronizationError::CoreError(err)
    }
}

impl From<protocols::ProtocolError> for ClockSynchronizationError {
    fn from(err: protocols::ProtocolError) -> Self {
        ClockSynchronizationError::ProtocolError(err)
    }
}

impl From<sources::SourceManagementError> for ClockSynchronizationError {
    fn from(err: sources::SourceManagementError) -> Self {
        ClockSynchronizationError::SourceError(err)
    }
}

impl From<gps::GpsError> for ClockSynchronizationError {
    fn from(err: gps::GpsError) -> Self {
        ClockSynchronizationError::GpsError(err)
    }
}

impl From<network::NetworkSyncError> for ClockSynchronizationError {
    fn from(err: network::NetworkSyncError) -> Self {
        ClockSynchronizationError::NetworkError(err)
    }
}

impl From<quality::QualityMonitorError> for ClockSynchronizationError {
    fn from(err: quality::QualityMonitorError) -> Self {
        ClockSynchronizationError::QualityError(err)
    }
}

impl From<drift::DriftCompensationError> for ClockSynchronizationError {
    fn from(err: drift::DriftCompensationError) -> Self {
        ClockSynchronizationError::DriftError(err)
    }
}

impl From<health::HealthMonitorError> for ClockSynchronizationError {
    fn from(err: health::HealthMonitorError) -> Self {
        ClockSynchronizationError::HealthError(err)
    }
}

impl From<statistics::StatisticsError> for ClockSynchronizationError {
    fn from(err: statistics::StatisticsError) -> Self {
        ClockSynchronizationError::StatisticsError(err)
    }
}

impl From<scirs2_core::CoreError> for ClockSynchronizationError {
    fn from(err: scirs2_core::CoreError) -> Self {
        ClockSynchronizationError::SystemError(err.to_string())
    }
}

/// Builder for configuring clock synchronization
///
/// Provides a fluent interface for configuring the various aspects
/// of clock synchronization with sensible defaults.
#[derive(Debug)]
pub struct ClockSynchronizationBuilder {
    core_config: Option<core::ClockSynchronizationConfig>,
    protocol_configs: Vec<protocols::ClockSyncProtocol>,
    source_configs: Vec<sources::TimeSource>,
    gps_config: Option<gps::GpsConfig>,
    network_config: Option<network::NetworkSyncConfig>,
    quality_config: Option<quality::QualityMonitoringConfig>,
    drift_config: Option<drift::DriftCompensationConfig>,
    health_config: Option<health::HealthMonitorConfig>,
    statistics_config: Option<statistics::StatisticsCollectionConfig>,
}

impl ClockSynchronizationBuilder {
    /// Create new builder with default configuration
    pub fn new() -> Self {
        Self {
            core_config: None,
            protocol_configs: Vec::new(),
            source_configs: Vec::new(),
            gps_config: None,
            network_config: None,
            quality_config: None,
            drift_config: None,
            health_config: None,
            statistics_config: None,
        }
    }

    /// Set core synchronization configuration
    pub fn with_core_config(mut self, config: core::ClockSynchronizationConfig) -> Self {
        self.core_config = Some(config);
        self
    }

    /// Add synchronization protocol
    pub fn with_protocol(mut self, protocol: protocols::ClockSyncProtocol) -> Self {
        self.protocol_configs.push(protocol);
        self
    }

    /// Add time source
    pub fn with_source(mut self, source: sources::TimeSource) -> Self {
        self.source_configs.push(source);
        self
    }

    /// Set GPS configuration
    pub fn with_gps_config(mut self, config: gps::GpsConfig) -> Self {
        self.gps_config = Some(config);
        self
    }

    /// Set network synchronization configuration
    pub fn with_network_config(mut self, config: network::NetworkSyncConfig) -> Self {
        self.network_config = Some(config);
        self
    }

    /// Set quality monitoring configuration
    pub fn with_quality_config(mut self, config: quality::QualityMonitoringConfig) -> Self {
        self.quality_config = Some(config);
        self
    }

    /// Set drift compensation configuration
    pub fn with_drift_config(mut self, config: drift::DriftCompensationConfig) -> Self {
        self.drift_config = Some(config);
        self
    }

    /// Set health monitoring configuration
    pub fn with_health_config(mut self, config: health::HealthMonitorConfig) -> Self {
        self.health_config = Some(config);
        self
    }

    /// Set statistics collection configuration
    pub fn with_statistics_config(
        mut self,
        config: statistics::StatisticsCollectionConfig,
    ) -> Self {
        self.statistics_config = Some(config);
        self
    }

    /// Build the clock synchronization manager
    pub fn build(self) -> Result<ClockSynchronizationManager> {
        let core_config = self.core_config.unwrap_or_default();

        // Create and configure the synchronization manager
        let mut manager = ClockSynchronizationManager::new();
        manager.config = core_config;

        // Configure protocols
        for protocol in self.protocol_configs {
            manager.add_protocol(protocol)?;
        }

        // Configure sources
        for source in self.source_configs {
            manager.add_time_source(source)?;
        }

        // Apply additional configurations
        if let Some(gps_config) = self.gps_config {
            manager.configure_gps(gps_config)?;
        }

        if let Some(network_config) = self.network_config {
            manager.configure_network(network_config)?;
        }

        if let Some(quality_config) = self.quality_config {
            manager.configure_quality_monitoring(quality_config)?;
        }

        if let Some(drift_config) = self.drift_config {
            manager.configure_drift_compensation(drift_config)?;
        }

        if let Some(health_config) = self.health_config {
            manager.configure_health_monitoring(health_config)?;
        }

        if let Some(statistics_config) = self.statistics_config {
            manager.configure_statistics(statistics_config)?;
        }

        Ok(manager)
    }
}

impl Default for ClockSynchronizationBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Utility functions for clock synchronization
pub mod utils {
    use super::*;

    /// Create a basic NTP-based synchronization setup
    pub fn create_ntp_sync_manager(
        ntp_servers: Vec<String>,
    ) -> Result<ClockSynchronizationManager> {
        let mut builder = ClockSynchronizationBuilder::new();

        // Add NTP protocol
        builder = builder.with_protocol(protocols::ClockSyncProtocol::NTP);

        // Add network time sources
        let source_count = builder.source_configs.len();
        for _ in 0..source_count {
            // Add NTP source
            let source = sources::TimeSource {
                source_type: sources::ClockSource::NTP,
            };
            builder = builder.with_source(source);
        }

        // Enable basic monitoring
        builder = builder.with_quality_config(quality::QualityMonitoringConfig::default());
        builder = builder.with_health_config(health::HealthMonitorConfig::default());

        builder.build()
    }

    /// Create a GPS-based synchronization setup
    pub fn create_gps_sync_manager(
        gps_config: gps::GpsConfig,
    ) -> Result<ClockSynchronizationManager> {
        let mut builder = ClockSynchronizationBuilder::new();

        // Add GPS configuration
        builder = builder.with_gps_config(gps_config.clone());

        // Add GPS time source
        let source = sources::TimeSource {
            source_type: sources::ClockSource::GPS,
        };
        builder = builder.with_source(source);

        // Enable comprehensive monitoring for GPS
        builder = builder.with_quality_config(quality::QualityMonitoringConfig::default());
        builder = builder.with_drift_config(drift::DriftCompensationConfig::default());
        builder = builder.with_health_config(health::HealthMonitorConfig::default());

        builder.build()
    }

    /// Create a high-precision synchronization setup
    pub fn create_precision_sync_manager() -> Result<ClockSynchronizationManager> {
        let mut builder = ClockSynchronizationBuilder::new();

        // Use PTP for high precision
        builder = builder.with_protocol(protocols::ClockSyncProtocol::PTP);

        // Add atomic clock source
        let source = sources::TimeSource {
            source_type: sources::ClockSource::Atomic,
        };
        builder = builder.with_source(source);

        // Enable all monitoring and compensation
        builder = builder.with_quality_config(quality::QualityMonitoringConfig::default());
        builder = builder.with_drift_config(drift::DriftCompensationConfig::default());
        builder = builder.with_health_config(health::HealthMonitorConfig::default());
        builder = builder.with_statistics_config(statistics::StatisticsCollectionConfig::default());

        builder.build()
    }

    /// Convert duration to human-readable string
    pub fn duration_to_string(duration: Duration) -> String {
        let total_seconds = duration.as_secs();
        let days = total_seconds / 86400;
        let hours = (total_seconds % 86400) / 3600;
        let minutes = (total_seconds % 3600) / 60;
        let seconds = total_seconds % 60;
        let millis = duration.subsec_millis();
        let micros = duration.subsec_micros() % 1000;
        let nanos = duration.subsec_nanos() % 1000;

        if days > 0 {
            format!("{}d {}h {}m {}s", days, hours, minutes, seconds)
        } else if hours > 0 {
            format!("{}h {}m {}s", hours, minutes, seconds)
        } else if minutes > 0 {
            format!("{}m {}s", minutes, seconds)
        } else if seconds > 0 {
            format!("{}.{:03}s", seconds, millis)
        } else if millis > 0 {
            format!("{}.{:03}ms", millis, micros)
        } else if micros > 0 {
            format!("{}.{:03}μs", micros, nanos)
        } else {
            format!("{}ns", nanos)
        }
    }

    /// Validate clock offset against requirements
    pub fn validate_clock_offset(
        offset: ClockOffset,
        requirements: &quality::ClockAccuracyRequirements,
    ) -> bool {
        offset.offset_ns.abs() as f64 <= requirements.max_drift_ppm
    }

    /// Calculate quality score from multiple metrics
    pub fn calculate_quality_score(metrics: &std::collections::HashMap<String, f64>) -> f64 {
        if metrics.is_empty() {
            return 0.0;
        }

        let sum: f64 = metrics.values().sum();
        sum / metrics.len() as f64
    }

    /// Get system uptime
    pub fn get_system_uptime() -> Duration {
        // This would be implemented to get actual system uptime
        // For now, return a placeholder
        Duration::from_secs(86400) // 1 day
    }
}

/// Prelude module for common imports
pub mod prelude {
    pub use super::{
        ClockOffset, ClockSynchronizationBuilder, ClockSynchronizationConfig,
        ClockSynchronizationError, ClockSynchronizationManager, Result,
    };

    pub use super::health::{AlertSeverity, HealthCheckType};
    pub use super::protocols::{ClockSyncProtocol, NtpConfig, PtpConfig};
    pub use super::quality::{QualityGrade, QualityMetric, TrendDirection};
    pub use super::sources::{AtomicClockType, ClockSource, TimeSource};
    pub use super::statistics::{PerformanceMetric, ReportFormat};
    pub use super::utils;
}

// Module-level documentation tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_pattern() {
        let builder =
            ClockSynchronizationBuilder::new().with_protocol(protocols::ClockSyncProtocol::NTP);

        // Builder should be constructible
        assert!(builder.protocol_configs.len() == 1);
    }

    #[test]
    fn test_error_conversions() {
        let core_error = core::ClockSynchronizationError;
        let sync_error: ClockSynchronizationError = core_error.into();

        // The conversion should work
        match sync_error {
            ClockSynchronizationError::CoreError(_) => {}
            _ => panic!("Error conversion failed"),
        }
    }

    #[test]
    fn test_utility_functions() {
        // Test duration formatting
        let duration = Duration::from_millis(1500);
        let formatted = utils::duration_to_string(duration);
        assert!(formatted.contains("s"));

        // Test quality score calculation
        let mut metrics = std::collections::HashMap::new();
        metrics.insert("accuracy".to_string(), 0.9);
        metrics.insert("stability".to_string(), 0.8);
        let score = utils::calculate_quality_score(&metrics);
        assert!((score - 0.85).abs() < 1e-10);
    }
}