Skip to main content

cbtop/adversarial/
resources.rs

1//! Resource limiting, bit-flip injection, cancellation, and recovery.
2
3use std::time::{Duration, Instant};
4
5use super::{AdversarialError, AdversarialResult, ResourceUsage};
6
7/// Bit-flip injector for testing corruption handling
8#[derive(Debug, Clone)]
9pub struct BitFlipInjector {
10    /// Seed for reproducible bit flips
11    pub seed: u64,
12    /// Number of bits to flip
13    pub flip_count: usize,
14}
15
16impl Default for BitFlipInjector {
17    fn default() -> Self {
18        Self {
19            seed: 42,
20            flip_count: 1,
21        }
22    }
23}
24
25impl BitFlipInjector {
26    /// Create a new bit-flip injector
27    pub fn new(seed: u64, flip_count: usize) -> Self {
28        Self { seed, flip_count }
29    }
30
31    /// Inject bit flips into data (returns modified copy)
32    pub fn inject(&self, data: &[u8]) -> Vec<u8> {
33        let mut result = data.to_vec();
34        if result.is_empty() {
35            return result;
36        }
37
38        // Simple LCG for reproducible "random" positions
39        let mut rng_state = self.seed;
40        for _ in 0..self.flip_count {
41            // LCG: next = (a * state + c) mod m
42            rng_state = rng_state
43                .wrapping_mul(6364136223846793005)
44                .wrapping_add(1442695040888963407);
45
46            let byte_idx = (rng_state as usize) % result.len();
47            let bit_idx = ((rng_state >> 32) as usize) % 8;
48
49            result[byte_idx] ^= 1 << bit_idx;
50        }
51
52        result
53    }
54
55    /// Inject bit flips into float data
56    pub fn inject_floats(&self, data: &[f32]) -> Vec<f32> {
57        // Convert to bytes, flip bits, convert back
58        let bytes: Vec<u8> = data.iter().flat_map(|f| f.to_le_bytes()).collect();
59
60        let corrupted = self.inject(&bytes);
61
62        corrupted
63            .as_chunks::<4>()
64            .0
65            .iter()
66            .map(|chunk| f32::from_le_bytes(*chunk))
67            .collect()
68    }
69}
70
71/// Resource limiter for bounded operations (F1016, F1017, F1018)
72#[derive(Debug, Clone)]
73pub struct ResourceLimiter {
74    /// Maximum stack depth for recursive operations
75    pub max_stack_depth: usize,
76    /// Maximum memory allocation in bytes
77    pub max_memory_bytes: usize,
78    /// Timeout for operations
79    pub timeout: Duration,
80    /// Current stack depth
81    current_depth: usize,
82    /// Current allocated memory
83    current_memory: usize,
84    /// Operation start time
85    start_time: Option<Instant>,
86}
87
88impl Default for ResourceLimiter {
89    fn default() -> Self {
90        Self {
91            max_stack_depth: 1000,
92            max_memory_bytes: 1024 * 1024 * 1024, // 1GB
93            timeout: Duration::from_secs(60),
94            current_depth: 0,
95            current_memory: 0,
96            start_time: None,
97        }
98    }
99}
100
101impl ResourceLimiter {
102    /// Create a new resource limiter
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    /// Set maximum stack depth
108    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
109        self.max_stack_depth = max_depth;
110        self
111    }
112
113    /// Set maximum memory
114    pub fn with_max_memory(mut self, max_bytes: usize) -> Self {
115        self.max_memory_bytes = max_bytes;
116        self
117    }
118
119    /// Set timeout
120    pub fn with_timeout(mut self, timeout: Duration) -> Self {
121        self.timeout = timeout;
122        self
123    }
124
125    /// Start a timed operation
126    pub fn start_operation(&mut self) {
127        self.start_time = Some(Instant::now());
128    }
129
130    /// Check if operation has timed out (F1018)
131    pub fn check_timeout(&self, operation: &str) -> AdversarialResult<()> {
132        if let Some(start) = self.start_time {
133            let elapsed = start.elapsed();
134            if elapsed > self.timeout {
135                return Err(AdversarialError::Timeout {
136                    operation: operation.to_string(),
137                    elapsed,
138                    limit: self.timeout,
139                });
140            }
141        }
142        Ok(())
143    }
144
145    /// Enter a recursive call (F1016)
146    pub fn enter_recursion(&mut self) -> AdversarialResult<()> {
147        self.current_depth += 1;
148        if self.current_depth > self.max_stack_depth {
149            return Err(AdversarialError::StackOverflow {
150                depth: self.current_depth,
151                max_depth: self.max_stack_depth,
152            });
153        }
154        Ok(())
155    }
156
157    /// Exit a recursive call
158    pub fn exit_recursion(&mut self) {
159        if self.current_depth > 0 {
160            self.current_depth -= 1;
161        }
162    }
163
164    /// Request memory allocation (F1017)
165    pub fn request_memory(&mut self, bytes: usize) -> AdversarialResult<()> {
166        let new_total = self.current_memory.saturating_add(bytes);
167        if new_total > self.max_memory_bytes {
168            return Err(AdversarialError::ResourceExhausted {
169                resource: format!(
170                    "memory: requested {bytes} bytes, would exceed limit of {} bytes",
171                    self.max_memory_bytes
172                ),
173            });
174        }
175        self.current_memory = new_total;
176        Ok(())
177    }
178
179    /// Release memory
180    pub fn release_memory(&mut self, bytes: usize) {
181        self.current_memory = self.current_memory.saturating_sub(bytes);
182    }
183
184    /// Get current resource usage
185    pub fn usage(&self) -> ResourceUsage {
186        ResourceUsage {
187            stack_depth: self.current_depth,
188            memory_bytes: self.current_memory,
189            elapsed: self.start_time.map(|s| s.elapsed()),
190        }
191    }
192
193    /// Reset limiter state
194    pub fn reset(&mut self) {
195        self.current_depth = 0;
196        self.current_memory = 0;
197        self.start_time = None;
198    }
199}
200
201/// Cancellation token for cooperative cancellation (F1019)
202#[derive(Debug, Clone)]
203pub struct CancellationToken {
204    cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
205}
206
207impl Default for CancellationToken {
208    fn default() -> Self {
209        Self::new()
210    }
211}
212
213impl CancellationToken {
214    /// Create a new cancellation token
215    pub fn new() -> Self {
216        Self {
217            cancelled: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
218        }
219    }
220
221    /// Request cancellation
222    pub fn cancel(&self) {
223        self.cancelled
224            .store(true, std::sync::atomic::Ordering::SeqCst);
225    }
226
227    /// Check if cancelled
228    pub fn is_cancelled(&self) -> bool {
229        self.cancelled.load(std::sync::atomic::Ordering::SeqCst)
230    }
231
232    /// Return error if cancelled
233    pub fn check(&self, operation: &str) -> AdversarialResult<()> {
234        if self.is_cancelled() {
235            return Err(AdversarialError::Cancelled {
236                operation: operation.to_string(),
237            });
238        }
239        Ok(())
240    }
241
242    /// Clone the token (same underlying state)
243    pub fn clone_token(&self) -> Self {
244        Self {
245            cancelled: std::sync::Arc::clone(&self.cancelled),
246        }
247    }
248}
249
250/// Recovery handler for error recovery testing (F1020)
251#[derive(Debug, Clone)]
252pub struct RecoveryHandler<S: Clone> {
253    /// Stored checkpoint state
254    checkpoint: Option<S>,
255}
256
257impl<S: Clone> Default for RecoveryHandler<S> {
258    fn default() -> Self {
259        Self::new()
260    }
261}
262
263impl<S: Clone> RecoveryHandler<S> {
264    /// Create a new recovery handler
265    pub fn new() -> Self {
266        Self { checkpoint: None }
267    }
268
269    /// Save a checkpoint
270    pub fn checkpoint(&mut self, state: S) {
271        self.checkpoint = Some(state);
272    }
273
274    /// Recover from error using checkpoint
275    pub fn recover(&self) -> AdversarialResult<S> {
276        self.checkpoint
277            .clone()
278            .ok_or_else(|| AdversarialError::RecoveryFailed {
279                original_error: "unknown".to_string(),
280                recovery_error: "no checkpoint available".to_string(),
281            })
282    }
283
284    /// Try operation with automatic recovery on failure
285    pub fn try_with_recovery<F, T, E>(&self, operation: F) -> AdversarialResult<T>
286    where
287        F: FnOnce() -> Result<T, E>,
288        E: std::fmt::Display,
289    {
290        match operation() {
291            Ok(result) => Ok(result),
292            Err(e) => Err(AdversarialError::RecoveryFailed {
293                original_error: e.to_string(),
294                recovery_error: if self.checkpoint.is_some() {
295                    "operation failed, checkpoint available".to_string()
296                } else {
297                    "operation failed, no checkpoint".to_string()
298                },
299            }),
300        }
301    }
302
303    /// Check if checkpoint exists
304    pub fn has_checkpoint(&self) -> bool {
305        self.checkpoint.is_some()
306    }
307}