mockforge-chaos 0.3.21

Chaos engineering features for MockForge - fault injection and resilience testing
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
//! ML-based assertion generation from historical data
//!
//! Analyzes historical orchestration execution data to automatically generate
//! meaningful assertions based on observed patterns and anomalies.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Historical execution data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionDataPoint {
    pub timestamp: DateTime<Utc>,
    pub orchestration_id: String,
    pub step_id: String,
    pub metrics: HashMap<String, f64>,
    pub success: bool,
    pub duration_ms: u64,
    pub error_message: Option<String>,
}

/// Statistical summary of metric
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricStats {
    pub mean: f64,
    pub median: f64,
    pub std_dev: f64,
    pub min: f64,
    pub max: f64,
    pub p95: f64,
    pub p99: f64,
    pub sample_count: usize,
}

/// Generated assertion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratedAssertion {
    pub id: String,
    pub assertion_type: AssertionType,
    pub path: String,
    pub operator: AssertionOperator,
    pub value: f64,
    pub confidence: f64,
    pub rationale: String,
    pub based_on_samples: usize,
    pub created_at: DateTime<Utc>,
}

/// Type of assertion
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AssertionType {
    MetricThreshold,
    SuccessRate,
    Duration,
    ErrorRate,
    Custom,
}

/// Assertion operator
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AssertionOperator {
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    InRange,
    NotInRange,
}

/// Assertion generation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssertionGeneratorConfig {
    /// Minimum number of samples required
    pub min_samples: usize,
    /// Confidence threshold (0.0 - 1.0)
    pub min_confidence: f64,
    /// Standard deviations for threshold detection
    pub std_dev_multiplier: f64,
    /// Use percentiles for threshold calculation
    pub use_percentiles: bool,
    /// Percentile to use for upper bounds
    pub upper_percentile: f64,
    /// Percentile to use for lower bounds
    pub lower_percentile: f64,
}

impl Default for AssertionGeneratorConfig {
    fn default() -> Self {
        Self {
            min_samples: 10,
            min_confidence: 0.7,
            std_dev_multiplier: 2.0,
            use_percentiles: true,
            upper_percentile: 95.0,
            lower_percentile: 5.0,
        }
    }
}

/// ML-based assertion generator
pub struct AssertionGenerator {
    config: AssertionGeneratorConfig,
    historical_data: Vec<ExecutionDataPoint>,
}

impl AssertionGenerator {
    /// Create a new assertion generator
    pub fn new(config: AssertionGeneratorConfig) -> Self {
        Self {
            config,
            historical_data: Vec::new(),
        }
    }

    /// Add historical data
    pub fn add_data(&mut self, data: ExecutionDataPoint) {
        self.historical_data.push(data);
    }

    /// Add multiple data points
    pub fn add_bulk_data(&mut self, data: Vec<ExecutionDataPoint>) {
        self.historical_data.extend(data);
    }

    /// Generate assertions based on historical data
    pub fn generate_assertions(&self) -> Result<Vec<GeneratedAssertion>, String> {
        if self.historical_data.len() < self.config.min_samples {
            return Err(format!(
                "Insufficient data: need at least {} samples, have {}",
                self.config.min_samples,
                self.historical_data.len()
            ));
        }

        let mut assertions = Vec::new();

        // Group data by orchestration and step
        let grouped_data = self.group_data_by_step();

        for ((orch_id, step_id), data_points) in grouped_data {
            if data_points.len() < self.config.min_samples {
                continue;
            }

            // Generate duration assertions
            assertions.extend(self.generate_duration_assertions(
                &orch_id,
                &step_id,
                &data_points,
            )?);

            // Generate success rate assertions
            assertions.extend(self.generate_success_rate_assertions(
                &orch_id,
                &step_id,
                &data_points,
            )?);

            // Generate metric assertions
            assertions.extend(self.generate_metric_assertions(&orch_id, &step_id, &data_points)?);

            // Generate error rate assertions
            assertions.extend(self.generate_error_rate_assertions(
                &orch_id,
                &step_id,
                &data_points,
            )?);
        }

        Ok(assertions)
    }

    /// Group data by step
    fn group_data_by_step(&self) -> HashMap<(String, String), Vec<ExecutionDataPoint>> {
        let mut grouped: HashMap<(String, String), Vec<ExecutionDataPoint>> = HashMap::new();

        for data_point in &self.historical_data {
            let key = (data_point.orchestration_id.clone(), data_point.step_id.clone());
            grouped.entry(key).or_default().push(data_point.clone());
        }

        grouped
    }

