vortex-core 0.1.0

Core types and deterministic scheduler for Vortex simulation engine
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Fault configuration DSL — declarative fault injection rules.
//!
//! Users describe fault injection scenarios in a structured config that can
//! be serialized to/from YAML, TOML, or JSON. The [`FaultConfig`] is used by
//! all layers (SDK traits, syscall interceptor, WASM sandbox) to decide when
//! and how to inject faults.

use serde::{Deserialize, Serialize};

/// Top-level fault configuration.
///
/// ```
/// # use vortex_core::FaultConfig;
/// let yaml = r#"
///   fs:
///     rules:
///       - path: "*.wal"
///         op: write
///         error: enospc
///         after_bytes: 4096
///         probability: 0.05
///   clock:
///     drift_us_per_sec: 200
///     jitter_us: 50
///   alloc:
///     fail_probability: 0.001
///     hard_limit_bytes: 67108864
///   process:
///     rules:
///       - command: "gcc"
///         fault: hang
///         after_us: 5000000
///   threading:
///     strategy: random
///     preempt_probability: 0.1
/// "#;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FaultConfig {
    /// Filesystem fault rules.
    #[serde(default)]
    pub fs: FsFaultConfig,
    /// Clock fault configuration.
    #[serde(default)]
    pub clock: ClockFaultConfig,
    /// Memory allocator fault configuration.
    #[serde(default)]
    pub alloc: AllocFaultConfig,
    /// Subprocess fault rules.
    #[serde(default)]
    pub process: ProcessFaultConfig,
    /// Network fault rules (for local loopback interception).
    #[serde(default)]
    pub network: NetworkFaultConfig,
    /// Thread scheduling configuration (Layer 2 ptrace only).
    #[serde(default)]
    pub threading: ThreadSchedulingConfig,
}

impl FaultConfig {
    /// Create an empty configuration (no faults injected).
    pub fn none() -> Self {
        Self {
            fs: FsFaultConfig::default(),
            clock: ClockFaultConfig::default(),
            alloc: AllocFaultConfig::default(),
            process: ProcessFaultConfig::default(),
            network: NetworkFaultConfig::default(),
            threading: ThreadSchedulingConfig::default(),
        }
    }

    /// Merge two configs: `overlay` values take precedence over `base`.
    /// Rules are concatenated (not replaced).
    pub fn merge(base: &FaultConfig, overlay: &FaultConfig) -> FaultConfig {
        FaultConfig {
            fs: FsFaultConfig {
                rules: [base.fs.rules.clone(), overlay.fs.rules.clone()].concat(),
            },
            clock: if overlay.clock != ClockFaultConfig::default() {
                overlay.clock.clone()
            } else {
                base.clock.clone()
            },
            alloc: if overlay.alloc != AllocFaultConfig::default() {
                overlay.alloc.clone()
            } else {
                base.alloc.clone()
            },
            process: ProcessFaultConfig {
                rules: [base.process.rules.clone(), overlay.process.rules.clone()].concat(),
            },
            network: NetworkFaultConfig {
                rules: [base.network.rules.clone(), overlay.network.rules.clone()].concat(),
            },
            threading: if overlay.threading != ThreadSchedulingConfig::default() {
                overlay.threading.clone()
            } else {
                base.threading.clone()
            },
        }
    }

    /// Validate the configuration, returning a list of errors.
    pub fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();
        for (i, rule) in self.fs.rules.iter().enumerate() {
            if rule.probability < 0.0 || rule.probability > 1.0 {
                errors.push(ConfigError {
                    path: format!("fs.rules[{i}].probability"),
                    message: format!(
                        "probability must be in [0.0, 1.0], got {}",
                        rule.probability
                    ),
                });
            }
            if rule.path.is_empty() {
                errors.push(ConfigError {
                    path: format!("fs.rules[{i}].path"),
                    message: "path pattern must not be empty".into(),
                });
            }
        }
        if self.alloc.fail_probability < 0.0 || self.alloc.fail_probability > 1.0 {
            errors.push(ConfigError {
                path: "alloc.fail_probability".into(),
                message: format!("must be in [0.0, 1.0], got {}", self.alloc.fail_probability),
            });
        }
        if self.clock.jitter_us < 0 {
            errors.push(ConfigError {
                path: "clock.jitter_us".into(),
                message: format!("jitter must be non-negative, got {}", self.clock.jitter_us),
            });
        }
        for (i, rule) in self.process.rules.iter().enumerate() {
            if rule.command.is_empty() {
                errors.push(ConfigError {
                    path: format!("process.rules[{i}].command"),
                    message: "command pattern must not be empty".into(),
                });
            }
        }
        if self.threading.preempt_probability < 0.0 || self.threading.preempt_probability > 1.0 {
            errors.push(ConfigError {
                path: "threading.preempt_probability".into(),
                message: format!(
                    "must be in [0.0, 1.0], got {}",
                    self.threading.preempt_probability
                ),
            });
        }
        errors
    }

    /// Returns `true` if any fault injection is configured.
    pub fn has_faults(&self) -> bool {
        !self.fs.rules.is_empty()
            || self.clock != ClockFaultConfig::default()
            || self.alloc != AllocFaultConfig::default()
            || !self.process.rules.is_empty()
            || !self.network.rules.is_empty()
            || self.threading.is_enabled()
    }
}

