vortex-trace 0.1.0

Structured event tracing and replay for Vortex simulations
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
//! `vortex-trace` — Structured event tracing for deterministic simulation replay.
//!
//! Every significant event in the simulation is captured as a [`TraceEvent`].
//! Given the same seed, the trace is bit-for-bit identical — enabling:
//! - Post-mortem debugging of failed seeds
//! - Differential replay (compare two runs)
//! - Human-readable dump for manual inspection

pub mod determinism;
pub mod diagnosis;
pub mod minimize;
pub mod replay;
mod stats;

pub use determinism::{DeterminismResult, compare_traces, verify_determinism};
pub use diagnosis::{CausalEvent, DiagnosisReport, FaultCause, ViolationInfo, diagnose};
pub use minimize::{MinimizedTrace, minimize_faults, minimize_ticks};
pub use stats::SimStats;

use serde::{Deserialize, Serialize};
use vortex_core::NodeId;

/// A unique, monotonically increasing event identifier within a trace.
pub type EventId = u64;

/// A structured event captured during simulation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceEvent {
    /// Global event sequence number.
    pub event_id: EventId,
    /// Simulation tick when this event occurred.
    pub tick: u64,
    /// Node that originated this event (0 = cluster-level).
    pub node_id: NodeId,
    /// The event payload.
    pub kind: TraceEventKind,
}

/// The specific kind of trace event.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TraceEventKind {
    /// A message was sent from one node to another.
    MessageSent {
        to: NodeId,
        msg_type: String,
        size_bytes: usize,
    },
    /// A message was delivered to a node.
    MessageDelivered {
        from: NodeId,
        msg_type: String,
        size_bytes: usize,
    },
    /// A message was dropped.
    MessageDropped {
        from: NodeId,
        to: NodeId,
        reason: String,
    },
    /// A timer fired.
    TimerFired { timer_type: String },
    /// A state transition occurred.
    StateTransition {
        from_state: String,
        to_state: String,
        metadata: String,
    },
    /// A fault was injected.
    FaultInjected { fault_type: String, details: String },
    /// A fault was healed.
    FaultHealed { fault_type: String, details: String },
    /// A storage operation was applied.
    StorageOp { op_type: String, key_count: usize },
    /// A custom application event.
    Custom { tag: String, data: String },
}

/// Collects trace events during a simulation run.
///
/// Single-threaded by design — the simulation loop is single-threaded.
pub struct SimTrace {
    events: Vec<TraceEvent>,
    next_event_id: EventId,
}

impl SimTrace {
    /// Create an empty trace.
    pub fn new() -> Self {
        Self {
            events: Vec::new(),
            next_event_id: 0,
        }
    }

    /// Record a new event.
    pub fn record(&mut self, tick: u64, node_id: NodeId, kind: TraceEventKind) {
        self.events.push(TraceEvent {
            event_id: self.next_event_id,
            tick,
            node_id,
            kind,
        });
        self.next_event_id += 1;
    }

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

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

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

    /// Get events filtered by node ID.
    pub fn events_for_node(&self, node_id: NodeId) -> Vec<&TraceEvent> {
        self.events
            .iter()
            .filter(|e| e.node_id == node_id)
            .collect()
    }

    /// Get events matching a predicate.
    pub fn events_matching<F: Fn(&TraceEventKind) -> bool>(&self, f: F) -> Vec<&TraceEvent> {
        self.events.iter().filter(|e| f(&e.kind)).collect()
    }

    /// Filter events by tick range [start, end] (inclusive).
    pub fn events_between(&self, start_tick: u64, end_tick: u64) -> Vec<&TraceEvent> {
        self.events
            .iter()
            .filter(|e| e.tick >= start_tick && e.tick <= end_tick)
            .collect()
    }

    /// Get the last N events.
    pub fn last_n(&self, n: usize) -> &[TraceEvent] {
        let start = self.events.len().saturating_sub(n);
        &self.events[start..]
    }

    /// Follow the causal chain backward from an event.
    pub fn causal_chain(&self, event_id: EventId) -> Vec<&TraceEvent> {
        let mut chain = Vec::new();
        let mut current_id = event_id;
        let mut visited_nodes: std::collections::HashSet<NodeId> = std::collections::HashSet::new();

        let start = match self.events.iter().find(|e| e.event_id == current_id) {
            Some(e) => e,
            None => return chain,
        };

        chain.push(start);
        visited_nodes.insert(start.node_id);
        let mut current_tick = start.tick;

        for event in self.events.iter().rev() {
            if event.tick > current_tick || event.event_id >= current_id {
                continue;
            }
            if visited_nodes.contains(&event.node_id) {
                chain.push(event);
                current_id = event.event_id;
                current_tick = event.tick;
                if let TraceEventKind::MessageDelivered { from, .. } = &event.kind {
                    visited_nodes.insert(*from);
                }
                if chain.len() >= 100 {
                    break;
                }
            }
        }
        chain
    }

