scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! Task scheduling and execution management
//!
//! This module handles adaptive task scheduling, queue management, execution history,
//! and performance prediction for the distributed computing framework.

use super::cluster::{NodeCapabilities, NodeId};
use super::types::{DistributedComputingConfig, DistributionStrategy, FaultToleranceLevel};
use crate::error::{CoreError, CoreResult};
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Adaptive task scheduler
#[derive(Debug)]
pub struct AdaptiveTaskScheduler {
    /// Scheduling algorithm
    #[allow(dead_code)]
    algorithm: SchedulingAlgorithm,
    /// Task queue
    task_queue: TaskQueue,
    /// Execution history
    #[allow(dead_code)]
    execution_history: ExecutionHistory,
    /// Performance predictor
    #[allow(dead_code)]
    performance_predictor: PerformancePredictor,
    /// Scheduler configuration
    #[allow(dead_code)]
    config: SchedulerConfig,
}

/// Scheduling algorithms
#[derive(Debug, Clone)]
pub enum SchedulingAlgorithm {
    RoundRobin,
    LeastLoaded,
    PerformanceBased,
    LocalityAware,
    CostOptimized,
    DeadlineAware,
    MLGuided,
    HybridAdaptive,
}

/// Task queue management
#[derive(Debug)]
pub struct TaskQueue {
    /// Pending tasks
    pub pending_tasks: Vec<DistributedTask>,
    /// Running tasks
    pub running_tasks: HashMap<TaskId, RunningTask>,
    /// Completed tasks
    #[allow(dead_code)]
    completed_tasks: Vec<CompletedTask>,
    /// Priority queues
    #[allow(dead_code)]
    priority_queues: HashMap<TaskPriority, Vec<DistributedTask>>,
}

/// Task identifier

#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct TaskId(pub String);

/// Distributed task representation
#[derive(Debug, Clone)]
pub struct DistributedTask {
    /// Task identifier
    pub id: TaskId,
    /// Task type
    pub task_type: TaskType,
    /// Input data
    pub input_data: TaskData,
    /// Input data (alias for backward compatibility)
    pub data: TaskData,
    /// Required resources
    pub resource_requirements: ResourceRequirements,
    /// Required resources (alias for backward compatibility)
    pub resources: ResourceRequirements,
    /// Expected duration
    pub expected_duration: Duration,
    /// Execution constraints
    pub constraints: ExecutionConstraints,
    /// Priority
    pub priority: TaskPriority,
    /// Deadline
    pub deadline: Option<Instant>,
    /// Dependencies
    pub dependencies: Vec<TaskId>,
    /// Metadata
    pub metadata: TaskMetadata,
    /// Requires checkpointing for fault tolerance
    pub requires_checkpointing: bool,
    /// Streaming output mode
    pub streaming_output: bool,
    /// Distribution strategy for the task
    pub distribution_strategy: DistributionStrategy,
    /// Fault tolerance settings
    pub fault_tolerance: FaultToleranceLevel,
    /// Maximum retries on failure
    pub maxretries: u32,
    /// Checkpoint interval
    pub checkpoint_interval: Option<Duration>,
}

/// Task types
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub enum TaskType {
    MatrixOperation,
    MatrixMultiplication,
    DataProcessing,
    SignalProcessing,
    MachineLearning,
    Simulation,
    Optimization,
    DataAnalysis,
    Rendering,
    Custom(String),
}

/// Task data
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct TaskData {
    /// Data payload
    pub payload: Vec<u8>,
    /// Data format
    pub format: String,
    /// Data size (bytes)
    pub size_bytes: usize,
    /// Compression used
    pub compressed: bool,
    /// Encryption used
    pub encrypted: bool,
}

/// Resource requirements
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct ResourceRequirements {
    /// Minimum CPU cores
    pub min_cpu_cores: u32,
    /// Minimum memory (GB)
    pub min_memory_gb: f64,
    /// GPU required
    pub gpu_required: bool,
    /// Minimum GPU memory (GB)
    pub min_gpu_memory_gb: Option<f64>,
    /// Storage required (GB)
    pub storage_required_gb: f64,
    /// Network bandwidth (Mbps)
    pub networkbandwidth_mbps: f64,
    /// Special requirements
    pub special_requirements: Vec<String>,
}

/// Execution constraints
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct ExecutionConstraints {
    /// Maximum execution time
    pub maxexecution_time: Duration,
    /// Preferred node types
    pub preferred_node_types: Vec<String>,
    /// Excluded nodes
    pub excluded_nodes: Vec<NodeId>,
    /// Locality preferences
    pub locality_preferences: Vec<String>,
    /// Security requirements
    pub security_requirements: Vec<String>,
}

/// Task priority levels

#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TaskPriority {
    Critical,
    High,
    Normal,
    Low,
    Background,
}

/// Task metadata
#[derive(Debug, Clone)]
pub struct TaskMetadata {
    /// Task name
    pub name: String,
    /// Creator
    pub creator: String,
    /// Creation time
    pub created_at: Instant,
    /// Tags
    pub tags: Vec<String>,
    /// Custom properties
    pub properties: HashMap<String, String>,
}