impl Default for FaultConfig {
    fn default() -> Self {
        Self::none()
    }
}

// ---------------------------------------------------------------------------
// Filesystem faults
// ---------------------------------------------------------------------------

/// Filesystem fault injection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct FsFaultConfig {
    /// Ordered list of fault rules (first matching rule wins).
    #[serde(default)]
    pub rules: Vec<FsFaultRule>,
}

/// A single filesystem fault rule.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FsFaultRule {
    /// Glob pattern for matching file paths (e.g. `"*.wal"`, `"/data/**"`).
    pub path: String,
    /// Which operation to fault.
    #[serde(default)]
    pub op: FsOp,
    /// What error to inject.
    #[serde(default)]
    pub error: FsError,
    /// Inject error after this many bytes have been written (0 = immediately).
    #[serde(default)]
    pub after_bytes: u64,
    /// Probability of fault injection per operation [0.0, 1.0].
    #[serde(default = "default_probability")]
    pub probability: f64,
}

fn default_probability() -> f64 {
    1.0
}

/// Filesystem operation to target.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FsOp {
    Read,
    Write,
    Open,
    Fsync,
    Rename,
    Delete,
    /// Match any operation.
    #[default]
    Any,
}

/// Filesystem error to inject.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FsError {
    /// Disk full (ENOSPC).
    Enospc,
    /// I/O error (EIO).
    #[default]
    Eio,
    /// Permission denied (EACCES).
    Eacces,
    /// Torn write: partial write then error.
    TornWrite,
    /// Byte corruption in written data.
    Corrupt,
    /// Delayed fsync: fsync becomes a no-op, simulating data loss on crash.
    /// Writes succeed but are never durably committed.
    DelayedFsync,
}

// ---------------------------------------------------------------------------
// Clock faults
// ---------------------------------------------------------------------------

/// Clock fault injection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ClockFaultConfig {
    /// Clock drift in microseconds per second of logical time.
    #[serde(default)]
    pub drift_us_per_sec: i64,
    /// Random jitter added to each clock read, in microseconds.
    #[serde(default)]
    pub jitter_us: i64,
}

// ---------------------------------------------------------------------------
// Allocator faults
// ---------------------------------------------------------------------------

/// Memory allocator fault injection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct AllocFaultConfig {
    /// Probability of any single allocation failing [0.0, 1.0].
    #[serde(default)]
    pub fail_probability: f64,
    /// Hard limit on total heap bytes. All allocations after this are rejected.
    /// 0 = no limit.
    #[serde(default)]
    pub hard_limit_bytes: u64,
    /// Only fail allocations larger than this size (bytes). 0 = all sizes.
    #[serde(default)]
    pub min_fail_size: u64,
}

// ---------------------------------------------------------------------------
// Process faults
// ---------------------------------------------------------------------------

/// Subprocess fault injection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ProcessFaultConfig {
    /// Ordered list of subprocess fault rules.
    #[serde(default)]
    pub rules: Vec<ProcessFaultRule>,
}

/// A single subprocess fault rule.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProcessFaultRule {
    /// Glob pattern for matching command names (e.g. `"gcc"`, `"npm*"`).
    pub command: String,
    /// What kind of fault to inject.
    #[serde(default)]
    pub fault: ProcessFault,
    /// Inject the fault after this many microseconds of simulated runtime.
    /// 0 = immediately.
    #[serde(default)]
    pub after_us: u64,
}

/// Types of subprocess faults.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProcessFault {
    /// Process hangs indefinitely (never exits).
    Hang,
    /// Process is killed by SIGKILL (exit code 137).
    Sigkill,
    /// Process produces corrupted stdout.
    CorruptStdout,
    /// Process exits with a non-zero exit code.
    #[default]
    ExitError,
}

// ---------------------------------------------------------------------------
// Network faults
// ---------------------------------------------------------------------------

