Skip to main content

qualia_core_db/net/qdnf/harness/
faults.rs

1//! Loss, reorder, duplicate, corruption, delay and partition injection.
2
3use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::harness::partition::PartitionGate;
5
6pub const PIPE_SLOTS: usize = 8;
7pub const FRAME_CAP: usize = 512;
8
9#[repr(u8)]
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum Fault {
12    None = 0,
13    Drop = 1,
14    Duplicate = 2,
15    Reorder = 3,
16    Corrupt = 4,
17    Truncate = 5,
18    Delay = 6,
19    Partition = 7,
20}
21
22#[derive(Clone, Copy, Debug)]
23pub struct FaultSchedule {
24    pub pattern: [Fault; PIPE_SLOTS],
25    pub index: usize,
26}
27
28impl FaultSchedule {
29    /// `FaultSchedule::never`.
30    pub const fn never() -> Self {
31        Self {
32            pattern: [Fault::None; PIPE_SLOTS],
33            index: 0,
34        }
35    }
36
37    /// Builder: sets `pattern`.
38    pub const fn with_pattern(pattern: [Fault; PIPE_SLOTS]) -> Self {
39        Self { pattern, index: 0 }
40    }
41
42    /// Next scheduled fault (drop/delay/partition).
43    pub fn next(&mut self) -> Fault {
44        let f = self.pattern[self.index % self.pattern.len()];
45        self.index = self.index.wrapping_add(1);
46        f
47    }
48
49    /// In-place mutate for Drop/Corrupt/Truncate. Duplicate/Reorder/Delay/Partition
50    /// need [`FaultPipe`]; this helper does not queue.
51    pub fn apply<'a>(&self, fault: Fault, frame: &'a mut [u8]) -> Option<&'a [u8]> {
52        match fault {
53            Fault::None => Some(frame),
54            Fault::Drop | Fault::Partition => None,
55            Fault::Duplicate | Fault::Reorder | Fault::Delay => Some(frame),
56            Fault::Corrupt => {
57                if !frame.is_empty() {
58                    frame[0] ^= 0xff;
59                }
60                Some(frame)
61            }
62            Fault::Truncate => {
63                if frame.len() > 4 {
64                    Some(&frame[..frame.len() / 2])
65                } else {
66                    None
67                }
68            }
69        }
70    }
71}
72
73#[derive(Clone, Copy)]
74struct Slot {
75    len: u16,
76    delay: u8,
77    bytes: [u8; FRAME_CAP],
78}
79
80impl Slot {
81    const EMPTY: Self = Self {
82        len: 0,
83        delay: 0,
84        bytes: [0u8; FRAME_CAP],
85    };
86}
87
88/// Bounded eight-slot pipe. Duplicate, reorder and delay actually queue.
89pub struct FaultPipe {
90    schedule: FaultSchedule,
91    slots: [Slot; PIPE_SLOTS],
92    len: usize,
93    gate: PartitionGate,
94}
95
96impl FaultPipe {
97    /// Creates a default `FaultPipe`.
98    pub const fn new() -> Self {
99        Self::with_schedule(FaultSchedule::never())
100    }
101
102    /// Builder: `schedule`.
103    pub const fn with_schedule(schedule: FaultSchedule) -> Self {
104        Self {
105            schedule,
106            slots: [Slot::EMPTY; PIPE_SLOTS],
107            len: 0,
108            gate: PartitionGate::open(),
109        }
110    }
111
112    /// `FaultPipe::queued`.
113    pub const fn queued(&self) -> usize {
114        self.len
115    }
116
117    /// `true` when `partitioned`.
118    pub const fn is_partitioned(&self) -> bool {
119        self.gate.is_partitioned()
120    }
121
122    /// Cuts the pipe — pushes fail until `heal`.
123    pub fn partition(&mut self) {
124        self.gate.partition();
125    }
126
127    /// Restores the pipe.
128    pub fn heal(&mut self) {
129        self.gate.heal();
130    }
131
132    /// Drop in-flight slots. Does not model crash-consistent storage (QA-01.06).
133    pub fn restart(&mut self) {
134        self.slots = [Slot::EMPTY; PIPE_SLOTS];
135        self.len = 0;
136        self.gate.heal();
137    }
138
139    /// Decrement delay on every queued slot so delayed/reordered frames can complete.
140    pub fn tick(&mut self) {
141        let mut i = 0;
142        while i < self.len {
143            if self.slots[i].delay > 0 {
144                self.slots[i].delay -= 1;
145            }
146            i += 1;
147        }
148    }
149
150    /// Pushes `frame` through the fault-injecting pipe; may drop/queue per schedule.
151    pub fn push(&mut self, frame: &[u8]) -> Result<(), QdnfError> {
152        self.gate.admit()?;
153        if frame.len() > FRAME_CAP {
154            return Err(QdnfError::Capacity);
155        }
156        let fault = self.schedule.next();
157        match fault {
158            Fault::None => self.enqueue(frame, 0),
159            Fault::Drop => Ok(()),
160            Fault::Duplicate => {
161                if self.len + 2 > PIPE_SLOTS {
162                    return Err(QdnfError::Capacity);
163                }
164                self.enqueue(frame, 0)?;
165                self.enqueue(frame, 0)
166            }
167            Fault::Reorder => self.enqueue(frame, 1),
168            Fault::Corrupt => {
169                let mut tmp = [0u8; FRAME_CAP];
170                tmp[..frame.len()].copy_from_slice(frame);
171                if !frame.is_empty() {
172                    tmp[0] ^= 0xff;
173                }
174                self.enqueue(&tmp[..frame.len()], 0)
175            }
176            Fault::Truncate => {
177                if frame.len() > 4 {
178                    self.enqueue(&frame[..frame.len() / 2], 0)
179                } else {
180                    Ok(())
181                }
182            }
183            Fault::Delay => self.enqueue(frame, 1),
184            Fault::Partition => {
185                self.gate.partition();
186                Err(QdnfError::WouldBlock)
187            }
188        }
189    }
190
191    /// Pops a frame into `out`; returns bytes read.
192    pub fn pop(&mut self, out: &mut [u8]) -> Result<usize, QdnfError> {
193        self.gate.admit()?;
194        let mut i = 0;
195        while i < self.len {
196            if self.slots[i].delay == 0 {
197                let n = self.slots[i].len as usize;
198                if out.len() < n {
199                    return Err(QdnfError::Capacity);
200                }
201                if n > 0 {
202                    out[..n].copy_from_slice(&self.slots[i].bytes[..n]);
203                }
204                self.remove(i);
205                return Ok(n);
206            }
207            i += 1;
208        }
209        Err(QdnfError::WouldBlock)
210    }
211
212    fn enqueue(&mut self, frame: &[u8], delay: u8) -> Result<(), QdnfError> {
213        if self.len >= PIPE_SLOTS {
214            return Err(QdnfError::Capacity);
215        }
216        let slot = &mut self.slots[self.len];
217        slot.len = frame.len() as u16;
218        slot.delay = delay;
219        if !frame.is_empty() {
220            slot.bytes[..frame.len()].copy_from_slice(frame);
221        }
222        self.len += 1;
223        Ok(())
224    }
225
226    fn remove(&mut self, i: usize) {
227        let mut j = i;
228        while j + 1 < self.len {
229            self.slots[j] = self.slots[j + 1];
230            j += 1;
231        }
232        self.len -= 1;
233        self.slots[self.len] = Slot::EMPTY;
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    fn pattern(first: Fault) -> FaultSchedule {
242        let mut pattern = [Fault::None; PIPE_SLOTS];
243        pattern[0] = first;
244        FaultSchedule::with_pattern(pattern)
245    }
246
247    #[test]
248    fn success() {
249        let mut pipe = FaultPipe::new();
250        let frame = [1u8, 2, 3, 4];
251        pipe.push(&frame).unwrap();
252        let mut out = [0u8; 8];
253        let n = pipe.pop(&mut out).unwrap();
254        assert_eq!(&out[..n], &frame);
255        assert_eq!(pipe.pop(&mut out), Err(QdnfError::WouldBlock));
256    }
257
258    #[test]
259    fn drop_discards() {
260        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Drop));
261        pipe.push(&[9, 8, 7, 6]).unwrap();
262        assert_eq!(pipe.queued(), 0);
263        let mut out = [0u8; 8];
264        assert_eq!(pipe.pop(&mut out), Err(QdnfError::WouldBlock));
265    }
266
267    #[test]
268    fn partition_heal() {
269        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Partition));
270        assert_eq!(pipe.push(&[1, 2, 3, 4]), Err(QdnfError::WouldBlock));
271        assert!(pipe.is_partitioned());
272        let mut out = [0u8; 8];
273        assert_eq!(pipe.pop(&mut out), Err(QdnfError::WouldBlock));
274        pipe.heal();
275        pipe.push(&[1, 2, 3, 4]).unwrap();
276        let n = pipe.pop(&mut out).unwrap();
277        assert_eq!(&out[..n], &[1, 2, 3, 4]);
278    }
279
280    #[test]
281    fn corrupt() {
282        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Corrupt));
283        pipe.push(&[0x0f, 0x00]).unwrap();
284        let mut out = [0u8; 8];
285        let n = pipe.pop(&mut out).unwrap();
286        assert_eq!(&out[..n], &[0xf0, 0x00]);
287    }
288
289    #[test]
290    fn truncate() {
291        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Truncate));
292        pipe.push(&[1, 2, 3, 4, 5, 6, 7, 8]).unwrap();
293        let mut out = [0u8; 8];
294        let n = pipe.pop(&mut out).unwrap();
295        assert_eq!(&out[..n], &[1, 2, 3, 4]);
296    }
297
298    #[test]
299    fn duplicate_queues_two() {
300        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Duplicate));
301        pipe.push(&[7, 7]).unwrap();
302        assert_eq!(pipe.queued(), 2);
303        let mut out = [0u8; 8];
304        let n1 = pipe.pop(&mut out).unwrap();
305        assert_eq!(&out[..n1], &[7, 7]);
306        let n2 = pipe.pop(&mut out).unwrap();
307        assert_eq!(&out[..n2], &[7, 7]);
308    }
309
310    #[test]
311    fn reorder_lets_later_frame_complete_first() {
312        let mut pattern = [Fault::None; PIPE_SLOTS];
313        pattern[0] = Fault::Reorder;
314        let mut pipe = FaultPipe::with_schedule(FaultSchedule::with_pattern(pattern));
315        pipe.push(&[1]).unwrap();
316        pipe.push(&[2]).unwrap();
317        let mut out = [0u8; 8];
318        let n1 = pipe.pop(&mut out).unwrap();
319        assert_eq!(&out[..n1], &[2]);
320        pipe.tick();
321        let n2 = pipe.pop(&mut out).unwrap();
322        assert_eq!(&out[..n2], &[1]);
323    }
324
325    #[test]
326    fn delay_completes_after_tick() {
327        let mut pipe = FaultPipe::with_schedule(pattern(Fault::Delay));
328        pipe.push(&[3, 4]).unwrap();
329        let mut out = [0u8; 8];
330        assert_eq!(pipe.pop(&mut out), Err(QdnfError::WouldBlock));
331        pipe.tick();
332        let n = pipe.pop(&mut out).unwrap();
333        assert_eq!(&out[..n], &[3, 4]);
334    }
335
336    #[test]
337    fn restart_drops_inflight() {
338        let mut pipe = FaultPipe::new();
339        pipe.push(&[1, 2]).unwrap();
340        pipe.restart();
341        assert_eq!(pipe.queued(), 0);
342        let mut out = [0u8; 8];
343        assert_eq!(pipe.pop(&mut out), Err(QdnfError::WouldBlock));
344        pipe.push(&[9]).unwrap();
345        let n = pipe.pop(&mut out).unwrap();
346        assert_eq!(&out[..n], &[9]);
347    }
348}