chronon 0.1.0

Deterministic execution kernel with crash-safe replication and exactly-once side effects
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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use serde::{Deserialize, Serialize};

/// Types of operations that can be recorded.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Operation {
    /// Deposit operation.
    Deposit { user: String, amount: u64 },
    /// Withdrawal operation.
    Withdrawal { user: String, amount: u64 },
    /// Balance query.
    Query { user: String },
}

/// Result of an operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OperationResult {
    /// Operation succeeded.
    Success {
        /// For queries, this is the balance. For deposits/withdrawals, this is the new balance.
        balance: Option<u64>,
    },
    /// Operation failed.
    Failure { reason: String },
    /// Operation is pending (not yet committed).
    Pending,
    /// Operation was redirected to another node.
    Redirected { to_node: Option<u32> },
}

/// A single entry in the operation history.
#[derive(Debug, Clone)]
pub struct HistoryEntry {
    /// When the operation was initiated.
    pub timestamp: Instant,
    /// Client that initiated the operation.
    pub client_id: u64,
    /// Sequence number for this client.
    pub sequence_number: u64,
    /// The operation performed.
    pub operation: Operation,
    /// The result of the operation.
    pub result: OperationResult,
    /// Log index where this was committed (if applicable).
    pub log_index: Option<u64>,
}

/// Global history log for all operations.
#[derive(Debug, Default)]
pub struct History {
    /// All recorded entries.
    entries: Vec<HistoryEntry>,
    /// Index by client_id and sequence_number.
    by_client: HashMap<(u64, u64), usize>,
}

impl History {
    pub fn new() -> Self {
        History {
            entries: Vec::new(),
            by_client: HashMap::new(),
        }
    }

    /// Record an operation.
    pub fn record(
        &mut self,
        client_id: u64,
        sequence_number: u64,
        operation: Operation,
        result: OperationResult,
        log_index: Option<u64>,
    ) {
        let entry = HistoryEntry {
            timestamp: Instant::now(),
            client_id,
            sequence_number,
            operation,
            result,
            log_index,
        };

        let idx = self.entries.len();
        self.entries.push(entry);
        self.by_client.insert((client_id, sequence_number), idx);
    }

    pub fn entries(&self) -> &[HistoryEntry] {
        &self.entries
    }

    /// Get entry by client and sequence number.
    pub fn get(&self, client_id: u64, sequence_number: u64) -> Option<&HistoryEntry> {
        self.by_client
            .get(&(client_id, sequence_number))
            .and_then(|&idx| self.entries.get(idx))
    }

    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if history is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all entries.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.by_client.clear();
    }
}

/// Thread-safe history wrapper.
pub struct SharedHistory {
    inner: Arc<Mutex<History>>,
}

impl SharedHistory {
    /// Create a new shared history.
    pub fn new() -> Self {
        SharedHistory {
            inner: Arc::new(Mutex::new(History::new())),
        }
    }

    /// Record an operation.
    pub fn record(
        &self,
        client_id: u64,
        sequence_number: u64,
        operation: Operation,
        result: OperationResult,
        log_index: Option<u64>,
    ) {
        let mut history = self.inner.lock().unwrap();
        history.record(client_id, sequence_number, operation, result, log_index);
    }

    /// Get a clone of the inner history for analysis.
    pub fn snapshot(&self) -> History {
        let history = self.inner.lock().unwrap();
        History {
            entries: history.entries.clone(),
            by_client: history.by_client.clone(),
        }
    }

    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.inner.lock().unwrap().len()
    }

    /// Check if history is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.lock().unwrap().is_empty()
    }

    /// Clear all entries.
    pub fn clear(&self) {
        self.inner.lock().unwrap().clear();
    }

    /// Clone the Arc for sharing.
    pub fn clone_arc(&self) -> Self {
        SharedHistory {
            inner: self.inner.clone(),
        }
    }
}

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

impl Clone for SharedHistory {
    fn clone(&self) -> Self {
        self.clone_arc()
    }
}

/// Result of a consistency check.
#[derive(Debug, Clone)]
pub struct CheckResult {
    /// Whether all checks passed.
    pub passed: bool,
    /// List of violations found.
    pub violations: Vec<Violation>,
    /// Statistics about the check.
    pub stats: CheckStats,
}

/// A consistency violation.
#[derive(Debug, Clone)]
pub struct Violation {
    /// Type of violation.
    pub kind: ViolationKind,
    /// Description of the violation.
    pub description: String,
    /// Related history entries (by index).
    pub related_entries: Vec<usize>,
}

