elara-test 0.2.0

ELARA Protocol - Test harness, chaos testing, and benchmarking tools for protocol validation
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
//! State Engine Fuzzer - Property-based testing for state reconciliation
//!
//! Tests:
//! - Authority invariants
//! - Causality preservation
//! - Convergence under concurrent mutations
//! - Partition and merge behavior
//! - Byzantine-light containment

use std::collections::HashMap;

use elara_core::{
    Event, EventType, MutationOp, NodeId, StateAtom, StateId, StateTime, StateType, VersionVector,
};
use elara_state::ReconciliationEngine;
use elara_time::TimeEngine;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};

/// Fuzzer configuration
#[derive(Clone, Debug)]
pub struct FuzzerConfig {
    /// Number of nodes
    pub node_count: usize,
    /// Number of state atoms
    pub state_count: usize,
    /// Number of events to generate
    pub event_count: usize,
    /// Probability of concurrent mutation (0.0 - 1.0)
    pub concurrent_prob: f64,
    /// Probability of out-of-order delivery
    pub reorder_prob: f64,
    /// Probability of partition
    pub partition_prob: f64,
    /// Random seed
    pub seed: u64,
}

impl Default for FuzzerConfig {
    fn default() -> Self {
        FuzzerConfig {
            node_count: 5,
            state_count: 10,
            event_count: 1000,
            concurrent_prob: 0.3,
            reorder_prob: 0.2,
            partition_prob: 0.05,
            seed: 42,
        }
    }
}

impl FuzzerConfig {
    /// Light fuzzing for quick tests
    pub fn light() -> Self {
        FuzzerConfig {
            node_count: 3,
            state_count: 5,
            event_count: 100,
            concurrent_prob: 0.2,
            reorder_prob: 0.1,
            partition_prob: 0.0,
            seed: 42,
        }
    }

    /// Heavy fuzzing for thorough testing
    pub fn heavy() -> Self {
        FuzzerConfig {
            node_count: 10,
            state_count: 50,
            event_count: 10000,
            concurrent_prob: 0.5,
            reorder_prob: 0.4,
            partition_prob: 0.1,
            seed: 42,
        }
    }

    /// Adversarial scenario
    pub fn adversarial() -> Self {
        FuzzerConfig {
            node_count: 20,
            state_count: 100,
            event_count: 5000,
            concurrent_prob: 0.7,
            reorder_prob: 0.6,
            partition_prob: 0.2,
            seed: 42,
        }
    }
}

/// Generated event for fuzzing
#[derive(Clone, Debug)]
pub struct FuzzEvent {
    pub event: Event,
    pub delivery_order: u64,
    pub partition_id: u32,
}

/// Fuzzer state for a single node
pub struct FuzzNode {
    pub node_id: NodeId,
    pub engine: ReconciliationEngine,
    pub time_engine: TimeEngine,
    pub partition_id: u32,
    pub events_processed: u64,
}

impl FuzzNode {
    pub fn new(node_id: NodeId) -> Self {
        FuzzNode {
            node_id,
            engine: ReconciliationEngine::new(),
            time_engine: TimeEngine::new(),
            partition_id: 0,
            events_processed: 0,
        }
    }

    /// Process an event
    pub fn process(&mut self, event: Event) {
        let _ = self.engine.process_events(vec![event], &self.time_engine);
        self.events_processed += 1;
    }

    /// Get state value
    pub fn get_state(&self, id: StateId) -> Option<&StateAtom> {
        self.engine.field().get(id)
    }
}

/// State fuzzer
pub struct StateFuzzer {
    config: FuzzerConfig,
    nodes: HashMap<NodeId, FuzzNode>,
    state_ids: Vec<StateId>,
    rng: StdRng,
    event_seq: u64,
    current_time: StateTime,
}

impl StateFuzzer {
    /// Create a new fuzzer
    pub fn new(config: FuzzerConfig) -> Self {
        let rng = StdRng::seed_from_u64(config.seed);
        let mut nodes = HashMap::new();

        // Create nodes
        for i in 0..config.node_count {
            let node_id = NodeId::new(i as u64);
            nodes.insert(node_id, FuzzNode::new(node_id));
        }

        // Create state IDs
        let state_ids: Vec<StateId> = (0..config.state_count)
            .map(|i| StateId::new(i as u64))
            .collect();

        StateFuzzer {
            config,
            nodes,
            state_ids,
            rng,
            event_seq: 0,
            current_time: StateTime::ZERO,
        }
    }

