Skip to content

Commit 9bddfd5

Browse files
Copilotmakr-code
andcommitted
Add audit event and anomaly detection infrastructure
Co-authored-by: makr-code <150588092+makr-code@users.noreply.github.com>
1 parent 6d0715a commit 9bddfd5

6 files changed

Lines changed: 1990 additions & 0 deletions

File tree

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/**
2+
* @file task_anomaly_detector.h
3+
* @brief Anomaly detection system for task scheduler execution patterns
4+
*
5+
* Implements real-time anomaly detection for task execution monitoring:
6+
* - Frequency-based anomaly detection (sudden spikes/drops)
7+
* - Pattern-based anomaly detection (unusual execution patterns)
8+
* - Resource usage anomaly detection
9+
* - Failure rate anomaly detection
10+
* - Statistical baseline learning
11+
* - Configurable thresholds and sensitivity
12+
*/
13+
14+
#ifndef THEMIS_TASK_ANOMALY_DETECTOR_H
15+
#define THEMIS_TASK_ANOMALY_DETECTOR_H
16+
17+
#include "scheduler/task_audit_event.h"
18+
#include <string>
19+
#include <map>
20+
#include <deque>
21+
#include <mutex>
22+
#include <chrono>
23+
#include <memory>
24+
25+
namespace themis {
26+
namespace scheduler {
27+
28+
/**
29+
* @brief Configuration for anomaly detection
30+
*/
31+
struct AnomalyDetectorConfig {
32+
// Detection thresholds (0-1 scale)
33+
double frequency_threshold = 0.7; // Trigger alert if frequency score > threshold
34+
double pattern_threshold = 0.7; // Trigger alert if pattern score > threshold
35+
double resource_threshold = 0.8; // Trigger alert if resource score > threshold
36+
double failure_rate_threshold = 0.6; // Trigger alert if failure rate score > threshold
37+
double overall_threshold = 0.7; // Trigger alert if overall score > threshold
38+
39+
// Baseline learning
40+
size_t min_samples = 30; // Minimum samples needed for baseline
41+
size_t max_history_size = 1000; // Maximum history entries per task
42+
std::chrono::hours baseline_window{24}; // Time window for baseline calculation
43+
44+
// Frequency detection
45+
double frequency_spike_factor = 3.0; // Spike if frequency > mean * factor
46+
double frequency_drop_factor = 0.3; // Drop if frequency < mean * factor
47+
48+
// Resource detection
49+
double resource_spike_factor = 2.5; // Spike if resource > mean * factor
50+
51+
// Failure rate detection
52+
double failure_rate_spike = 0.3; // Alert if failure rate > threshold
53+
54+
// Pattern detection
55+
size_t pattern_window_size = 10; // Window size for pattern analysis
56+
57+
// Enabled features
58+
bool enable_frequency_detection = true;
59+
bool enable_pattern_detection = true;
60+
bool enable_resource_detection = true;
61+
bool enable_failure_rate_detection = true;
62+
};
63+
64+
/**
65+
* @brief Statistics for a single task
66+
*/
67+
struct TaskStatistics {
68+
// Execution frequency
69+
size_t total_executions = 0;
70+
double executions_per_hour = 0.0;
71+
double mean_execution_frequency = 0.0;
72+
double stddev_execution_frequency = 0.0;
73+
74+
// Execution time
75+
double mean_execution_time_ms = 0.0;
76+
double stddev_execution_time_ms = 0.0;
77+
double min_execution_time_ms = 0.0;
78+
double max_execution_time_ms = 0.0;
79+
80+
// Resource usage
81+
double mean_cpu_time_ms = 0.0;
82+
double stddev_cpu_time_ms = 0.0;
83+
double mean_memory_bytes = 0.0;
84+
double stddev_memory_bytes = 0.0;
85+
86+
// Failure tracking
87+
size_t total_failures = 0;
88+
double failure_rate = 0.0;
89+
double recent_failure_rate = 0.0; // Last N executions
90+
91+
// Time tracking
92+
std::chrono::system_clock::time_point first_execution;
93+
std::chrono::system_clock::time_point last_execution;
94+
95+
// Pattern tracking
96+
std::deque<std::chrono::system_clock::time_point> execution_times;
97+
std::deque<double> execution_durations;
98+
std::deque<bool> execution_results; // true = success, false = failure
99+
std::deque<double> cpu_usage;
100+
std::deque<double> memory_usage;
101+
};
102+
103+
/**
104+
* @brief Anomaly detector for task scheduler
105+
*
106+
* Features:
107+
* - Statistical baseline learning from historical data
108+
* - Real-time anomaly scoring (0-1 scale)
109+
* - Multi-dimensional anomaly detection (frequency, pattern, resource, failure)
110+
* - Configurable sensitivity and thresholds
111+
* - Thread-safe operation
112+
* - Automatic baseline updates
113+
*/
114+
class TaskAnomalyDetector {
115+
public:
116+
explicit TaskAnomalyDetector(const AnomalyDetectorConfig& config = AnomalyDetectorConfig());
117+
118+
/**
119+
* @brief Record a task execution event
120+
* @param event Audit event to process
121+
* @return Anomaly metrics for this execution
122+
*/
123+
AnomalyMetrics recordExecution(const TaskAuditEvent& event);
124+
125+
/**
126+
* @brief Get statistics for a specific task
127+
* @param task_id Task identifier
128+
* @return Task statistics (or empty if task not found)
129+
*/
130+
std::optional<TaskStatistics> getTaskStatistics(const std::string& task_id) const;
131+
132+
/**
133+
* @brief Get all task statistics
134+
* @return Map of task_id -> statistics
135+
*/
136+
std::map<std::string, TaskStatistics> getAllStatistics() const;
137+
138+
/**
139+
* @brief Reset statistics for a specific task
140+
* @param task_id Task identifier
141+
*/
142+
void resetTaskStatistics(const std::string& task_id);
143+
144+
/**
145+
* @brief Reset all statistics
146+
*/
147+
void resetAllStatistics();
148+
149+
/**
150+
* @brief Check if task has sufficient baseline data
151+
* @param task_id Task identifier
152+
* @return true if baseline is established
153+
*/
154+
bool hasBaseline(const std::string& task_id) const;
155+
156+
/**
157+
* @brief Get current configuration
158+
*/
159+
AnomalyDetectorConfig getConfig() const;
160+
161+
/**
162+
* @brief Update configuration
163+
*/
164+
void updateConfig(const AnomalyDetectorConfig& config);
165+
166+
/**
167+
* @brief Export statistics to JSON (for persistence/analysis)
168+
*/
169+
nlohmann::json exportStatistics() const;
170+
171+
/**
172+
* @brief Import statistics from JSON (for restoration)
173+
*/
174+
void importStatistics(const nlohmann::json& data);
175+
176+
private:
177+
AnomalyDetectorConfig config_;
178+
mutable std::mutex mutex_;
179+
180+
// Per-task statistics
181+
std::map<std::string, TaskStatistics> task_stats_;
182+
183+
// Anomaly detection methods
184+
double detectFrequencyAnomaly(const std::string& task_id,
185+
const std::chrono::system_clock::time_point& now);
186+
187+
double detectPatternAnomaly(const std::string& task_id,
188+
const std::chrono::system_clock::time_point& now);
189+
190+
double detectResourceAnomaly(const std::string& task_id,
191+
const TaskResourceUsage& resource_usage);
192+
193+
double detectFailureRateAnomaly(const std::string& task_id,
194+
bool success);
195+
196+
// Statistical helpers
197+
void updateStatistics(const std::string& task_id, const TaskAuditEvent& event);
198+
double calculateMean(const std::deque<double>& values) const;
199+
double calculateStdDev(const std::deque<double>& values, double mean) const;
200+
double calculatePercentile(const std::deque<double>& values, double percentile) const;
201+
202+
// Cleanup old data
203+
void cleanupOldData(TaskStatistics& stats);
204+
};
205+
206+
} // namespace scheduler
207+
} // namespace themis
208+
209+
#endif // THEMIS_TASK_ANOMALY_DETECTOR_H

0 commit comments

Comments
 (0)