aprender-cbtop 0.65.2

Compute Block Top - Real-time load testing and hardware monitoring TUI
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
//! Predictive scheduler implementation with SLO-aware workload placement.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use super::types::{
    HostProfile, InstanceType, PredictiveSchedulerConfig, SchedulerMetrics, SchedulingDecision,
    WorkloadSpec,
};

/// Predictive scheduling optimizer
pub struct PredictiveScheduler {
    config: PredictiveSchedulerConfig,
    hosts: HashMap<String, HostProfile>,
    metrics: SchedulerMetrics,
    /// Historical execution times per host
    execution_history: HashMap<String, Vec<Duration>>,
    /// SLO violation history per host
    violation_history: HashMap<String, Vec<bool>>,
}

impl PredictiveScheduler {
    /// Create a new predictive scheduler
    pub fn new(config: PredictiveSchedulerConfig) -> Self {
        Self {
            config,
            hosts: HashMap::new(),
            metrics: SchedulerMetrics::default(),
            execution_history: HashMap::new(),
            violation_history: HashMap::new(),
        }
    }

    /// Register a host with the scheduler
    pub fn register_host(&mut self, profile: HostProfile) {
        let host_id = profile.host_id.clone();
        self.hosts.insert(host_id.clone(), profile);
        self.execution_history.insert(host_id.clone(), Vec::new());
        self.violation_history.insert(host_id, Vec::new());
    }

    /// Remove a host from the scheduler
    pub fn deregister_host(&mut self, host_id: &str) {
        self.hosts.remove(host_id);
        self.execution_history.remove(host_id);
        self.violation_history.remove(host_id);
    }

    /// Update host load
    pub fn update_host_load(&mut self, host_id: &str, load: f64) {
        if let Some(host) = self.hosts.get_mut(host_id) {
            host.current_load = load.clamp(0.0, 1.0);
        }
    }

    /// Update host preemption deadline
    pub fn update_preemption_deadline(&mut self, host_id: &str, deadline: Option<Instant>) {
        if let Some(host) = self.hosts.get_mut(host_id) {
            host.preemption_deadline = deadline;
        }
    }

    /// Schedule a workload to optimal host
    pub fn schedule(&mut self, workload: &WorkloadSpec) -> Option<SchedulingDecision> {
        let start = Instant::now();

        // Filter eligible hosts
        let eligible_hosts: Vec<_> = self
            .hosts
            .values()
            .filter(|h| self.is_host_eligible(h, workload))
            .collect();

        if eligible_hosts.is_empty() {
            return None;
        }

        // Score each host
        let mut best_decision: Option<SchedulingDecision> = None;
        let mut best_score = f64::NEG_INFINITY;

        for host in eligible_hosts {
            let decision = self.evaluate_host(host, workload);
            if decision.score > best_score {
                best_score = decision.score;
                best_decision = Some(decision);
            }
        }

        // Update metrics
        if let Some(ref decision) = best_decision {
            self.metrics.total_decisions += 1;
            let scheduling_time = start.elapsed().as_micros() as f64;
            let n = self.metrics.total_decisions as f64;
            self.metrics.avg_scheduling_latency_us =
                self.metrics.avg_scheduling_latency_us * (n - 1.0) / n + scheduling_time / n;

            // Track spot savings
            if let Some(host) = self.hosts.get(&decision.host_id) {
                if host.instance_type == InstanceType::Spot {
                    let on_demand_cost =
                        decision.predicted_cost / host.instance_type.cost_multiplier();
                    self.metrics.spot_savings += on_demand_cost - decision.predicted_cost;
                }
            }
        }

        best_decision
    }

    /// Check if host is eligible for workload
    fn is_host_eligible(&self, host: &HostProfile, workload: &WorkloadSpec) -> bool {
        // Check capacity
        if host.current_load >= self.config.min_capacity_threshold {
            return false;
        }

        // Check memory
        if host.memory_capacity < workload.memory_required {
            return false;
        }

        // Check preemption safety
        if !host.is_safe_for_scheduling(self.config.preemption_buffer) {
            return false;
        }

        // Check spot instance policy
        if host.instance_type == InstanceType::Spot && !self.config.enable_spot_instances {
            return false;
        }

        true
    }