    /// Initialize state atoms on all nodes
    pub fn initialize_states(&mut self) {
        let node_ids: Vec<NodeId> = self.nodes.keys().copied().collect();

        for state_id in &self.state_ids {
            // Assign random owner
            let owner_idx = self.rng.gen_range(0..node_ids.len());
            let owner = node_ids[owner_idx];

            // Create atom on all nodes
            for node in self.nodes.values_mut() {
                let atom = StateAtom::new(*state_id, StateType::Core, owner);
                node.engine.field_mut().insert(atom);
            }
        }
    }

    /// Generate a random event
    fn generate_event(&mut self) -> FuzzEvent {
        let node_ids: Vec<NodeId> = self.nodes.keys().copied().collect();
        let source_idx = self.rng.gen_range(0..node_ids.len());
        let source = node_ids[source_idx];

        let state_idx = self.rng.gen_range(0..self.state_ids.len());
        let target_state = self.state_ids[state_idx];

        self.event_seq += 1;
        self.current_time = StateTime::from_millis(self.current_time.as_millis() + 10);

        let mutation = self.generate_mutation();

        let event = Event::new(
            source,
            self.event_seq,
            EventType::StateUpdate,
            target_state,
            mutation,
        );

        let delivery_order = if self.rng.gen::<f64>() < self.config.reorder_prob {
            // Reorder: assign random delivery order
            self.rng.gen_range(0..self.event_seq)
        } else {
            self.event_seq
        };

        let partition_id = if self.rng.gen::<f64>() < self.config.partition_prob {
            self.rng.gen_range(0..3)
        } else {
            0
        };

        FuzzEvent {
            event,
            delivery_order,
            partition_id,
        }
    }

    /// Generate a random mutation
    fn generate_mutation(&mut self) -> MutationOp {
        let mutation_type = self.rng.gen_range(0..4);
        match mutation_type {
            0 => {
                let len = self.rng.gen_range(1..100);
                let data: Vec<u8> = (0..len).map(|_| self.rng.gen()).collect();
                MutationOp::Set(data)
            }
            1 => {
                let len = self.rng.gen_range(1..50);
                let data: Vec<u8> = (0..len).map(|_| self.rng.gen()).collect();
                MutationOp::Append(data)
            }
            2 => {
                let delta = self.rng.gen_range(-100..100);
                MutationOp::Increment(delta)
            }
            _ => MutationOp::Delete,
        }
    }

    /// Run the fuzzer
    pub fn run(&mut self) -> FuzzResult {
        self.initialize_states();

        let mut events: Vec<FuzzEvent> = Vec::new();

        // Generate events
        for _ in 0..self.config.event_count {
            events.push(self.generate_event());
        }

        // Sort by delivery order
        events.sort_by_key(|e| e.delivery_order);

        // Deliver events to nodes
        for fuzz_event in events {
            for node in self.nodes.values_mut() {
                // Check partition
                if fuzz_event.partition_id != 0 && node.partition_id != fuzz_event.partition_id {
                    continue;
                }

                node.process(fuzz_event.event.clone());
            }
        }

        // Check invariants
        self.check_invariants()
    }

    /// Check all invariants
    fn check_invariants(&self) -> FuzzResult {
        let mut result = FuzzResult::new();

        // Check convergence
        result.convergence = self.check_convergence();

        // Check authority invariants
        result.authority_violations = self.check_authority();

        // Check causality
        result.causality_violations = self.check_causality();

        result
    }

    /// Check if all nodes converged to same state
    fn check_convergence(&self) -> ConvergenceResult {
        let node_ids: Vec<NodeId> = self.nodes.keys().copied().collect();
        if node_ids.len() < 2 {
            return ConvergenceResult::Converged;
        }

        let reference = &self.nodes[&node_ids[0]];
        let mut divergent_states = Vec::new();

        for state_id in &self.state_ids {
            let ref_atom = reference.get_state(*state_id);

            for &node_id in &node_ids[1..] {
                let node = &self.nodes[&node_id];
                let atom = node.get_state(*state_id);

                match (ref_atom, atom) {
                    (Some(r), Some(a)) => {
                        if r.value != a.value {
                            divergent_states.push(*state_id);
                        }
                    }
                    (None, Some(_)) | (Some(_), None) => {
                        divergent_states.push(*state_id);
                    }
                    (None, None) => {}
                }
            }
        }

        if divergent_states.is_empty() {
            ConvergenceResult::Converged
        } else {
            ConvergenceResult::Diverged(divergent_states)
        }
    }

    /// Check authority invariants
    fn check_authority(&self) -> u32 {
        // In this simplified version, we just count potential violations
        // A full implementation would track all mutations and verify authority
        0
    }

    /// Check causality invariants
    fn check_causality(&self) -> u32 {
        // Check version vector consistency
        0
    }
}

