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
//! Simulation context and event logging.
//!
//! [`SimContext`] is the central state holder for a single simulation run.
//! It owns the seed, logical clock, fault configuration, and the structured
//! event log. Every simulated action flows through the context so that
//! two runs with the same seed produce identical [`SimEventLog`]s.

use crate::rng::DetRng;
use crate::seed::{SeedTree, VortexSeed};
use std::fmt;

/// Monotonic sequence counter for event ordering within a simulation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SeqNo(pub u64);

/// A single recorded simulation event.
#[derive(Debug, Clone)]
pub struct SimLogEntry {
    /// Monotonic sequence number (unique within a simulation run).
    pub seq: SeqNo,
    /// Logical timestamp (microseconds) when this event occurred.
    pub timestamp_us: u64,
    /// Which subsystem produced this event.
    pub subsystem: Subsystem,
    /// Human-readable description of what happened.
    pub description: String,
    /// Optional structured payload (for machine comparison).
    pub payload: Option<Vec<u8>>,
}

/// Subsystem tags for event categorisation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Subsystem {
    /// Async executor / task scheduling.
    Executor,
    /// Virtual file system.
    Fs,
    /// Logical clock / timers.
    Clock,
    /// Memory allocator.
    Alloc,
    /// Network (existing distributed sim).
    Network,
    /// Subprocess / process spawning.
    Process,
    /// Storage (existing KV sim).
    Storage,
    /// User / custom subsystem.
    Custom,
}

impl fmt::Display for Subsystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Subsystem::Executor => write!(f, "executor"),
            Subsystem::Fs => write!(f, "fs"),
            Subsystem::Clock => write!(f, "clock"),
            Subsystem::Alloc => write!(f, "alloc"),
            Subsystem::Network => write!(f, "network"),
            Subsystem::Process => write!(f, "process"),
            Subsystem::Storage => write!(f, "storage"),
            Subsystem::Custom => write!(f, "custom"),
        }
    }
}

/// Structured event log for a simulation run.
///
/// Records every simulated action with monotonic sequence numbers.
/// Two runs with the same seed should produce identical logs — use
/// [`SimEventLog::diff`] to verify this and pinpoint the first divergence.
pub struct SimEventLog {
    entries: Vec<SimLogEntry>,
    next_seq: u64,
}

impl SimEventLog {
    /// Create a new, empty event log.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            next_seq: 0,
        }
    }

    /// Record an event. Returns the assigned sequence number.
    pub fn record(
        &mut self,
        timestamp_us: u64,
        subsystem: Subsystem,
        description: String,
        payload: Option<Vec<u8>>,
    ) -> SeqNo {
        let seq = SeqNo(self.next_seq);
        self.next_seq += 1;
        self.entries.push(SimLogEntry {
            seq,
            timestamp_us,
            subsystem,
            description,
            payload,
        });
        seq
    }

    /// Record a simple event (no payload).
    pub fn record_simple(
        &mut self,
        timestamp_us: u64,
        subsystem: Subsystem,
        description: impl Into<String>,
    ) -> SeqNo {
        self.record(timestamp_us, subsystem, description.into(), None)
    }

    /// Get all entries.
    pub fn entries(&self) -> &[SimLogEntry] {
        &self.entries
    }

    /// Number of recorded events.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the log is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Compare two event logs and find the first point of divergence.
    ///
    /// Returns `None` if the logs are identical (same length, same descriptions,
    /// same subsystems, same payloads at every sequence number).
    /// Returns `Some(divergence)` with details about where they first differ.
    pub fn diff(a: &SimEventLog, b: &SimEventLog) -> Option<LogDivergence> {
        let min_len = a.entries.len().min(b.entries.len());
        for i in 0..min_len {
            let ea = &a.entries[i];
            let eb = &b.entries[i];
            if ea.subsystem != eb.subsystem
                || ea.description != eb.description
                || ea.timestamp_us != eb.timestamp_us
                || ea.payload != eb.payload
            {
                return Some(LogDivergence {
                    seq: SeqNo(i as u64),
                    entry_a: ea.clone(),
                    entry_b: eb.clone(),
                    kind: DivergenceKind::ContentMismatch,
                });
            }
        }
        if a.entries.len() != b.entries.len() {
            let longer = if a.entries.len() > b.entries.len() {
                "a"
            } else {
                "b"
            };
            return Some(LogDivergence {
                seq: SeqNo(min_len as u64),
                entry_a: a
                    .entries
                    .get(min_len)
                    .cloned()
                    .unwrap_or_else(|| SimLogEntry {
                        seq: SeqNo(min_len as u64),
                        timestamp_us: 0,
                        subsystem: Subsystem::Custom,
                        description: format!("<log {longer} has no more entries>"),
                        payload: None,
                    }),
                entry_b: b
                    .entries
                    .get(min_len)
                    .cloned()
                    .unwrap_or_else(|| SimLogEntry {
                        seq: SeqNo(min_len as u64),
                        timestamp_us: 0,
                        subsystem: Subsystem::Custom,
                        description: format!("<log {longer} has no more entries>"),
                        payload: None,
                    }),
                kind: DivergenceKind::LengthMismatch {
                    len_a: a.entries.len(),
                    len_b: b.entries.len(),
                },
            });
        }
        None
    }
}

