depyler-core 3.24.0

Core transpilation engine for the Depyler Python-to-Rust transpiler
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
// Chaos Engineering Configuration (from renacer Sprint 29)
// Source: renacer v0.4.1 (https://github.com/paiml/renacer)
//
// Provides chaos testing infrastructure for systematic fault injection
// and stress testing of the Depyler transpiler.

use std::time::Duration;

/// Chaos engineering configuration for stress testing the transpiler
///
/// Supports:
/// - Memory limit enforcement
/// - CPU throttling
/// - Timeout controls
/// - Signal injection for fault simulation
///
/// # Examples
///
/// ```
/// use depyler_core::chaos::ChaosConfig;
/// use std::time::Duration;
///
/// // Gentle chaos testing (development)
/// let gentle = ChaosConfig::gentle();
///
/// // Aggressive chaos testing (CI/CD)
/// let aggressive = ChaosConfig::aggressive();
///
/// // Custom configuration
/// let custom = ChaosConfig::new()
///     .with_memory_limit(100 * 1024 * 1024)
///     .with_cpu_limit(0.5)
///     .with_timeout(Duration::from_secs(30))
///     .with_signal_injection(true)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct ChaosConfig {
    /// Maximum memory usage in bytes (0 = unlimited)
    pub memory_limit: usize,
    /// CPU limit as fraction 0.0-1.0 (0.0 = unlimited)
    pub cpu_limit: f64,
    /// Maximum execution timeout
    pub timeout: Duration,
    /// Enable random signal injection for fault testing
    pub signal_injection: bool,
}

impl Default for ChaosConfig {
    fn default() -> Self {
        Self {
            memory_limit: 0,
            cpu_limit: 0.0,
            timeout: Duration::from_secs(60),
            signal_injection: false,
        }
    }
}

impl ChaosConfig {
    /// Create a new chaos configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set memory limit in bytes
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// let config = ChaosConfig::new().with_memory_limit(512 * 1024 * 1024); // 512 MB
    /// assert_eq!(config.memory_limit, 512 * 1024 * 1024);
    /// ```
    pub fn with_memory_limit(mut self, bytes: usize) -> Self {
        self.memory_limit = bytes;
        self
    }

    /// Set CPU limit as fraction (0.0-1.0, automatically clamped)
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// let config = ChaosConfig::new().with_cpu_limit(0.8); // 80% CPU
    /// assert_eq!(config.cpu_limit, 0.8);
    ///
    /// // Out-of-range values are clamped
    /// let clamped = ChaosConfig::new().with_cpu_limit(1.5);
    /// assert_eq!(clamped.cpu_limit, 1.0);
    /// ```
    pub fn with_cpu_limit(mut self, fraction: f64) -> Self {
        self.cpu_limit = fraction.clamp(0.0, 1.0);
        self
    }

    /// Set execution timeout
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// # use std::time::Duration;
    /// let config = ChaosConfig::new().with_timeout(Duration::from_secs(30));
    /// assert_eq!(config.timeout, Duration::from_secs(30));
    /// ```
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Enable or disable signal injection
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// let config = ChaosConfig::new().with_signal_injection(true);
    /// assert_eq!(config.signal_injection, true);
    /// ```
    pub fn with_signal_injection(mut self, enabled: bool) -> Self {
        self.signal_injection = enabled;
        self
    }

    /// Build the final configuration (consumes self)
    pub fn build(self) -> Self {
        self
    }

    /// Gentle chaos preset for development testing
    ///
    /// - Memory: 512 MB limit
    /// - CPU: 80% throttle
    /// - Timeout: 120 seconds
    /// - Signals: Disabled
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// # use std::time::Duration;
    /// let config = ChaosConfig::gentle();
    /// assert_eq!(config.memory_limit, 512 * 1024 * 1024);
    /// assert_eq!(config.cpu_limit, 0.8);
    /// assert_eq!(config.timeout, Duration::from_secs(120));
    /// assert_eq!(config.signal_injection, false);
    /// ```
    pub fn gentle() -> Self {
        Self::new()
            .with_memory_limit(512 * 1024 * 1024)
            .with_cpu_limit(0.8)
            .with_timeout(Duration::from_secs(120))
    }

