feltdb 0.4.1

Embedded durable state store: an append-only log with atomic multi-record transactions, version-conditional writes, and idempotent retries
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
/// Convergence layer module for distributed state consistency
/// Provides causal state versioning, conflict resolution, and deterministic merge
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;

/// Vector clock for tracking causality in distributed systems
/// Each instance maintains a logical clock value
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct VectorClock {
    /// Map of instance_id to logical clock value
    pub clocks: HashMap<String, u64>,
}

impl VectorClock {
    /// Create a new vector clock
    pub fn new() -> Self {
        Self {
            clocks: HashMap::new(),
        }
    }

    /// Create a vector clock from a HashMap
    pub fn from_clocks(clocks: HashMap<String, u64>) -> Self {
        Self { clocks }
    }

    /// Increment the clock for a specific instance
    pub fn increment(&mut self, instance_id: &str) {
        let entry = self.clocks.entry(instance_id.to_string()).or_insert(0);
        *entry += 1;
    }

    /// Get the clock value for an instance
    pub fn get(&self, instance_id: &str) -> u64 {
        *self.clocks.get(instance_id).unwrap_or(&0)
    }

    /// Merge with another vector clock (takes maximum for each instance)
    pub fn merge(&mut self, other: &VectorClock) {
        for (instance_id, other_clock) in &other.clocks {
            let entry = self.clocks.entry(instance_id.clone()).or_insert(0);
            *entry = (*entry).max(*other_clock);
        }
    }

    /// Check if this clock causally precedes another
    pub fn happens_before(&self, other: &VectorClock) -> bool {
        let mut at_least_one_less = false;

        for (instance_id, other_value) in &other.clocks {
            let self_value = self.get(instance_id);
            if self_value > *other_value {
                return false; // This clock is ahead in some dimension
            }
            if self_value < *other_value {
                at_least_one_less = true;
            }
        }

        // Also check if self has clocks that other doesn't (or other is behind on them)
        for (instance_id, self_value) in &self.clocks {
            let other_value = other.get(instance_id);
            if self_value > &other_value {
                return false;
            }
        }

        at_least_one_less
    }

    /// Check if two clocks are concurrent (neither happens before the other)
    pub fn is_concurrent(&self, other: &VectorClock) -> bool {
        !self.happens_before(other) && !other.happens_before(self)
    }

    /// True when this clock has seen at least everything `other` has, in every
    /// dimension.
    ///
    /// This is the test a causal receiver needs, and it is not `happens_before`.
    /// `happens_before` answers a question about ordering and returns false for
    /// concurrent clocks, so a receiver using it would admit an operation whose
    /// dependencies are genuinely unmet whenever the frontier happened to be
    /// ahead in some unrelated dimension. Dominance asks only "have I seen
    /// everything this operation needs", which is what eligibility means.
    pub fn dominates(&self, other: &VectorClock) -> bool {
        other
            .clocks
            .iter()
            .all(|(instance_id, required)| self.get(instance_id) >= *required)
    }

    /// Compare two vector clocks for causal ordering
    pub fn causal_cmp(&self, other: &VectorClock) -> Ordering {
        if self == other {
            return Ordering::Equal;
        }

        if self.happens_before(other) {
            Ordering::Less
        } else if other.happens_before(self) {
            Ordering::Greater
        } else {
            // Concurrent - use lexicographic comparison of instance IDs as tiebreaker
            let all_instances: std::collections::BTreeSet<_> =
                self.clocks.keys().chain(other.clocks.keys()).collect();

            for instance_id in all_instances {
                let self_val = self.get(instance_id);
                let other_val = other.get(instance_id);
                if self_val != other_val {
                    return if self_val < other_val {
                        Ordering::Less
                    } else {
                        Ordering::Greater
                    };
                }
            }
            Ordering::Equal
        }
    }
}

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

/// State version representing a causal snapshot of the system
/// Tracks which instance is at which logical clock value
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct StateVersion {
    /// Vector clock representing this state
    pub vector_clock: VectorClock,
    /// Timestamp when this version was created (ms since UNIX epoch)
    pub timestamp_ms: u128,
}

impl StateVersion {
    /// Create a new state version
    pub fn new(vector_clock: VectorClock, timestamp_ms: u128) -> Self {
        Self {
            vector_clock,
            timestamp_ms,
        }
    }

    /// Create a state version from clocks
    pub fn from_clocks(clocks: HashMap<String, u64>, timestamp_ms: u128) -> Self {
        Self {
            vector_clock: VectorClock::from_clocks(clocks),
            timestamp_ms,
        }
    }

    /// Check if this state version causally precedes another
    pub fn happens_before(&self, other: &StateVersion) -> bool {
        self.vector_clock.happens_before(&other.vector_clock)
    }