impl Default for SimEventLog {
    fn default() -> Self {
        Self::new()
    }
}

/// Description of where two event logs first diverge.
#[derive(Debug, Clone)]
pub struct LogDivergence {
    /// Sequence number at which divergence was detected.
    pub seq: SeqNo,
    /// Entry from log A at that position.
    pub entry_a: SimLogEntry,
    /// Entry from log B at that position.
    pub entry_b: SimLogEntry,
    /// What kind of divergence.
    pub kind: DivergenceKind,
}

/// The kind of divergence found between two logs.
#[derive(Debug, Clone)]
pub enum DivergenceKind {
    /// The entries at the same sequence number have different content.
    ContentMismatch,
    /// The logs have different lengths.
    LengthMismatch { len_a: usize, len_b: usize },
}

impl fmt::Display for LogDivergence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            DivergenceKind::ContentMismatch => {
                write!(
                    f,
                    "Divergence at seq {}: A=[{}] {:?} vs B=[{}] {:?}",
                    self.seq.0,
                    self.entry_a.subsystem,
                    self.entry_a.description,
                    self.entry_b.subsystem,
                    self.entry_b.description,
                )
            }
            DivergenceKind::LengthMismatch { len_a, len_b } => {
                write!(
                    f,
                    "Length mismatch at seq {}: log A has {} entries, log B has {} entries",
                    self.seq.0, len_a, len_b,
                )
            }
        }
    }
}

/// Central simulation context.
///
/// Holds the master seed, seed tree, logical clock, and event log for a
/// single simulation run. Pass a reference to `SimContext` into every
/// subsystem that needs deterministic randomness or event logging.
pub struct SimContext {
    seed: VortexSeed,
    seed_tree: SeedTree,
    logical_time_us: u64,
    event_log: SimEventLog,
}

impl SimContext {
    /// Create a new simulation context from a master seed.
    pub fn new(seed: VortexSeed) -> Self {
        Self {
            seed,
            seed_tree: SeedTree::new(seed),
            logical_time_us: 0,
            event_log: SimEventLog::new(),
        }
    }

    /// Create from a simple u64 seed.
    pub fn from_u64(seed: u64) -> Self {
        Self::new(VortexSeed::from_u64(seed))
    }

    /// Get the master seed.
    pub fn seed(&self) -> VortexSeed {
        self.seed
    }

    /// Get the seed tree for deriving subsystem-specific RNGs.
    pub fn seed_tree(&self) -> &SeedTree {
        &self.seed_tree
    }

    /// Create a [`DetRng`] for a specific subsystem domain.
    pub fn rng_for(&self, domain: &str) -> DetRng {
        let sub_seed = self.seed_tree.derive(domain);
        DetRng::new(sub_seed.to_u64())
    }

    /// Get the current logical time in microseconds.
    pub fn logical_time_us(&self) -> u64 {
        self.logical_time_us
    }

    /// Advance logical time by the given microseconds.
    pub fn advance_time_us(&mut self, delta_us: u64) {
        self.logical_time_us += delta_us;
    }

    /// Set logical time to an absolute value.
    pub fn set_time_us(&mut self, time_us: u64) {
        self.logical_time_us = time_us;
    }

    /// Record an event in the event log.
    pub fn log_event(&mut self, subsystem: Subsystem, description: impl Into<String>) -> SeqNo {
        self.event_log
            .record_simple(self.logical_time_us, subsystem, description)
    }

    /// Record an event with a payload.
    pub fn log_event_with_payload(
        &mut self,
        subsystem: Subsystem,
        description: impl Into<String>,
        payload: Vec<u8>,
    ) -> SeqNo {
        self.event_log.record(
            self.logical_time_us,
            subsystem,
            description.into(),
            Some(payload),
        )
    }

    /// Get a reference to the event log.
    pub fn event_log(&self) -> &SimEventLog {
        &self.event_log
    }