/// Types of consistency violations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViolationKind {
    /// Value was not conserved (money appeared or disappeared).
    ValueNotConserved,
    /// Balance decreased without a withdrawal (time travel).
    TimeTravel,
    /// Duplicate operation was executed twice.
    DuplicateExecution,
    /// Operation ordering violation.
    OrderingViolation,
}

/// Statistics from the consistency check.
#[derive(Debug, Clone, Default)]
pub struct CheckStats {
    /// Total operations checked.
    pub total_operations: usize,
    /// Successful operations.
    pub successful_operations: usize,
    /// Failed operations.
    pub failed_operations: usize,
    /// Redirected operations.
    pub redirected_operations: usize,
    /// Total deposits.
    pub total_deposits: u64,
    /// Total withdrawals.
    pub total_withdrawals: u64,
    /// Final total balance.
    pub final_total_balance: u64,
    /// Expected total balance.
    pub expected_total_balance: u64,
}

/// The consistency checker (Oracle).
pub struct Checker {
    /// Initial balances for each user.
    initial_balances: HashMap<String, u64>,
}

impl Checker {
    /// Create a new checker with initial balances.
    pub fn new(initial_balances: HashMap<String, u64>) -> Self {
        Checker { initial_balances }
    }

    /// Create a checker with no initial balances.
    pub fn empty() -> Self {
        Checker {
            initial_balances: HashMap::new(),
        }
    }

    /// Verify linearizability and consistency invariants.
    pub fn verify(&self, history: &History, final_balances: &HashMap<String, u64>) -> CheckResult {
        let mut violations = Vec::new();
        let mut stats = CheckStats::default();

        // Track per-user balance observations for time travel detection
        let mut user_observations: HashMap<String, Vec<(usize, u64)>> = HashMap::new();

        // Track successful operations by (client_id, sequence_number) for duplicate detection
        let mut successful_ops: HashMap<(u64, u64), usize> = HashMap::new();

        // Process all entries
        for (idx, entry) in history.entries().iter().enumerate() {
            stats.total_operations += 1;

            match &entry.result {
                OperationResult::Success { balance } => {
                    stats.successful_operations += 1;

                    // Check for duplicate execution
                    let key = (entry.client_id, entry.sequence_number);
                    if let Some(&prev_idx) = successful_ops.get(&key) {
                        violations.push(Violation {
                            kind: ViolationKind::DuplicateExecution,
                            description: format!(
                                "Operation (client={}, seq={}) executed twice at entries {} and {}",
                                entry.client_id, entry.sequence_number, prev_idx, idx
                            ),
                            related_entries: vec![prev_idx, idx],
                        });
                    } else {
                        successful_ops.insert(key, idx);
                    }

                    // Track deposits and withdrawals
                    match &entry.operation {
                        Operation::Deposit { user, amount } => {
                            stats.total_deposits += amount;
                            if let Some(bal) = balance {
                                user_observations
                                    .entry(user.clone())
                                    .or_default()
                                    .push((idx, *bal));
                            }
                        }
                        Operation::Withdrawal { user, amount } => {
                            stats.total_withdrawals += amount;
                            if let Some(bal) = balance {
                                user_observations
                                    .entry(user.clone())
                                    .or_default()
                                    .push((idx, *bal));
                            }
                        }
                        Operation::Query { user } => {
                            if let Some(bal) = balance {
                                user_observations
                                    .entry(user.clone())
                                    .or_default()
                                    .push((idx, *bal));
                            }
                        }
                    }
                }
                OperationResult::Failure { .. } => {
                    stats.failed_operations += 1;
                }
                OperationResult::Redirected { .. } => {
                    stats.redirected_operations += 1;
                }
                OperationResult::Pending => {
                    // Pending operations don't count
                }
            }
        }

        // Check time travel: balance should not decrease without withdrawal
        for (user, observations) in &user_observations {
            let mut last_balance: Option<u64> = None;
            let mut last_idx: Option<usize> = None;

            for &(idx, balance) in observations {
                if let Some(prev_balance) = last_balance {
                    // Check if balance decreased
                    if balance < prev_balance {
                        // Check if there was a withdrawal between these observations
                        let had_withdrawal = history.entries()[last_idx.unwrap()..=idx]
                            .iter()
                            .any(|e| {
                                matches!(
                                    (&e.operation, &e.result),
                                    (
                                        Operation::Withdrawal { user: u, .. },
                                        OperationResult::Success { .. }
                                    ) if u == user
                                )
                            });

                        if !had_withdrawal {
                            violations.push(Violation {
                                kind: ViolationKind::TimeTravel,
                                description: format!(
                                    "User {} balance decreased from {} to {} without withdrawal (entries {} to {})",
                                    user, prev_balance, balance, last_idx.unwrap(), idx
                                ),
                                related_entries: vec![last_idx.unwrap(), idx],
                            });
                        }
                    }
                }
                last_balance = Some(balance);
                last_idx = Some(idx);
            }
        }

        // Check conservation of value
        let initial_total: u64 = self.initial_balances.values().sum();
        let expected_total = initial_total + stats.total_deposits - stats.total_withdrawals;
        let actual_total: u64 = final_balances.values().sum();

        stats.expected_total_balance = expected_total;
        stats.final_total_balance = actual_total;

        if expected_total != actual_total {
            violations.push(Violation {
                kind: ViolationKind::ValueNotConserved,
                description: format!(
                    "Value not conserved: initial={}, deposits={}, withdrawals={}, expected={}, actual={}",
                    initial_total, stats.total_deposits, stats.total_withdrawals, expected_total, actual_total
                ),
                related_entries: vec![],
            });
        }

        CheckResult {
            passed: violations.is_empty(),
            violations,
            stats,
        }
    }