/// Network fault injection configuration (for local loopback interception).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct NetworkFaultConfig {
    /// Ordered list of network fault rules.
    #[serde(default)]
    pub rules: Vec<NetworkFaultRule>,
}

/// A single network fault rule.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NetworkFaultRule {
    /// Target address pattern (e.g. `"127.0.0.1:5432"`, `"*:8080"`).
    pub target: String,
    /// What kind of fault to inject.
    #[serde(default)]
    pub fault: NetworkFault,
    /// Probability of this fault being injected per connection/packet.
    #[serde(default = "default_probability")]
    pub probability: f64,
    /// Bandwidth limit in bytes per second (only applies to BandwidthLimit fault).
    /// 0 means unbounded.
    #[serde(default)]
    pub limit_bytes_per_sec: u64,
}

/// Types of network faults.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NetworkFault {
    /// Connection refused.
    #[default]
    ConnRefused,
    /// Connection timeout.
    ConnTimeout,
    /// Packet dropped silently.
    PacketDrop,
    /// Packet delay.
    PacketDelay,
    /// Packet data corrupted.
    PacketCorrupt,
    /// Bandwidth throttling based on bytes per second.
    BandwidthLimit,
}

// ---------------------------------------------------------------------------
// Thread scheduling
// ---------------------------------------------------------------------------

/// Thread scheduling configuration for deterministic thread interleaving.
///
/// Controls how the ptrace supervisor schedules threads when multiple are
/// runnable. Only effective in Layer 2 (ptrace interceptor).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThreadSchedulingConfig {
    /// Scheduling strategy for choosing which thread to run next.
    #[serde(default)]
    pub strategy: SchedulingStrategy,
    /// Probability of preempting a thread at each syscall boundary [0.0, 1.0].
    /// Higher values explore more interleavings but increase overhead.
    #[serde(default)]
    pub preempt_probability: f64,
}

impl Default for ThreadSchedulingConfig {
    fn default() -> Self {
        Self {
            strategy: SchedulingStrategy::default(),
            preempt_probability: 0.0,
        }
    }
}

impl ThreadSchedulingConfig {
    /// Returns `true` if deterministic thread scheduling is enabled.
    pub fn is_enabled(&self) -> bool {
        self.preempt_probability > 0.0
    }
}

/// Strategy for choosing which thread to schedule next.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SchedulingStrategy {
    /// Seed-driven random scheduling: use DetRng to pick the next thread.
    #[default]
    Random,
    /// Fixed round-robin: threads execute in a deterministic rotation.
    RoundRobin,
    /// Adversarial: always pick the thread most likely to cause races
    /// (e.g., the thread that last accessed shared state).
    Adversarial,
}

// ---------------------------------------------------------------------------
// Validation errors
// ---------------------------------------------------------------------------