    /// Check if two state versions are concurrent
    pub fn is_concurrent(&self, other: &StateVersion) -> bool {
        self.vector_clock.is_concurrent(&other.vector_clock)
    }

    /// Get causal ordering between two state versions
    pub fn causal_cmp(&self, other: &StateVersion) -> Ordering {
        self.vector_clock.causal_cmp(&other.vector_clock)
    }
}

/// Tracks the causal history of an operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CausalHistory {
    /// The vector clock when this operation occurred
    pub state_version: StateVersion,
    /// Instance that originated this operation
    pub instance_id: String,
    /// Sequence number from that instance
    pub sequence: u64,
    /// Any dependencies on other operations (by their vector clocks)
    pub dependencies: Vec<VectorClock>,
}

impl CausalHistory {
    /// Create a new causal history entry
    pub fn new(state_version: StateVersion, instance_id: String, sequence: u64) -> Self {
        Self {
            state_version,
            instance_id,
            sequence,
            dependencies: Vec::new(),
        }
    }

    /// Add a dependency on another operation
    pub fn add_dependency(&mut self, dep_clock: VectorClock) {
        if !self.dependencies.contains(&dep_clock) {
            self.dependencies.push(dep_clock);
        }
    }

    /// Check if this operation depends on another (transitively)
    pub fn depends_on(&self, other: &CausalHistory) -> bool {
        // Direct dependency
        if self
            .dependencies
            .contains(&other.state_version.vector_clock)
        {
            return true;
        }

        // Indirect dependency would require full history traversal
        // For now, check if other happens before self
        other.state_version.happens_before(&self.state_version)
    }
}

/// Conflict resolution strategy for concurrent operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConflictResolutionStrategy {
    /// Last-Write-Wins based on timestamp with instance_id as tiebreaker
    LastWriteWins,
    /// Causally consistent - apply in causal order, keep concurrent
    CausalConsistent,
    /// Application-defined (returned as unresolved for app to handle)
    ApplicationDefined,
}

/// Result of conflict resolution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConflictResolution {
    /// Which operation "won" (Some(index)) or if unresolved (None)
    pub winner_index: Option<usize>,
    /// The resolution strategy used
    pub strategy: ConflictResolutionStrategy,
    /// Whether operations are concurrent
    pub is_concurrent: bool,
    /// Whether operations have causal ordering
    pub is_causal: bool,
}

impl ConflictResolution {
    /// Resolve concurrent operations using Last-Write-Wins strategy
    pub fn resolve_lww(histories: &[CausalHistory]) -> Self {
        if histories.is_empty() {
            return Self {
                winner_index: None,
                strategy: ConflictResolutionStrategy::LastWriteWins,
                is_concurrent: false,
                is_causal: false,
            };
        }

        if histories.len() == 1 {
            return Self {
                winner_index: Some(0),
                strategy: ConflictResolutionStrategy::LastWriteWins,
                is_concurrent: false,
                is_causal: false,
            };
        }

        // Check for causal ordering
        let mut is_causal = false;
        for i in 0..histories.len() {
            for j in 0..histories.len() {
                if i != j
                    && histories[i]
                        .state_version
                        .happens_before(&histories[j].state_version)
                {
                    is_causal = true;
                    break;
                }
            }
            if is_causal {
                break;
            }
        }

        // If there's causal ordering, return the one that happens after all others
        if is_causal {
            let mut winner_idx = 0;
            for i in 1..histories.len() {
                // If winner happens before i, then i is later
                if histories[winner_idx]
                    .state_version
                    .happens_before(&histories[i].state_version)
                {
                    winner_idx = i;
                }
            }
            return Self {
                winner_index: Some(winner_idx),
                strategy: ConflictResolutionStrategy::LastWriteWins,
                is_concurrent: false,
                is_causal: true,
            };
        }

        // Concurrent operations - use LWW with tiebreaker
        let mut winner_idx = 0;
        for i in 1..histories.len() {
            let ts_cmp = histories[i]
                .state_version
                .timestamp_ms
                .cmp(&histories[winner_idx].state_version.timestamp_ms);

            if ts_cmp == std::cmp::Ordering::Greater {
                winner_idx = i;
            } else if ts_cmp == std::cmp::Ordering::Equal {
                // Tiebreaker: lexicographic comparison of instance_id
                if histories[i].instance_id > histories[winner_idx].instance_id {
                    winner_idx = i;
                }
            }
        }

        Self {
            winner_index: Some(winner_idx),
            strategy: ConflictResolutionStrategy::LastWriteWins,
            is_concurrent: true,
            is_causal: false,
        }
    }
}

