Skip to main content

optirs_nas/evaluation/
resource.rs

1//! Resource monitoring for evaluation
2//!
3//! Tracks memory, CPU, GPU usage and other resources during evaluation.
4
5use scirs2_core::numeric::Float;
6use std::collections::{HashMap, VecDeque};
7use std::fmt::Debug;
8use std::time::SystemTime;
9
10use crate::error::Result;
11use crate::ResourceUsage;
12
13/// Resource monitor for tracking evaluation resources
14#[derive(Debug)]
15pub struct ResourceMonitor<T: Float + Debug + Send + Sync + 'static> {
16    /// Current resource usage
17    current_usage: ResourceUsage<T>,
18
19    /// Resource usage history
20    usage_history: VecDeque<ResourceUsageSnapshot<T>>,
21
22    /// Resource limits
23    limits: ResourceLimits<T>,
24
25    /// Monitoring configuration
26    config: MonitoringConfig,
27}
28
29/// Resource usage snapshot
30#[derive(Debug, Clone)]
31pub struct ResourceUsageSnapshot<T: Float + Debug + Send + Sync + 'static> {
32    /// Timestamp
33    pub timestamp: SystemTime,
34
35    /// Memory usage (MB)
36    pub memory_mb: T,
37
38    /// CPU usage (%)
39    pub cpu_usage_percent: T,
40
41    /// GPU usage (%)
42    pub gpu_usage_percent: T,
43
44    /// Network I/O (MB/s)
45    pub network_io_mbps: T,
46
47    /// Disk I/O (MB/s)
48    pub disk_io_mbps: T,
49}
50
51/// Resource limits
52#[derive(Debug, Clone)]
53pub struct ResourceLimits<T: Float + Debug + Send + Sync + 'static> {
54    /// Maximum memory (MB)
55    pub max_memory_mb: T,
56
57    /// Maximum CPU usage (%)
58    pub max_cpu_percent: T,
59
60    /// Maximum GPU memory (MB)
61    pub max_gpu_memory_mb: T,
62
63    /// Maximum evaluation time (seconds)
64    pub max_evaluation_time_seconds: T,
65}
66
67/// Monitoring configuration
68#[derive(Debug, Clone)]
69pub struct MonitoringConfig {
70    /// Monitoring interval (milliseconds)
71    pub monitoring_interval_ms: u64,
72
73    /// History size limit
74    pub history_size_limit: usize,
75
76    /// Enable detailed monitoring
77    pub enable_detailed_monitoring: bool,
78
79    /// Alert thresholds
80    pub alert_thresholds: HashMap<String, f64>,
81}
82
83impl<T: Float + Debug + Default + Send + Sync> ResourceMonitor<T> {
84    pub(crate) fn new() -> Self {
85        Self {
86            current_usage: ResourceUsage::default(),
87            usage_history: VecDeque::new(),
88            limits: ResourceLimits {
89                max_memory_mb: scirs2_core::numeric::NumCast::from(8192.0)
90                    .unwrap_or_else(|| T::zero()),
91                max_cpu_percent: scirs2_core::numeric::NumCast::from(90.0)
92                    .unwrap_or_else(|| T::zero()),
93                max_gpu_memory_mb: scirs2_core::numeric::NumCast::from(16384.0)
94                    .unwrap_or_else(|| T::zero()),
95                max_evaluation_time_seconds: scirs2_core::numeric::NumCast::from(3600.0)
96                    .unwrap_or_else(|| T::zero()),
97            },
98            config: MonitoringConfig {
99                monitoring_interval_ms: 1000,
100                history_size_limit: 1000,
101                enable_detailed_monitoring: true,
102                alert_thresholds: HashMap::new(),
103            },
104        }
105    }
106
107    pub(crate) fn start_monitoring(&mut self) -> Result<()> {
108        // Start resource monitoring (simplified)
109        Ok(())
110    }
111
112    /// Stop monitoring
113    pub fn stop_monitoring(&mut self) {
114        // Stop resource monitoring
115    }
116
117    /// Get current resource usage
118    pub fn get_current_usage(&self) -> &ResourceUsage<T> {
119        &self.current_usage
120    }
121
122    /// Replace the tracked current usage with a freshly measured record.
123    pub fn set_current_usage(&mut self, usage: ResourceUsage<T>) {
124        self.current_usage = usage;
125    }
126
127    /// Get resource limits
128    pub fn get_limits(&self) -> &ResourceLimits<T> {
129        &self.limits
130    }
131
132    /// Set resource limits
133    pub fn set_limits(&mut self, limits: ResourceLimits<T>) {
134        self.limits = limits;
135    }
136
137    /// Get monitoring configuration
138    pub fn get_config(&self) -> &MonitoringConfig {
139        &self.config
140    }
141
142    /// Set monitoring configuration
143    pub fn set_config(&mut self, config: MonitoringConfig) {
144        self.config = config;
145    }
146
147    /// Record a resource snapshot
148    pub fn record_snapshot(&mut self, snapshot: ResourceUsageSnapshot<T>) {
149        if self.usage_history.len() >= self.config.history_size_limit {
150            self.usage_history.pop_front();
151        }
152        self.usage_history.push_back(snapshot);
153    }
154
155    /// Get usage history
156    pub fn get_history(&self) -> &VecDeque<ResourceUsageSnapshot<T>> {
157        &self.usage_history
158    }
159
160    /// Clear history
161    pub fn clear_history(&mut self) {
162        self.usage_history.clear();
163    }
164
165    /// Check whether the currently tracked usage stays inside the configured
166    /// limits. Returns `true` when every tracked resource is within budget.
167    pub fn check_limits(&self) -> bool {
168        let mb_per_gb: T = scirs2_core::numeric::NumCast::from(1024.0).unwrap_or_else(|| T::one());
169        let memory_mb = self.current_usage.memory_gb * mb_per_gb;
170        memory_mb <= self.limits.max_memory_mb
171    }
172}