    /// Aggressive chaos preset for CI/CD stress testing
    ///
    /// - Memory: 64 MB limit
    /// - CPU: 25% throttle
    /// - Timeout: 10 seconds
    /// - Signals: Enabled
    ///
    /// # Example
    /// ```
    /// # use depyler_core::chaos::ChaosConfig;
    /// # use std::time::Duration;
    /// let config = ChaosConfig::aggressive();
    /// assert_eq!(config.memory_limit, 64 * 1024 * 1024);
    /// assert_eq!(config.cpu_limit, 0.25);
    /// assert_eq!(config.timeout, Duration::from_secs(10));
    /// assert_eq!(config.signal_injection, true);
    /// ```
    pub fn aggressive() -> Self {
        Self::new()
            .with_memory_limit(64 * 1024 * 1024)
            .with_cpu_limit(0.25)
            .with_timeout(Duration::from_secs(10))
            .with_signal_injection(true)
    }
}

/// Result type for chaos testing operations
pub type ChaosResult<T> = Result<T, ChaosError>;

/// Errors that can occur during chaos testing
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChaosError {
    /// Memory limit exceeded during test
    MemoryLimitExceeded {
        /// Configured memory limit
        limit: usize,
        /// Actual memory used
        used: usize,
    },
    /// Execution timeout exceeded
    Timeout {
        /// Actual elapsed time
        elapsed: Duration,
        /// Configured timeout limit
        limit: Duration,
    },
    /// Signal injection failed
    SignalInjectionFailed {
        /// Signal number that failed
        signal: i32,
        /// Reason for failure
        reason: String,
    },
}

impl std::fmt::Display for ChaosError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChaosError::MemoryLimitExceeded { limit, used } => {
                write!(f, "Memory limit exceeded: {} > {} bytes", used, limit)
            }
            ChaosError::Timeout { elapsed, limit } => {
                write!(f, "Timeout: {:?} > {:?}", elapsed, limit)
            }
            ChaosError::SignalInjectionFailed { signal, reason } => {
                write!(f, "Signal injection failed ({}): {}", signal, reason)
            }
        }
    }
}