/// Running task information
#[derive(Debug, Clone)]
pub struct RunningTask {
    /// Task
    pub task: DistributedTask,
    /// Assigned node
    pub assigned_node: NodeId,
    /// Start time
    pub start_time: Instant,
    /// Progress (0.0..1.0)
    pub progress: f64,
    /// Current status
    pub status: TaskStatus,
    /// Resource usage
    pub resource_usage: TaskResourceUsage,
}

/// Task status
#[derive(Debug, Clone)]
pub enum TaskStatus {
    Queued,
    Assigned,
    Running,
    Paused,
    Completing,
    Completed,
    Failed,
    Cancelled,
}

/// Task resource usage
#[derive(Debug, Clone)]
pub struct TaskResourceUsage {
    /// CPU usage
    pub cpu_usage: f64,
    /// Memory usage (bytes)
    pub memory_usage: usize,
    /// GPU usage
    pub gpu_usage: Option<f64>,
    /// Network usage (bytes/sec)
    pub network_usage: f64,
    /// Storage usage (bytes)
    pub storage_usage: usize,
}

/// Completed task information
#[derive(Debug, Clone)]
pub struct CompletedTask {
    /// Task
    pub task: DistributedTask,
    /// Execution node
    pub execution_node: NodeId,
    /// Start time
    pub start_time: Instant,
    /// End time
    pub end_time: Instant,
    /// Final status
    pub final_status: TaskStatus,
    /// Result data
    pub result_data: Option<TaskData>,
    /// Performance metrics
    pub performance_metrics: TaskPerformanceMetrics,
    /// Error information
    pub error_info: Option<TaskError>,
}

/// Task performance metrics
#[derive(Debug, Clone)]
pub struct TaskPerformanceMetrics {
    /// Execution time
    pub execution_time: Duration,
    /// CPU time
    pub cpu_time: Duration,
    /// Memory peak usage
    pub memory_peak: usize,
    /// Network bytes transferred
    pub network_bytes: u64,
    /// Efficiency score
    pub efficiency_score: f64,
}

/// Task error information
#[derive(Debug, Clone)]
pub struct TaskError {
    /// Error code
    pub errorcode: String,
    /// Error message
    pub message: String,
    /// Error category
    pub category: ErrorCategory,
    /// Stack trace
    pub stack_trace: Option<String>,
    /// Recovery suggestions
    pub recovery_suggestions: Vec<String>,
}

/// Error categories
#[derive(Debug, Clone)]
pub enum ErrorCategory {
    ResourceExhausted,
    NetworkFailure,
    NodeFailure,
    InvalidInput,
    SecurityViolation,
    TimeoutExpired,
    UnknownError,
}

/// Execution history tracking
#[derive(Debug)]
pub struct ExecutionHistory {
    /// Task execution records
    #[allow(dead_code)]
    records: Vec<ExecutionRecord>,
    /// Performance trends
    #[allow(dead_code)]
    performance_trends: PerformanceTrends,
    /// Resource utilization patterns
    #[allow(dead_code)]
    utilization_patterns: UtilizationPatterns,
}

/// Execution record
#[derive(Debug, Clone)]
pub struct ExecutionRecord {
    /// Task type
    pub task_type: TaskType,
    /// Node capabilities used
    pub node_capabilities: NodeCapabilities,
    /// Execution time
    pub execution_time: Duration,
    /// Resource usage
    pub resource_usage: TaskResourceUsage,
    /// Success flag
    pub success: bool,
    /// Timestamp
    pub timestamp: Instant,
}

/// Performance trends
#[derive(Debug, Clone)]
pub struct PerformanceTrends {
    /// Average execution times by task type
    pub avgexecution_times: HashMap<String, Duration>,
    /// Success rates by node type
    pub success_rates: HashMap<String, f64>,
    /// Resource efficiency trends
    pub efficiency_trends: Vec<EfficiencyDataPoint>,
}

/// Efficiency data point
#[derive(Debug, Clone)]
pub struct EfficiencyDataPoint {
    /// Timestamp
    pub timestamp: Instant,
    /// Efficiency score
    pub efficiency: f64,
    /// Task type
    pub task_type: TaskType,
    /// Node type
    pub node_type: String,
}

/// Resource utilization patterns
#[derive(Debug, Clone)]
pub struct UtilizationPatterns {
    /// CPU utilization patterns
    pub cpu_patterns: Vec<UtilizationPattern>,
    /// Memory utilization patterns
    pub memory_patterns: Vec<UtilizationPattern>,
    /// Network utilization patterns
    pub network_patterns: Vec<UtilizationPattern>,
}

/// Utilization pattern
#[derive(Debug, Clone)]
pub struct UtilizationPattern {
    /// Pattern type
    pub pattern_type: PatternType,
    /// Time series data
    pub data_points: Vec<DataPoint>,
    /// Pattern confidence
    pub confidence: f64,
}