    /// Evaluate a host for workload placement
    fn evaluate_host(&self, host: &HostProfile, workload: &WorkloadSpec) -> SchedulingDecision {
        let predicted_time = self.predict_execution_time(host, workload);
        let slo_compliance_prob = self.predict_slo_compliance(host, workload, predicted_time);
        let predicted_cost = self.calculate_cost(host, workload, predicted_time);

        // Multi-objective scoring
        let score = self.calculate_score(host, slo_compliance_prob, predicted_cost, workload);

        let reason = self.generate_reason(host, slo_compliance_prob, predicted_cost);

        SchedulingDecision {
            host_id: host.host_id.clone(),
            predicted_time,
            predicted_cost,
            slo_compliance_prob,
            score,
            reason,
        }
    }

    /// Predict execution time using historical data
    fn predict_execution_time(&self, host: &HostProfile, workload: &WorkloadSpec) -> Duration {
        let base_estimate = workload.estimated_execution_time(host);

        // Adjust based on historical variance
        if let Some(history) = self.execution_history.get(&host.host_id) {
            if !history.is_empty() {
                // Use exponential smoothing on historical data
                let alpha = 0.3;
                let mut smoothed = history[0].as_secs_f64();
                for duration in history.iter().skip(1) {
                    smoothed = alpha * duration.as_secs_f64() + (1.0 - alpha) * smoothed;
                }

                // Blend historical with estimate
                let blended = 0.7 * base_estimate.as_secs_f64() + 0.3 * smoothed;
                return Duration::from_secs_f64(blended);
            }
        }

        // Add safety margin based on performance CV
        let margin = 1.0 + host.performance_cv;
        Duration::from_secs_f64(base_estimate.as_secs_f64() * margin)
    }

    /// Predict SLO compliance probability
    pub(super) fn predict_slo_compliance(
        &self,
        host: &HostProfile,
        workload: &WorkloadSpec,
        predicted_time: Duration,
    ) -> f64 {
        // Base compliance from time vs deadline
        let time_ratio = predicted_time.as_secs_f64() / workload.slo_deadline.as_secs_f64();

        // Sigmoid function for compliance probability
        // P(comply) = 1 / (1 + exp(k * (time_ratio - 1)))
        let k = 10.0; // Steepness
        let base_prob = 1.0 / (1.0 + (k * (time_ratio - 0.9)).exp());

        // Adjust for host reliability
        let reliability_factor = host.instance_type.reliability();

        // Adjust for historical compliance
        let historical_factor = if let Some(history) = self.violation_history.get(&host.host_id) {
            if history.len() >= 10 {
                let recent: Vec<_> = history.iter().rev().take(10).collect();
                let violations = recent.iter().filter(|&&v| *v).count();
                1.0 - (violations as f64 / 10.0)
            } else {
                host.historical_slo_compliance
            }
        } else {
            host.historical_slo_compliance
        };

        base_prob * reliability_factor * historical_factor
    }

    /// Calculate execution cost
    fn calculate_cost(
        &self,
        host: &HostProfile,
        _workload: &WorkloadSpec,
        predicted_time: Duration,
    ) -> f64 {
        let hours = predicted_time.as_secs_f64() / 3600.0;
        let base_cost = host.hourly_cost * host.instance_type.cost_multiplier() * hours;

        // Add network cost based on latency
        let network_cost = host.network_latency_ms * 0.0001; // Small factor for latency

        base_cost + network_cost
    }

    /// Calculate multi-objective score
    fn calculate_score(
        &self,
        host: &HostProfile,
        slo_compliance_prob: f64,
        predicted_cost: f64,
        workload: &WorkloadSpec,
    ) -> f64 {
        // Priority weighting
        let priority_weight = 1.0 + (workload.priority as f64 * 0.1);

        // SLO compliance score (heavily weighted)
        let slo_score = if slo_compliance_prob >= self.config.target_slo_compliance {
            slo_compliance_prob * 100.0
        } else {
            // Penalty for below-target compliance
            slo_compliance_prob * 100.0
                - self.config.slo_violation_penalty
                    * (self.config.target_slo_compliance - slo_compliance_prob)
                    * 100.0
        };

        // Cost score (inverse - lower is better)
        let max_cost = self.config.max_cost_per_op;
        let cost_score = if predicted_cost <= max_cost {
            (1.0 - predicted_cost / max_cost) * 50.0
        } else {
            -((predicted_cost / max_cost) - 1.0) * 50.0
        };

        // Load balancing score (prefer less loaded hosts)
        let load_score = (1.0 - host.current_load) * 20.0;

        // Combine scores
        (slo_score + cost_score + load_score) * priority_weight
    }