impl std::error::Error for ChaosError {}

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

    // === ChaosConfig construction tests ===

    #[test]
    fn test_new() {
        let config = ChaosConfig::new();
        assert_eq!(config.memory_limit, 0);
        assert_eq!(config.cpu_limit, 0.0);
    }

    #[test]
    fn test_clone() {
        let config = ChaosConfig::new()
            .with_memory_limit(100)
            .with_cpu_limit(0.5);
        let cloned = config.clone();
        assert_eq!(cloned.memory_limit, 100);
        assert_eq!(cloned.cpu_limit, 0.5);
    }

    #[test]
    fn test_debug() {
        let config = ChaosConfig::gentle();
        let debug = format!("{:?}", config);
        assert!(debug.contains("ChaosConfig"));
        assert!(debug.contains("memory_limit"));
    }

    // === Individual builder method tests ===

    #[test]
    fn test_with_memory_limit_zero() {
        let config = ChaosConfig::new().with_memory_limit(0);
        assert_eq!(config.memory_limit, 0);
    }

    #[test]
    fn test_with_memory_limit_large() {
        let config = ChaosConfig::new().with_memory_limit(1024 * 1024 * 1024); // 1 GB
        assert_eq!(config.memory_limit, 1024 * 1024 * 1024);
    }

    #[test]
    fn test_with_timeout_zero() {
        let config = ChaosConfig::new().with_timeout(Duration::ZERO);
        assert_eq!(config.timeout, Duration::ZERO);
    }

    #[test]
    fn test_with_signal_injection_false() {
        let config = ChaosConfig::new().with_signal_injection(false);
        assert!(!config.signal_injection);
    }

    #[test]
    fn test_build_returns_self() {
        let config = ChaosConfig::new().with_memory_limit(50);
        let built = config.build();
        assert_eq!(built.memory_limit, 50);
    }

    // === ChaosError tests ===

    #[test]
    fn test_chaos_error_memory_limit_exceeded() {
        let err = ChaosError::MemoryLimitExceeded {
            limit: 500,
            used: 1000,
        };
        assert!(matches!(err, ChaosError::MemoryLimitExceeded { .. }));
    }

    #[test]
    fn test_chaos_error_timeout() {
        let err = ChaosError::Timeout {
            elapsed: Duration::from_secs(10),
            limit: Duration::from_secs(5),
        };
        assert!(matches!(err, ChaosError::Timeout { .. }));
    }

    #[test]
    fn test_chaos_error_signal_injection_failed() {
        let err = ChaosError::SignalInjectionFailed {
            signal: 15,
            reason: "Not permitted".to_string(),
        };
        assert!(matches!(err, ChaosError::SignalInjectionFailed { .. }));
    }

    #[test]
    fn test_chaos_error_clone() {
        let err = ChaosError::MemoryLimitExceeded {
            limit: 100,
            used: 200,
        };
        let cloned = err.clone();
        assert_eq!(cloned, err);
    }

    #[test]
    fn test_chaos_error_partial_eq() {
        let err1 = ChaosError::Timeout {
            elapsed: Duration::from_secs(1),
            limit: Duration::from_secs(1),
        };
        let err2 = ChaosError::Timeout {
            elapsed: Duration::from_secs(1),
            limit: Duration::from_secs(1),
        };
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_chaos_error_ne() {
        let err1 = ChaosError::Timeout {
            elapsed: Duration::from_secs(1),
            limit: Duration::from_secs(2),
        };
        let err2 = ChaosError::Timeout {
            elapsed: Duration::from_secs(3),
            limit: Duration::from_secs(2),
        };
        assert_ne!(err1, err2);
    }

    #[test]
    fn test_chaos_error_debug() {
        let err = ChaosError::SignalInjectionFailed {
            signal: 9,
            reason: "SIGKILL".to_string(),
        };
        let debug = format!("{:?}", err);
        assert!(debug.contains("SignalInjectionFailed"));
        assert!(debug.contains("9"));
    }

    #[test]
    fn test_chaos_error_is_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(ChaosError::MemoryLimitExceeded { limit: 1, used: 2 });
        assert!(err.to_string().contains("Memory limit exceeded"));
    }

    // === Original tests ===

    #[test]
    fn test_default_config() {
        let config = ChaosConfig::default();
        assert_eq!(config.memory_limit, 0);
        assert_eq!(config.cpu_limit, 0.0);
        assert_eq!(config.timeout, Duration::from_secs(60));
        assert!(!config.signal_injection);
    }

    #[test]
    fn test_gentle_preset() {
        let config = ChaosConfig::gentle();
        assert_eq!(config.memory_limit, 512 * 1024 * 1024);
        assert_eq!(config.cpu_limit, 0.8);
        assert_eq!(config.timeout, Duration::from_secs(120));
        assert!(!config.signal_injection);
    }

    #[test]
    fn test_aggressive_preset() {
        let config = ChaosConfig::aggressive();
        assert_eq!(config.memory_limit, 64 * 1024 * 1024);
        assert_eq!(config.cpu_limit, 0.25);
        assert_eq!(config.timeout, Duration::from_secs(10));
        assert!(config.signal_injection);
    }

    #[test]
    fn test_cpu_limit_clamping() {
        let over = ChaosConfig::new().with_cpu_limit(1.5);
        assert_eq!(over.cpu_limit, 1.0);

        let under = ChaosConfig::new().with_cpu_limit(-0.5);
        assert_eq!(under.cpu_limit, 0.0);

        let valid = ChaosConfig::new().with_cpu_limit(0.75);
        assert_eq!(valid.cpu_limit, 0.75);
    }

    #[test]
    fn test_builder_pattern() {
        let config = ChaosConfig::new()
            .with_memory_limit(100 * 1024 * 1024)
            .with_cpu_limit(0.5)
            .with_timeout(Duration::from_secs(30))
            .with_signal_injection(true)
            .build();

        assert_eq!(config.memory_limit, 100 * 1024 * 1024);
        assert_eq!(config.cpu_limit, 0.5);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert!(config.signal_injection);
    }

    #[test]
    fn test_chaos_error_display() {
        let mem_err = ChaosError::MemoryLimitExceeded {
            limit: 1000,
            used: 2000,
        };
        assert_eq!(
            mem_err.to_string(),
            "Memory limit exceeded: 2000 > 1000 bytes"
        );

        let timeout_err = ChaosError::Timeout {
            elapsed: Duration::from_secs(5),
            limit: Duration::from_secs(3),
        };
        assert!(timeout_err.to_string().contains("Timeout"));

        let signal_err = ChaosError::SignalInjectionFailed {
            signal: 9,
            reason: "Permission denied".to_string(),
        };
        assert_eq!(
            signal_err.to_string(),
            "Signal injection failed (9): Permission denied"
        );
    }
}