    /// Generate duration assertions
    fn generate_duration_assertions(
        &self,
        orch_id: &str,
        step_id: &str,
        data: &[ExecutionDataPoint],
    ) -> Result<Vec<GeneratedAssertion>, String> {
        let durations: Vec<f64> = data.iter().map(|d| d.duration_ms as f64).collect();
        let stats = Self::calculate_stats(&durations);

        let mut assertions = Vec::new();

        // Generate P95 duration assertion
        if self.config.use_percentiles {
            let threshold = stats.p95;
            let confidence = self.calculate_confidence(&durations, threshold);

            if confidence >= self.config.min_confidence {
                assertions.push(GeneratedAssertion {
                    id: format!("duration_{}_{}", orch_id, step_id),
                    assertion_type: AssertionType::Duration,
                    path: format!("{}.{}.duration", orch_id, step_id),
                    operator: AssertionOperator::LessThanOrEqual,
                    value: threshold,
                    confidence,
                    rationale: format!(
                        "Based on P95 of historical data: {:.2}ms (mean: {:.2}ms, std: {:.2}ms)",
                        threshold, stats.mean, stats.std_dev
                    ),
                    based_on_samples: data.len(),
                    created_at: Utc::now(),
                });
            }
        }

        Ok(assertions)
    }

    /// Generate success rate assertions
    fn generate_success_rate_assertions(
        &self,
        orch_id: &str,
        step_id: &str,
        data: &[ExecutionDataPoint],
    ) -> Result<Vec<GeneratedAssertion>, String> {
        let success_count = data.iter().filter(|d| d.success).count();
        let total_count = data.len();
        let success_rate = success_count as f64 / total_count as f64;

        let mut assertions = Vec::new();

        // Only generate if success rate is consistently high
        if success_rate >= 0.9 {
            let confidence = success_rate;

            assertions.push(GeneratedAssertion {
                id: format!("success_rate_{}_{}", orch_id, step_id),
                assertion_type: AssertionType::SuccessRate,
                path: format!("{}.{}.success_rate", orch_id, step_id),
                operator: AssertionOperator::GreaterThanOrEqual,
                value: success_rate * 0.95, // Allow 5% deviation
                confidence,
                rationale: format!(
                    "Based on historical success rate: {:.2}% ({}/{} successful executions)",
                    success_rate * 100.0,
                    success_count,
                    total_count
                ),
                based_on_samples: total_count,
                created_at: Utc::now(),
            });
        }

        Ok(assertions)
    }

    /// Generate metric assertions
    fn generate_metric_assertions(
        &self,
        orch_id: &str,
        step_id: &str,
        data: &[ExecutionDataPoint],
    ) -> Result<Vec<GeneratedAssertion>, String> {
        let mut assertions = Vec::new();

        // Collect all metric names
        let mut all_metrics: HashMap<String, Vec<f64>> = HashMap::new();
        for data_point in data {
            for (metric_name, value) in &data_point.metrics {
                all_metrics.entry(metric_name.clone()).or_default().push(*value);
            }
        }

        // Generate assertions for each metric
        for (metric_name, values) in all_metrics {
            if values.len() < self.config.min_samples {
                continue;
            }

            let stats = Self::calculate_stats(&values);

            if self.config.use_percentiles {
                // Upper bound assertion (P95)
                let upper_threshold = stats.p95;
                let confidence = self.calculate_confidence(&values, upper_threshold);

                if confidence >= self.config.min_confidence {
                    assertions.push(GeneratedAssertion {
                        id: format!("metric_{}_{}_{}_upper", orch_id, step_id, metric_name),
                        assertion_type: AssertionType::MetricThreshold,
                        path: format!("{}.{}.metrics.{}", orch_id, step_id, metric_name),
                        operator: AssertionOperator::LessThanOrEqual,
                        value: upper_threshold,
                        confidence,
                        rationale: format!(
                            "Metric '{}' typically below {:.2} (P95: {:.2}, mean: {:.2}, std: {:.2})",
                            metric_name, upper_threshold, stats.p95, stats.mean, stats.std_dev
                        ),
                        based_on_samples: values.len(),
                        created_at: Utc::now(),
                    });
                }
            }
        }

        Ok(assertions)
    }