    /// Take ownership of the event log (consumes the context).
    pub fn into_event_log(self) -> SimEventLog {
        self.event_log
    }
}

impl fmt::Debug for SimContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SimContext")
            .field("seed", &self.seed)
            .field("logical_time_us", &self.logical_time_us)
            .field("events_recorded", &self.event_log.len())
            .finish()
    }
}

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

    #[test]
    fn test_context_creation() {
        let ctx = SimContext::from_u64(42);
        assert_eq!(ctx.seed(), VortexSeed::from_u64(42));
        assert_eq!(ctx.logical_time_us(), 0);
        assert!(ctx.event_log().is_empty());
    }

    #[test]
    fn test_context_time_advance() {
        let mut ctx = SimContext::from_u64(42);
        ctx.advance_time_us(1000);
        assert_eq!(ctx.logical_time_us(), 1000);
        ctx.advance_time_us(500);
        assert_eq!(ctx.logical_time_us(), 1500);
    }

    #[test]
    fn test_context_event_logging() {
        let mut ctx = SimContext::from_u64(42);
        ctx.advance_time_us(100);
        let seq1 = ctx.log_event(Subsystem::Fs, "open /data/wal.log");
        ctx.advance_time_us(50);
        let seq2 = ctx.log_event(Subsystem::Fs, "write 4096 bytes");

        assert_eq!(seq1, SeqNo(0));
        assert_eq!(seq2, SeqNo(1));
        assert_eq!(ctx.event_log().len(), 2);
        assert_eq!(ctx.event_log().entries()[0].timestamp_us, 100);
        assert_eq!(ctx.event_log().entries()[1].timestamp_us, 150);
    }

    #[test]
    fn test_context_deterministic_rngs() {
        let ctx1 = SimContext::from_u64(42);
        let ctx2 = SimContext::from_u64(42);

        let mut rng1 = ctx1.rng_for("fs");
        let mut rng2 = ctx2.rng_for("fs");
        let seq1: Vec<u64> = (0..100).map(|_| rng1.next_u64()).collect();
        let seq2: Vec<u64> = (0..100).map(|_| rng2.next_u64()).collect();
        assert_eq!(seq1, seq2);
    }

    #[test]
    fn test_context_different_domains_different_rngs() {
        let ctx = SimContext::from_u64(42);
        let mut fs_rng = ctx.rng_for("fs");
        let mut net_rng = ctx.rng_for("net");
        assert_ne!(fs_rng.next_u64(), net_rng.next_u64());
    }

    #[test]
    fn test_event_log_diff_identical() {
        let mut log1 = SimEventLog::new();
        let mut log2 = SimEventLog::new();
        log1.record_simple(0, Subsystem::Fs, "open file");
        log1.record_simple(100, Subsystem::Fs, "write data");
        log2.record_simple(0, Subsystem::Fs, "open file");
        log2.record_simple(100, Subsystem::Fs, "write data");
        assert!(SimEventLog::diff(&log1, &log2).is_none());
    }

    #[test]
    fn test_event_log_diff_content_mismatch() {
        let mut log1 = SimEventLog::new();
        let mut log2 = SimEventLog::new();
        log1.record_simple(0, Subsystem::Fs, "open file A");
        log2.record_simple(0, Subsystem::Fs, "open file B");

        let d = SimEventLog::diff(&log1, &log2).unwrap();
        assert_eq!(d.seq, SeqNo(0));
        assert!(matches!(d.kind, DivergenceKind::ContentMismatch));
    }

    #[test]
    fn test_event_log_diff_length_mismatch() {
        let mut log1 = SimEventLog::new();
        let mut log2 = SimEventLog::new();
        log1.record_simple(0, Subsystem::Fs, "open file");
        log1.record_simple(100, Subsystem::Fs, "write data");
        log2.record_simple(0, Subsystem::Fs, "open file");

        let d = SimEventLog::diff(&log1, &log2).unwrap();
        assert_eq!(d.seq, SeqNo(1));
        assert!(matches!(
            d.kind,
            DivergenceKind::LengthMismatch { len_a: 2, len_b: 1 }
        ));
    }

    #[test]
    fn test_event_log_diff_display() {
        let mut log1 = SimEventLog::new();
        let mut log2 = SimEventLog::new();
        log1.record_simple(0, Subsystem::Executor, "wake task A");
        log2.record_simple(0, Subsystem::Executor, "wake task B");

        let d = SimEventLog::diff(&log1, &log2).unwrap();
        let display = format!("{d}");
        assert!(display.contains("Divergence"));
        assert!(display.contains("task A"));
        assert!(display.contains("task B"));
    }
}