/// Deterministic merge result for reference graph convergence
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeResult {
    /// Merged vector clock representing the combined state
    pub merged_clock: VectorClock,
    /// Conflicts detected during merge
    pub conflicts: Vec<(usize, usize, ConflictResolution)>,
    /// Whether merge resulted in a new state or kept existing
    pub changed: bool,
}

impl MergeResult {
    /// Create a new merge result
    pub fn new(merged_clock: VectorClock) -> Self {
        Self {
            merged_clock,
            conflicts: Vec::new(),
            changed: false,
        }
    }
}

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

    #[test]
    fn vector_clock_increment() {
        let mut clock = VectorClock::new();
        clock.increment("inst1");
        assert_eq!(clock.get("inst1"), 1);
        assert_eq!(clock.get("inst2"), 0);

        clock.increment("inst1");
        assert_eq!(clock.get("inst1"), 2);
    }

    #[test]
    fn vector_clock_merge() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        clock1.increment("inst1");

        let mut clock2 = VectorClock::new();
        clock2.increment("inst2");
        clock2.increment("inst2");
        clock2.increment("inst2");

        clock1.merge(&clock2);
        assert_eq!(clock1.get("inst1"), 2);
        assert_eq!(clock1.get("inst2"), 3);
    }

    #[test]
    fn vector_clock_happens_before() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");

        let mut clock2 = VectorClock::new();
        clock2.increment("inst1");
        clock2.increment("inst1");

        assert!(clock1.happens_before(&clock2));
        assert!(!clock2.happens_before(&clock1));
    }

    #[test]
    fn vector_clock_concurrent() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");

        let mut clock2 = VectorClock::new();
        clock2.increment("inst2");

        assert!(clock1.is_concurrent(&clock2));
        assert!(clock2.is_concurrent(&clock1));
    }

    #[test]
    fn state_version_causal_ordering() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1, 1000);

        let mut clock2 = VectorClock::new();
        clock2.increment("inst1");
        clock2.increment("inst1");
        let version2 = StateVersion::new(clock2, 2000);

        assert!(version1.happens_before(&version2));
        assert!(version1.causal_cmp(&version2) == Ordering::Less);
    }

    #[test]
    fn conflict_resolution_lww_causal() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1, 1000);
        let history1 = CausalHistory::new(version1, "inst1".to_string(), 1);

        let mut clock2 = VectorClock::new();
        clock2.increment("inst1");
        clock2.increment("inst1");
        let version2 = StateVersion::new(clock2, 2000);
        let history2 = CausalHistory::new(version2, "inst1".to_string(), 2);

        let resolution = ConflictResolution::resolve_lww(&[history1, history2]);
        assert_eq!(resolution.winner_index, Some(1));
        assert!(resolution.is_causal);
        assert!(!resolution.is_concurrent);
    }

    #[test]
    fn conflict_resolution_lww_concurrent() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1, 1000);
        let history1 = CausalHistory::new(version1, "inst1".to_string(), 1);

        let mut clock2 = VectorClock::new();
        clock2.increment("inst2");
        let version2 = StateVersion::new(clock2, 2000);
        let history2 = CausalHistory::new(version2, "inst2".to_string(), 1);

        let resolution = ConflictResolution::resolve_lww(&[history1, history2]);
        assert!(resolution.winner_index.is_some());
        assert!(!resolution.is_causal);
        assert!(resolution.is_concurrent);
    }

    #[test]
    fn causal_history_dependency() {
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1.clone(), 1000);
        let history1 = CausalHistory::new(version1, "inst1".to_string(), 1);

        let mut clock2 = VectorClock::new();
        clock2.clone_from(&clock1);
        clock2.increment("inst2");
        let version2 = StateVersion::new(clock2, 2000);
        let mut history2 = CausalHistory::new(version2, "inst2".to_string(), 1);

        history2.add_dependency(clock1.clone());
        assert!(history2.depends_on(&history1));
    }

    #[test]
    fn vector_clock_lexicographic_tiebreaker() {
        let mut clock1 = VectorClock::new();
        clock1.clocks.insert("inst-a".to_string(), 1);
        clock1.clocks.insert("inst-b".to_string(), 1);

        let clock2 = VectorClock::from_clocks(clock1.clocks.clone());

        // Same clocks - should use lexicographic tiebreaker
        let cmp_result = clock1.causal_cmp(&clock2);
        assert_eq!(cmp_result, Ordering::Equal);
    }

    #[test]
    fn concurrent_mutations_deterministic_resolution() {
        // Scenario: Two instances concurrently modify the same entity
        // Result: Deterministic resolution based on LWW + instance_id tiebreaker

        // Instance A modifies at timestamp 1000
        let mut clock_a = VectorClock::new();
        clock_a.increment("inst-a");
        let version_a = StateVersion::new(clock_a, 1000);
        let history_a = CausalHistory::new(version_a, "inst-a".to_string(), 1);

        // Instance B modifies at timestamp 1000 (same time, but different instance)
        let mut clock_b = VectorClock::new();
        clock_b.increment("inst-b");
        let version_b = StateVersion::new(clock_b, 1000);
        let history_b = CausalHistory::new(version_b, "inst-b".to_string(), 1);

        // Resolve conflict
        let resolution = ConflictResolution::resolve_lww(&[history_a.clone(), history_b.clone()]);
        assert!(resolution.is_concurrent);
        assert!(!resolution.is_causal);
        assert!(resolution.winner_index.is_some());

        // Both resolutions should favor inst-b due to lexicographic ordering
        assert_eq!(
            resolution.winner_index,
            Some(1), // inst-b when b is second
        );
    }

    #[test]
    fn causal_chain_three_operations() {
        // Scenario: Three operations in a causal chain
        // inst1 -> inst2 -> inst3

        // Operation 1: inst1 creates something
        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1.clone(), 1000);
        let history1 = CausalHistory::new(version1, "inst1".to_string(), 1);

        // Operation 2: inst2 observes inst1 and adds to it
        let mut clock2 = clock1.clone();
        clock2.increment("inst2");
        let version2 = StateVersion::new(clock2.clone(), 2000);
        let history2 = CausalHistory::new(version2, "inst2".to_string(), 1);

        // Operation 3: inst3 observes both and adds more
        let mut clock3 = clock2.clone();
        clock3.increment("inst3");
        let version3 = StateVersion::new(clock3, 3000);
        let history3 = CausalHistory::new(version3, "inst3".to_string(), 1);

        // Verify causal chain
        assert!(history1
            .state_version
            .happens_before(&history2.state_version));
        assert!(history2
            .state_version
            .happens_before(&history3.state_version));
        assert!(history1
            .state_version
            .happens_before(&history3.state_version));

        // Resolve in different orders - should always choose the one that happens last
        let resolution1 = ConflictResolution::resolve_lww(&[history1, history2, history3]);
        assert_eq!(resolution1.winner_index, Some(2)); // history3 is latest
        assert!(resolution1.is_causal);
    }

    #[test]
    fn merge_result_construction() {
        let mut merged_clock = VectorClock::new();
        merged_clock.increment("inst1");
        merged_clock.increment("inst2");

        let mut merge_result = MergeResult::new(merged_clock.clone());
        assert!(!merge_result.changed);
        assert_eq!(merge_result.conflicts.len(), 0);

        // Add a conflict
        let history_a = CausalHistory::new(
            StateVersion::new(VectorClock::new(), 1000),
            "inst-a".to_string(),
            1,
        );
        let history_b = CausalHistory::new(
            StateVersion::new(VectorClock::new(), 1000),
            "inst-b".to_string(),
            1,
        );
        let resolution = ConflictResolution::resolve_lww(&[history_a, history_b]);
        merge_result.conflicts.push((0, 1, resolution));

        assert_eq!(merge_result.conflicts.len(), 1);
    }

    #[test]
    fn vector_clock_partial_order() {
        // Test partial ordering properties of vector clocks

        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");

        let mut clock2 = VectorClock::new();
        clock2.increment("inst1");
        clock2.increment("inst2");

        let mut clock3 = VectorClock::new();
        clock3.increment("inst2");
        clock3.increment("inst2");

        // clock1 happens before clock2
        assert!(clock1.happens_before(&clock2));
        assert!(!clock2.happens_before(&clock1));

        // clock1 and clock3 are concurrent
        assert!(clock1.is_concurrent(&clock3));
        assert!(clock3.is_concurrent(&clock1));

        // clock2 and clock3 are concurrent (neither is strictly before the other)
        assert!(clock2.is_concurrent(&clock3));
    }

    #[test]
    fn state_version_ordering() {
        // Test that StateVersion uses vector clock ordering

        let mut clock1 = VectorClock::new();
        clock1.increment("inst1");
        let version1 = StateVersion::new(clock1, 1000);

        let mut clock2 = VectorClock::new();
        clock2.increment("inst1");
        clock2.increment("inst1");
        let version2 = StateVersion::new(clock2, 2000);

        // version1 causally precedes version2
        assert!(version1.happens_before(&version2));

        // version1 is ordered before version2
        assert_eq!(version1.causal_cmp(&version2), Ordering::Less);
        assert_eq!(version2.causal_cmp(&version1), Ordering::Greater);
    }
}