/// A validation error in a fault configuration.
#[derive(Debug, Clone)]
pub struct ConfigError {
    /// Dot-separated path to the offending field (e.g. `"fs.rules[0].probability"`).
    pub path: String,
    /// Human-readable error message.
    pub message: String,
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.path, self.message)
    }
}

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

    #[test]
    fn test_default_config_has_no_faults() {
        let cfg = FaultConfig::none();
        assert!(!cfg.has_faults());
        assert!(cfg.validate().is_empty());
    }

    #[test]
    fn test_config_with_fs_fault() {
        let cfg = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "*.wal".into(),
                    op: FsOp::Write,
                    error: FsError::Enospc,
                    after_bytes: 4096,
                    probability: 0.05,
                }],
            },
            ..FaultConfig::none()
        };
        assert!(cfg.has_faults());
        assert!(cfg.validate().is_empty());
    }

    #[test]
    fn test_validate_bad_probability() {
        let cfg = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "*.log".into(),
                    op: FsOp::Write,
                    error: FsError::Eio,
                    after_bytes: 0,
                    probability: 1.5, // invalid
                }],
            },
            ..FaultConfig::none()
        };
        let errors = cfg.validate();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].path.contains("probability"));
    }

    #[test]
    fn test_validate_empty_path() {
        let cfg = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "".into(), // invalid
                    op: FsOp::Read,
                    error: FsError::Eio,
                    after_bytes: 0,
                    probability: 0.5,
                }],
            },
            ..FaultConfig::none()
        };
        let errors = cfg.validate();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].path.contains("path"));
    }

    #[test]
    fn test_merge_concatenates_rules() {
        let base = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "*.wal".into(),
                    op: FsOp::Write,
                    error: FsError::Enospc,
                    after_bytes: 4096,
                    probability: 0.05,
                }],
            },
            ..FaultConfig::none()
        };
        let overlay = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "*.log".into(),
                    op: FsOp::Read,
                    error: FsError::Eio,
                    after_bytes: 0,
                    probability: 0.01,
                }],
            },
            ..FaultConfig::none()
        };
        let merged = FaultConfig::merge(&base, &overlay);
        assert_eq!(merged.fs.rules.len(), 2);
        assert_eq!(merged.fs.rules[0].path, "*.wal");
        assert_eq!(merged.fs.rules[1].path, "*.log");
    }

    #[test]
    fn test_merge_overlay_clock_takes_precedence() {
        let base = FaultConfig {
            clock: ClockFaultConfig {
                drift_us_per_sec: 100,
                jitter_us: 50,
            },
            ..FaultConfig::none()
        };
        let overlay = FaultConfig {
            clock: ClockFaultConfig {
                drift_us_per_sec: 200,
                jitter_us: 10,
            },
            ..FaultConfig::none()
        };
        let merged = FaultConfig::merge(&base, &overlay);
        assert_eq!(merged.clock.drift_us_per_sec, 200);
        assert_eq!(merged.clock.jitter_us, 10);
    }

    #[test]
    fn test_serde_roundtrip() {
        let cfg = FaultConfig {
            fs: FsFaultConfig {
                rules: vec![FsFaultRule {
                    path: "/data/*.wal".into(),
                    op: FsOp::Write,
                    error: FsError::TornWrite,
                    after_bytes: 1024,
                    probability: 0.02,
                }],
            },
            clock: ClockFaultConfig {
                drift_us_per_sec: 200,
                jitter_us: 50,
            },
            alloc: AllocFaultConfig {
                fail_probability: 0.001,
                hard_limit_bytes: 67_108_864,
                min_fail_size: 0,
            },
            process: ProcessFaultConfig {
                rules: vec![ProcessFaultRule {
                    command: "gcc".into(),
                    fault: ProcessFault::Hang,
                    after_us: 5_000_000,
                }],
            },
            network: NetworkFaultConfig {
                rules: vec![NetworkFaultRule {
                    target: "127.0.0.1:5432".into(),
                    fault: NetworkFault::ConnTimeout,
                    probability: 0.1,
                    limit_bytes_per_sec: 0,
                }],
            },
            threading: ThreadSchedulingConfig {
                strategy: SchedulingStrategy::Random,
                preempt_probability: 0.1,
            },
        };
        let json = serde_json::to_string_pretty(&cfg).unwrap();
        let parsed: FaultConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(cfg, parsed);
    }

    #[test]
    fn test_threading_config_default_disabled() {
        let cfg = FaultConfig::none();
        assert!(!cfg.threading.is_enabled());
        assert_eq!(cfg.threading.strategy, SchedulingStrategy::Random);
        assert_eq!(cfg.threading.preempt_probability, 0.0);
    }

    #[test]
    fn test_threading_config_enabled() {
        let cfg = FaultConfig {
            threading: ThreadSchedulingConfig {
                strategy: SchedulingStrategy::Adversarial,
                preempt_probability: 0.5,
            },
            ..FaultConfig::none()
        };
        assert!(cfg.threading.is_enabled());
        assert!(cfg.has_faults());
    }

    #[test]
    fn test_validate_bad_preempt_probability() {
        let cfg = FaultConfig {
            threading: ThreadSchedulingConfig {
                strategy: SchedulingStrategy::Random,
                preempt_probability: 1.5,
            },
            ..FaultConfig::none()
        };
        let errors = cfg.validate();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].path.contains("threading"));
    }

    #[test]
    fn test_merge_threading_overlay() {
        let base = FaultConfig::none();
        let overlay = FaultConfig {
            threading: ThreadSchedulingConfig {
                strategy: SchedulingStrategy::RoundRobin,
                preempt_probability: 0.3,
            },
            ..FaultConfig::none()
        };
        let merged = FaultConfig::merge(&base, &overlay);
        assert_eq!(merged.threading.strategy, SchedulingStrategy::RoundRobin);
        assert_eq!(merged.threading.preempt_probability, 0.3);
    }

    #[test]
    fn test_serde_threading_roundtrip_json() {
        let json = r#"{
            "threading": {
                "strategy": "adversarial",
                "preempt_probability": 0.25
            }
        }"#;
        let cfg: FaultConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.threading.strategy, SchedulingStrategy::Adversarial);
        assert!((cfg.threading.preempt_probability - 0.25).abs() < f64::EPSILON);
    }
}