    /// Generate human-readable reason for selection
    fn generate_reason(
        &self,
        host: &HostProfile,
        slo_compliance_prob: f64,
        predicted_cost: f64,
    ) -> String {
        let mut reasons = Vec::new();

        if slo_compliance_prob >= 0.99 {
            reasons.push("excellent SLO compliance");
        } else if slo_compliance_prob >= 0.95 {
            reasons.push("good SLO compliance");
        }

        if host.instance_type == InstanceType::Spot {
            reasons.push("cost-effective spot instance");
        } else if host.instance_type == InstanceType::Reserved {
            reasons.push("reserved capacity");
        }

        if host.current_load < 0.3 {
            reasons.push("low current load");
        }

        if predicted_cost < self.config.max_cost_per_op * 0.5 {
            reasons.push("low cost");
        }

        if reasons.is_empty() {
            "best available option".to_string()
        } else {
            reasons.join(", ")
        }
    }

    /// Record execution result for learning
    pub fn record_result(
        &mut self,
        host_id: &str,
        actual_time: Duration,
        slo_violated: bool,
        actual_cost: f64,
    ) {
        // Update execution history
        if let Some(history) = self.execution_history.get_mut(host_id) {
            history.push(actual_time);
            if history.len() > self.config.history_window {
                history.remove(0);
            }
        }

        // Update violation history
        if let Some(history) = self.violation_history.get_mut(host_id) {
            history.push(slo_violated);
            if history.len() > self.config.history_window {
                history.remove(0);
            }
        }

        // Update metrics
        if slo_violated {
            self.metrics.slo_violations += 1;
        }
        self.metrics.total_cost += actual_cost;

        // Update host utilization
        if let Some(host) = self.hosts.get(host_id) {
            self.metrics
                .host_utilization
                .insert(host_id.to_string(), host.current_load);
        }

        // Update host historical compliance
        if let Some(host) = self.hosts.get_mut(host_id) {
            if let Some(history) = self.violation_history.get(host_id) {
                let recent_violations = history
                    .iter()
                    .rev()
                    .take(self.config.history_window)
                    .filter(|&&v| v)
                    .count();
                let total = history.len().min(self.config.history_window);
                if total > 0 {
                    host.historical_slo_compliance =
                        1.0 - (recent_violations as f64 / total as f64);
                }
            }
        }
    }

    /// Get current scheduler metrics
    pub fn metrics(&self) -> &SchedulerMetrics {
        &self.metrics
    }

    /// Get all registered hosts
    pub fn hosts(&self) -> impl Iterator<Item = &HostProfile> {
        self.hosts.values()
    }

    /// Get host by ID
    pub fn get_host(&self, host_id: &str) -> Option<&HostProfile> {
        self.hosts.get(host_id)
    }

    /// Rebalance workloads across hosts (returns migration suggestions)
    pub fn suggest_rebalancing(&self) -> Vec<(String, String)> {
        let mut migrations = Vec::new();

        // Find overloaded and underloaded hosts
        let mut overloaded: Vec<_> = self
            .hosts
            .values()
            .filter(|h| h.current_load > 0.8)
            .collect();
        let mut underloaded: Vec<_> = self
            .hosts
            .values()
            .filter(|h| {
                h.current_load < 0.3 && h.is_safe_for_scheduling(self.config.preemption_buffer)
            })
            .collect();

        overloaded.sort_by(|a, b| {
            b.current_load
                .partial_cmp(&a.current_load)
                .expect("values should be comparable")
        });
        underloaded.sort_by(|a, b| {
            a.current_load
                .partial_cmp(&b.current_load)
                .expect("values should be comparable")
        });

        // Suggest migrations from overloaded to underloaded
        for (over, under) in overloaded.iter().zip(underloaded.iter()) {
            migrations.push((over.host_id.clone(), under.host_id.clone()));
        }

        migrations
    }
}