    /// Quick check that just verifies value conservation.
    pub fn verify_conservation(
        &self,
        total_deposits: u64,
        total_withdrawals: u64,
        final_total: u64,
    ) -> bool {
        let initial_total: u64 = self.initial_balances.values().sum();
        let expected = initial_total + total_deposits - total_withdrawals;
        expected == final_total
    }
}

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

    #[test]
    fn test_history_recording() {
        let mut history = History::new();

        history.record(
            1,
            1,
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 100,
            },
            OperationResult::Success { balance: Some(100) },
            Some(0),
        );

        assert_eq!(history.len(), 1);
        let entry = history.get(1, 1).unwrap();
        assert_eq!(entry.client_id, 1);
        assert_eq!(entry.sequence_number, 1);
    }

    #[test]
    fn test_checker_conservation() {
        let checker = Checker::empty();

        let mut history = History::new();

        // Deposit 100
        history.record(
            1,
            1,
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 100,
            },
            OperationResult::Success { balance: Some(100) },
            Some(0),
        );

        // Deposit 50
        history.record(
            1,
            2,
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 50,
            },
            OperationResult::Success { balance: Some(150) },
            Some(1),
        );

        // Withdraw 30
        history.record(
            1,
            3,
            Operation::Withdrawal {
                user: "Alice".to_string(),
                amount: 30,
            },
            OperationResult::Success { balance: Some(120) },
            Some(2),
        );

        let mut final_balances = HashMap::new();
        final_balances.insert("Alice".to_string(), 120);

        let result = checker.verify(&history, &final_balances);
        assert!(result.passed, "Violations: {:?}", result.violations);
        assert_eq!(result.stats.total_deposits, 150);
        assert_eq!(result.stats.total_withdrawals, 30);
    }

    #[test]
    fn test_checker_detects_value_loss() {
        let checker = Checker::empty();

        let mut history = History::new();

        // Deposit 100
        history.record(
            1,
            1,
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 100,
            },
            OperationResult::Success { balance: Some(100) },
            Some(0),
        );

        // Final balance is wrong (should be 100, but is 50)
        let mut final_balances = HashMap::new();
        final_balances.insert("Alice".to_string(), 50);

        let result = checker.verify(&history, &final_balances);
        assert!(!result.passed);
        assert!(result
            .violations
            .iter()
            .any(|v| v.kind == ViolationKind::ValueNotConserved));
    }

    #[test]
    fn test_checker_detects_duplicate() {
        let checker = Checker::empty();

        let mut history = History::new();

        // Same operation recorded twice as successful
        history.record(
            1,
            1,
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 100,
            },
            OperationResult::Success { balance: Some(100) },
            Some(0),
        );

        history.record(
            1,
            1, // Same client_id and sequence_number
            Operation::Deposit {
                user: "Alice".to_string(),
                amount: 100,
            },
            OperationResult::Success { balance: Some(200) },
            Some(1),
        );

        let mut final_balances = HashMap::new();
        final_balances.insert("Alice".to_string(), 200);

        let result = checker.verify(&history, &final_balances);
        assert!(!result.passed);
        assert!(result
            .violations
            .iter()
            .any(|v| v.kind == ViolationKind::DuplicateExecution));
    }
}