    /// Dump as human-readable text.
    pub fn dump_text(&self) -> String {
        let mut out = String::new();
        for event in &self.events {
            let kind_str = match &event.kind {
                TraceEventKind::MessageSent {
                    to,
                    msg_type,
                    size_bytes,
                } => format!("MSG_SENT to={to} type={msg_type} size={size_bytes}"),
                TraceEventKind::MessageDelivered {
                    from,
                    msg_type,
                    size_bytes,
                } => format!("MSG_RECV from={from} type={msg_type} size={size_bytes}"),
                TraceEventKind::MessageDropped { from, to, reason } => {
                    format!("MSG_DROP {from}->{to} reason={reason}")
                }
                TraceEventKind::TimerFired { timer_type } => format!("TIMER {timer_type}"),
                TraceEventKind::StateTransition {
                    from_state,
                    to_state,
                    metadata,
                } => format!("STATE {from_state}->{to_state} {metadata}"),
                TraceEventKind::FaultInjected {
                    fault_type,
                    details,
                } => format!("FAULT+ {fault_type}: {details}"),
                TraceEventKind::FaultHealed {
                    fault_type,
                    details,
                } => format!("FAULT- {fault_type}: {details}"),
                TraceEventKind::StorageOp { op_type, key_count } => {
                    format!("STORAGE {op_type} keys={key_count}")
                }
                TraceEventKind::Custom { tag, data } => format!("CUSTOM {tag}: {data}"),
            };
            out.push_str(&format!(
                "[t={:06} e={:06} n={}] {}\n",
                event.tick, event.event_id, event.node_id, kind_str
            ));
        }
        out
    }

    /// Dump as JSON.
    pub fn dump_json(&self) -> String {
        serde_json::to_string_pretty(&self.events).unwrap_or_else(|_| "[]".to_string())
    }

    /// Dump as JSON Lines (one JSON object per line).
    pub fn dump_jsonl(&self) -> String {
        let mut out = String::new();
        for event in &self.events {
            if let Ok(json) = serde_json::to_string(event) {
                out.push_str(&json);
                out.push('\n');
            }
        }
        out
    }

    /// Clear the trace.
    pub fn clear(&mut self) {
        self.events.clear();
        self.next_event_id = 0;
    }
}

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

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

    #[test]
    fn test_record_and_len() {
        let mut trace = SimTrace::new();
        assert!(trace.is_empty());
        trace.record(
            1,
            1,
            TraceEventKind::TimerFired {
                timer_type: "election".into(),
            },
        );
        trace.record(
            2,
            2,
            TraceEventKind::StorageOp {
                op_type: "put".into(),
                key_count: 3,
            },
        );
        assert_eq!(trace.len(), 2);
        assert_eq!(trace.events()[0].event_id, 0);
        assert_eq!(trace.events()[1].event_id, 1);
    }

    #[test]
    fn test_events_for_node() {
        let mut trace = SimTrace::new();
        trace.record(
            1,
            1,
            TraceEventKind::TimerFired {
                timer_type: "a".into(),
            },
        );
        trace.record(
            2,
            2,
            TraceEventKind::TimerFired {
                timer_type: "b".into(),
            },
        );
        trace.record(
            3,
            1,
            TraceEventKind::TimerFired {
                timer_type: "c".into(),
            },
        );
        let node1 = trace.events_for_node(1);
        assert_eq!(node1.len(), 2);
    }

    #[test]
    fn test_events_matching() {
        let mut trace = SimTrace::new();
        trace.record(
            1,
            1,
            TraceEventKind::TimerFired {
                timer_type: "x".into(),
            },
        );
        trace.record(
            2,
            1,
            TraceEventKind::StorageOp {
                op_type: "put".into(),
                key_count: 1,
            },
        );
        trace.record(
            3,
            2,
            TraceEventKind::TimerFired {
                timer_type: "y".into(),
            },
        );
        let timers = trace.events_matching(|k| matches!(k, TraceEventKind::TimerFired { .. }));
        assert_eq!(timers.len(), 2);
    }

    #[test]
    fn test_dump_text() {
        let mut trace = SimTrace::new();
        trace.record(
            10,
            1,
            TraceEventKind::FaultInjected {
                fault_type: "partition".into(),
                details: "1<->2".into(),
            },
        );
        let text = trace.dump_text();
        assert!(text.contains("FAULT+ partition"));
        assert!(text.contains("[t=000010"));
    }

    #[test]
    fn test_json_roundtrip() {
        let mut trace = SimTrace::new();
        trace.record(
            1,
            1,
            TraceEventKind::MessageSent {
                to: 2,
                msg_type: "AppendEntries".into(),
                size_bytes: 128,
            },
        );
        let json = trace.dump_json();
        let parsed: Vec<TraceEvent> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].tick, 1);
    }

    #[test]
    fn test_deterministic_traces() {
        fn build() -> String {
            let mut trace = SimTrace::new();
            trace.record(
                1,
                1,
                TraceEventKind::StateTransition {
                    from_state: "Follower".into(),
                    to_state: "Leader".into(),
                    metadata: "term=1".into(),
                },
            );
            trace.dump_json()
        }
        assert_eq!(build(), build());
    }

    #[test]
    fn test_events_between() {
        let mut trace = SimTrace::new();
        for i in 0..10 {
            trace.record(
                i * 10,
                1,
                TraceEventKind::TimerFired {
                    timer_type: format!("t{i}"),
                },
            );
        }
        let between = trace.events_between(20, 50);
        assert_eq!(between.len(), 4); // ticks 20, 30, 40, 50
    }

    #[test]
    fn test_last_n() {
        let mut trace = SimTrace::new();
        for i in 0..10 {
            trace.record(
                i,
                1,
                TraceEventKind::TimerFired {
                    timer_type: format!("t{i}"),
                },
            );
        }
        let last3 = trace.last_n(3);
        assert_eq!(last3.len(), 3);
        assert_eq!(last3[0].tick, 7);
    }

    #[test]
    fn test_clear() {
        let mut trace = SimTrace::new();
        trace.record(
            1,
            1,
            TraceEventKind::TimerFired {
                timer_type: "x".into(),
            },
        );
        trace.clear();
        assert!(trace.is_empty());
    }
}