    /// Generate error rate assertions
    fn generate_error_rate_assertions(
        &self,
        orch_id: &str,
        step_id: &str,
        data: &[ExecutionDataPoint],
    ) -> Result<Vec<GeneratedAssertion>, String> {
        let error_count = data.iter().filter(|d| !d.success).count();
        let total_count = data.len();
        let error_rate = error_count as f64 / total_count as f64;

        let mut assertions = Vec::new();

        // Generate assertion if error rate is consistently low
        if error_rate <= 0.1 {
            assertions.push(GeneratedAssertion {
                id: format!("error_rate_{}_{}", orch_id, step_id),
                assertion_type: AssertionType::ErrorRate,
                path: format!("{}.{}.error_rate", orch_id, step_id),
                operator: AssertionOperator::LessThanOrEqual,
                value: (error_rate * 1.5).min(0.2), // Allow 50% increase, max 20%
                confidence: 1.0 - error_rate,
                rationale: format!(
                    "Based on historical error rate: {:.2}% ({}/{} failures)",
                    error_rate * 100.0,
                    error_count,
                    total_count
                ),
                based_on_samples: total_count,
                created_at: Utc::now(),
            });
        }

        Ok(assertions)
    }

    /// Calculate statistics for a set of values
    fn calculate_stats(values: &[f64]) -> MetricStats {
        if values.is_empty() {
            return MetricStats {
                mean: 0.0,
                median: 0.0,
                std_dev: 0.0,
                min: 0.0,
                max: 0.0,
                p95: 0.0,
                p99: 0.0,
                sample_count: 0,
            };
        }

        let mut sorted = values.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
        let median = sorted[sorted.len() / 2];
        let min = sorted[0];
        let max = sorted[sorted.len() - 1];

        let variance = sorted.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / sorted.len() as f64;
        let std_dev = variance.sqrt();

        let p95_idx = ((sorted.len() as f64) * 0.95) as usize;
        let p99_idx = ((sorted.len() as f64) * 0.99) as usize;
        let p95 = sorted[p95_idx.min(sorted.len() - 1)];
        let p99 = sorted[p99_idx.min(sorted.len() - 1)];

        MetricStats {
            mean,
            median,
            std_dev,
            min,
            max,
            p95,
            p99,
            sample_count: sorted.len(),
        }
    }

    /// Calculate confidence for a threshold
    fn calculate_confidence(&self, values: &[f64], threshold: f64) -> f64 {
        let within_threshold = values.iter().filter(|&&v| v <= threshold).count();
        within_threshold as f64 / values.len() as f64
    }

    /// Get data count
    pub fn data_count(&self) -> usize {
        self.historical_data.len()
    }

    /// Clear historical data
    pub fn clear_data(&mut self) {
        self.historical_data.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_sample_data(count: usize) -> Vec<ExecutionDataPoint> {
        (0..count)
            .map(|i| {
                let mut metrics = HashMap::new();
                metrics.insert("latency_ms".to_string(), 100.0 + (i % 20) as f64);
                metrics.insert("error_rate".to_string(), 0.01 + (i % 5) as f64 * 0.001);

                ExecutionDataPoint {
                    timestamp: Utc::now(),
                    orchestration_id: "orch-1".to_string(),
                    step_id: "step-1".to_string(),
                    metrics,
                    success: i % 10 != 0, // 90% success rate
                    duration_ms: 100 + (i % 50) as u64,
                    error_message: if i % 10 == 0 {
                        Some("Test error".to_string())
                    } else {
                        None
                    },
                }
            })
            .collect()
    }

    #[test]
    fn test_generator_creation() {
        let config = AssertionGeneratorConfig::default();
        let generator = AssertionGenerator::new(config);
        assert_eq!(generator.data_count(), 0);
    }

    #[test]
    fn test_add_data() {
        let config = AssertionGeneratorConfig::default();
        let mut generator = AssertionGenerator::new(config);

        let data = create_sample_data(1);
        generator.add_data(data[0].clone());

        assert_eq!(generator.data_count(), 1);
    }

    #[test]
    fn test_generate_assertions() {
        let config = AssertionGeneratorConfig::default();
        let mut generator = AssertionGenerator::new(config);

        let data = create_sample_data(50);
        generator.add_bulk_data(data);

        let assertions = generator.generate_assertions().unwrap();
        assert!(!assertions.is_empty());

        // Should have duration, success rate, and metric assertions
        assert!(assertions.iter().any(|a| a.assertion_type == AssertionType::Duration));
        assert!(assertions.iter().any(|a| a.assertion_type == AssertionType::SuccessRate));
    }

    #[test]
    fn test_insufficient_data() {
        let config = AssertionGeneratorConfig::default();
        let mut generator = AssertionGenerator::new(config);

        let data = create_sample_data(5);
        generator.add_bulk_data(data);

        let result = generator.generate_assertions();
        assert!(result.is_err());
    }

    #[test]
    fn test_stats_calculation() {
        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
        let stats = AssertionGenerator::calculate_stats(&values);

        assert_eq!(stats.mean, 5.5);
        assert_eq!(stats.median, 6.0);
        assert_eq!(stats.min, 1.0);
        assert_eq!(stats.max, 10.0);
        assert_eq!(stats.sample_count, 10);
    }
}