/// Pattern types
#[derive(Debug, Clone)]
pub enum PatternType {
    Constant,
    Linear,
    Exponential,
    Periodic,
    Irregular,
}

/// Data point
#[derive(Debug, Clone)]
pub struct DataPoint {
    /// Timestamp
    pub timestamp: Instant,
    /// Value
    pub value: f64,
}

/// Performance predictor
#[derive(Debug)]
pub struct PerformancePredictor {
    /// Prediction models
    #[allow(dead_code)]
    models: HashMap<String, PredictionModel>,
    /// Historical data
    #[allow(dead_code)]
    historical_data: Vec<ExecutionRecord>,
    /// Prediction accuracy metrics
    #[allow(dead_code)]
    accuracy_metrics: AccuracyMetrics,
}

/// Prediction model
#[derive(Debug, Clone)]
pub struct PredictionModel {
    /// Model type
    pub model_type: ModelType,
    /// Model parameters
    pub parameters: Vec<f64>,
    /// Training data size
    pub training_size: usize,
    /// Model accuracy
    pub accuracy: f64,
    /// Last update
    pub last_updated: Instant,
}

/// Model types
#[derive(Debug, Clone)]
pub enum ModelType {
    LinearRegression,
    RandomForest,
    NeuralNetwork,
    SupportVectorMachine,
    GradientBoosting,
}

/// Accuracy metrics
#[derive(Debug, Clone)]
pub struct AccuracyMetrics {
    /// Mean absolute error
    pub mean_absoluteerror: f64,
    /// Root mean square error
    pub root_mean_squareerror: f64,
    /// R-squared
    pub r_squared: f64,
    /// Prediction confidence intervals
    pub confidence_intervals: Vec<ConfidenceInterval>,
}

/// Confidence interval
#[derive(Debug, Clone)]
pub struct ConfidenceInterval {
    /// Lower bound
    pub lower: f64,
    /// Upper bound
    pub upper: f64,
    /// Confidence level
    pub confidence_level: f64,
}

/// Scheduler configuration
#[derive(Debug, Clone)]
pub struct SchedulerConfig {
    /// Maximum concurrent tasks per node
    pub max_concurrent_tasks: u32,
    /// Task timeout multiplier
    pub timeout_multiplier: f64,
    /// Enable load balancing
    pub enable_load_balancing: bool,
    /// Enable locality optimization
    pub enable_locality_optimization: bool,
    /// Scheduling interval
    pub scheduling_interval: Duration,
}

// Implementations
impl AdaptiveTaskScheduler {
    pub fn new(config: &DistributedComputingConfig) -> CoreResult<Self> {
        Ok(Self {
            algorithm: SchedulingAlgorithm::HybridAdaptive,
            task_queue: TaskQueue::new(),
            execution_history: ExecutionHistory::new(),
            performance_predictor: PerformancePredictor::new()?,
            config: SchedulerConfig {
                max_concurrent_tasks: 10,
                timeout_multiplier: 1.5,
                enable_load_balancing: true,
                enable_locality_optimization: true,
                scheduling_interval: Duration::from_secs(1),
            },
        })
    }

    pub fn start(&mut self) -> CoreResult<()> {
        println!("📅 Starting adaptive task scheduler...");
        Ok(())
    }

    pub fn submit_task(&mut self, task: DistributedTask) -> CoreResult<TaskId> {
        let taskid = task.id.clone();
        self.task_queue.pending_tasks.push(task);
        Ok(taskid)
    }

    pub fn get_task_status(&self, taskid: &TaskId) -> Option<TaskStatus> {
        self.task_queue
            .running_tasks
            .get(taskid)
            .map(|running_task| running_task.status.clone())
    }

    pub fn cancel_task(&self, _taskid: &TaskId) -> CoreResult<()> {
        println!("❌ Cancelling task...");
        Ok(())
    }
}

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

impl TaskQueue {
    pub fn new() -> Self {
        Self {
            pending_tasks: Vec::new(),
            running_tasks: HashMap::new(),
            completed_tasks: Vec::new(),
            priority_queues: HashMap::new(),
        }
    }
}

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

impl ExecutionHistory {
    pub fn new() -> Self {
        Self {
            records: Vec::new(),
            performance_trends: PerformanceTrends {
                avgexecution_times: HashMap::new(),
                success_rates: HashMap::new(),
                efficiency_trends: Vec::new(),
            },
            utilization_patterns: UtilizationPatterns {
                cpu_patterns: Vec::new(),
                memory_patterns: Vec::new(),
                network_patterns: Vec::new(),
            },
        }
    }
}

impl PerformancePredictor {
    pub fn new() -> CoreResult<Self> {
        Ok(Self {
            models: HashMap::new(),
            historical_data: Vec::new(),
            accuracy_metrics: AccuracyMetrics {
                mean_absoluteerror: 0.05,
                root_mean_squareerror: 0.07,
                r_squared: 0.92,
                confidence_intervals: vec![ConfidenceInterval {
                    lower: 0.8,
                    upper: 1.2,
                    confidence_level: 0.95,
                }],
            },
        })
    }
}