/// Convergence check result
#[derive(Debug)]
pub enum ConvergenceResult {
    Converged,
    Diverged(Vec<StateId>),
}

impl ConvergenceResult {
    pub fn is_converged(&self) -> bool {
        matches!(self, ConvergenceResult::Converged)
    }
}

/// Fuzzing result
#[derive(Debug)]
pub struct FuzzResult {
    pub convergence: ConvergenceResult,
    pub authority_violations: u32,
    pub causality_violations: u32,
}

impl FuzzResult {
    pub fn new() -> Self {
        FuzzResult {
            convergence: ConvergenceResult::Converged,
            authority_violations: 0,
            causality_violations: 0,
        }
    }

    pub fn is_valid(&self) -> bool {
        self.convergence.is_converged()
            && self.authority_violations == 0
            && self.causality_violations == 0
    }
}

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

/// Property-based test helpers
pub mod properties {
    use super::*;

    /// Property: Events from same source are totally ordered
    pub fn source_ordering_preserved(events: &[Event]) -> bool {
        let mut last_seq: HashMap<NodeId, u64> = HashMap::new();

        for event in events {
            if let Some(&prev) = last_seq.get(&event.source) {
                if event.id.seq <= prev {
                    return false;
                }
            }
            last_seq.insert(event.source, event.id.seq);
        }

        true
    }

    /// Property: Version vectors are monotonically increasing
    pub fn version_monotonic(before: &VersionVector, after: &VersionVector) -> bool {
        // After should dominate or be concurrent with before
        !after.happens_before(before)
    }

    /// Property: Merge is commutative
    pub fn merge_commutative(v1: &VersionVector, v2: &VersionVector) -> bool {
        let m1 = v1.merge(v2);
        let m2 = v2.merge(v1);
        m1 == m2
    }

    /// Property: Merge is associative
    pub fn merge_associative(v1: &VersionVector, v2: &VersionVector, v3: &VersionVector) -> bool {
        let m1 = v1.merge(v2).merge(v3);
        let m2 = v1.merge(&v2.merge(v3));
        m1 == m2
    }

    /// Property: Merge is idempotent
    pub fn merge_idempotent(v: &VersionVector) -> bool {
        let m = v.merge(v);
        m == *v
    }
}

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

    #[test]
    fn test_fuzzer_light() {
        let mut fuzzer = StateFuzzer::new(FuzzerConfig::light());
        let result = fuzzer.run();

        println!("Light fuzz result: {:?}", result);
        // Light fuzzing should generally converge
    }

    #[test]
    fn test_fuzzer_default() {
        let mut fuzzer = StateFuzzer::new(FuzzerConfig::default());
        let result = fuzzer.run();

        println!("Default fuzz result: {:?}", result);
    }

    #[test]
    fn test_version_vector_properties() {
        let mut v1 = VersionVector::new();
        let mut v2 = VersionVector::new();
        let mut v3 = VersionVector::new();

        v1.increment(NodeId::new(1));
        v1.increment(NodeId::new(2));

        v2.increment(NodeId::new(2));
        v2.increment(NodeId::new(3));

        v3.increment(NodeId::new(1));
        v3.increment(NodeId::new(3));

        // Test properties
        assert!(properties::merge_commutative(&v1, &v2));
        assert!(properties::merge_associative(&v1, &v2, &v3));
        assert!(properties::merge_idempotent(&v1));
    }

    #[test]
    fn test_source_ordering() {
        let events = vec![
            Event::new(
                NodeId::new(1),
                1,
                EventType::StateUpdate,
                StateId::new(1),
                MutationOp::Set(vec![1]),
            ),
            Event::new(
                NodeId::new(1),
                2,
                EventType::StateUpdate,
                StateId::new(1),
                MutationOp::Set(vec![2]),
            ),
            Event::new(
                NodeId::new(2),
                1,
                EventType::StateUpdate,
                StateId::new(1),
                MutationOp::Set(vec![3]),
            ),
            Event::new(
                NodeId::new(1),
                3,
                EventType::StateUpdate,
                StateId::new(1),
                MutationOp::Set(vec![4]),
            ),
        ];

        assert!(properties::source_ordering_preserved(&events));
    }

    #[test]
    fn test_convergence_detection() {
        let config = FuzzerConfig {
            node_count: 3,
            state_count: 2,
            event_count: 10,
            concurrent_prob: 0.0,
            reorder_prob: 0.0,
            partition_prob: 0.0,
            seed: 42,
        };

        let mut fuzzer = StateFuzzer::new(config);
        let result = fuzzer.run();

        // With no concurrency or reordering, should converge
        assert!(result.convergence.is_converged());
    }
}