oxirs-cluster 0.2.4

Raft-backed distributed dataset for high availability and horizontal scaling
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! # Strong Consistency Guarantees
//!
//! Provides linearizable reads and strong consistency guarantees:
//! - Linearizable read protocol (read index)
//! - Read quorum for consistency
//! - Lease-based reads for performance
//! - Follower reads with staleness bounds
//! - Causality tracking
//! - Read-your-writes consistency

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::RwLock;
use tracing::info;

use crate::raft::OxirsNodeId;

/// Consistency level
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ConsistencyLevel {
    /// Eventual consistency (fastest, weakest)
    Eventual,
    /// Session consistency (read-your-writes)
    Session,
    /// Bounded staleness (configurable staleness)
    BoundedStaleness,
    /// Strong consistency (linearizable, slowest)
    Linearizable,
}

/// Read strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReadStrategy {
    /// Leader read (always consistent)
    LeaderRead,
    /// Read index (linearizable with heartbeat)
    ReadIndex,
    /// Lease read (linearizable with lease)
    LeaseRead,
    /// Follower read (may be stale)
    FollowerRead,
}

/// Consistency configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsistencyConfig {
    /// Default consistency level
    pub default_consistency_level: ConsistencyLevel,
    /// Default read strategy
    pub default_read_strategy: ReadStrategy,
    /// Read quorum size
    pub read_quorum_size: usize,
    /// Maximum staleness for bounded staleness (milliseconds)
    pub max_staleness_ms: u64,
    /// Lease duration (milliseconds)
    pub lease_duration_ms: u64,
    /// Enable causality tracking
    pub enable_causality_tracking: bool,
    /// Enable read-your-writes
    pub enable_read_your_writes: bool,
}

impl Default for ConsistencyConfig {
    fn default() -> Self {
        Self {
            default_consistency_level: ConsistencyLevel::Linearizable,
            default_read_strategy: ReadStrategy::ReadIndex,
            read_quorum_size: 2, // Majority of 3
            max_staleness_ms: 100,
            lease_duration_ms: 5000, // 5 seconds
            enable_causality_tracking: true,
            enable_read_your_writes: true,
        }
    }
}

/// Read token for linearizable reads
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadToken {
    /// Token ID
    pub token_id: String,
    /// Read index (commit index when read was initiated)
    pub read_index: u64,
    /// Timestamp
    pub timestamp: SystemTime,
    /// Node ID
    pub node_id: OxirsNodeId,
    /// Consistency level
    pub consistency_level: ConsistencyLevel,
}

/// Lease information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LeaseInfo {
    /// Lease holder (leader node ID)
    pub holder: OxirsNodeId,
    /// Lease start time
    pub start_time: SystemTime,
    /// Lease expiration time
    pub expiration: SystemTime,
    /// Lease term
    pub term: u64,
}

impl LeaseInfo {
    fn is_valid(&self) -> bool {
        SystemTime::now() < self.expiration
    }
}

/// Causality token for session consistency
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CausalityToken {
    /// Session ID
    pub session_id: String,
    /// Last observed commit index
    pub last_commit_index: u64,
    /// Vector clock (node_id -> sequence)
    pub vector_clock: BTreeMap<OxirsNodeId, u64>,
}

/// Read request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadRequest {
    /// Request ID
    pub request_id: String,
    /// Consistency level
    pub consistency_level: ConsistencyLevel,
    /// Read strategy
    pub read_strategy: ReadStrategy,
    /// Causality token (for session consistency)
    pub causality_token: Option<CausalityToken>,
    /// Maximum staleness (for bounded staleness)
    pub max_staleness: Option<Duration>,
}

/// Read response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadResponse {
    /// Request ID
    pub request_id: String,
    /// Success
    pub success: bool,
    /// Read token (for verification)
    pub read_token: Option<ReadToken>,
    /// Actual staleness (milliseconds)
    pub staleness_ms: u64,
    /// Timestamp
    pub timestamp: SystemTime,
}

/// Consistency statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsistencyStats {
    /// Total reads
    pub total_reads: u64,
    /// Linearizable reads
    pub linearizable_reads: u64,
    /// Session reads
    pub session_reads: u64,
    /// Bounded staleness reads
    pub bounded_staleness_reads: u64,
    /// Eventual reads
    pub eventual_reads: u64,
    /// Average read latency (ms)
    pub avg_read_latency_ms: f64,
    /// Read index operations
    pub read_index_ops: u64,
    /// Lease reads
    pub lease_reads: u64,
    /// Follower reads
    pub follower_reads: u64,
    /// Consistency violations detected
    pub consistency_violations: u64,
}

impl Default for ConsistencyStats {
    fn default() -> Self {
        Self {
            total_reads: 0,
            linearizable_reads: 0,
            session_reads: 0,
            bounded_staleness_reads: 0,
            eventual_reads: 0,
            avg_read_latency_ms: 0.0,
            read_index_ops: 0,
            lease_reads: 0,
            follower_reads: 0,
            consistency_violations: 0,
        }
    }
}

/// Strong consistency manager
pub struct StrongConsistencyManager {
    config: ConsistencyConfig,
    /// Current leader
    current_leader: Arc<RwLock<Option<OxirsNodeId>>>,
    /// Current term
    current_term: Arc<RwLock<u64>>,
    /// Commit index
    commit_index: Arc<RwLock<u64>>,
    /// Active leases
    leases: Arc<RwLock<HashMap<OxirsNodeId, LeaseInfo>>>,
    /// Read tokens
    read_tokens: Arc<RwLock<VecDeque<ReadToken>>>,
    /// Session causality tokens
    session_tokens: Arc<RwLock<HashMap<String, CausalityToken>>>,
    /// Statistics
    stats: Arc<RwLock<ConsistencyStats>>,
    /// Local node ID
    local_node_id: OxirsNodeId,
}

impl StrongConsistencyManager {
    /// Create a new strong consistency manager
    pub fn new(local_node_id: OxirsNodeId, config: ConsistencyConfig) -> Self {
        Self {
            config,
            current_leader: Arc::new(RwLock::new(None)),
            current_term: Arc::new(RwLock::new(0)),
            commit_index: Arc::new(RwLock::new(0)),
            leases: Arc::new(RwLock::new(HashMap::new())),
            read_tokens: Arc::new(RwLock::new(VecDeque::new())),
            session_tokens: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(ConsistencyStats::default())),
            local_node_id,
        }
    }

    /// Perform a linearizable read
    pub async fn linearizable_read(&self, request: ReadRequest) -> Result<ReadResponse, String> {
        let start = std::time::Instant::now();

        let response = match request.read_strategy {
            ReadStrategy::LeaderRead => self.leader_read(&request).await?,
            ReadStrategy::ReadIndex => self.read_index(&request).await?,
            ReadStrategy::LeaseRead => self.lease_read(&request).await?,
            ReadStrategy::FollowerRead => self.follower_read(&request).await?,
        };

        // Update statistics
        // Use microseconds for better precision, then convert to milliseconds
        let latency = start.elapsed().as_micros() as f64 / 1000.0;
        let mut stats = self.stats.write().await;
        stats.total_reads += 1;

        // Track consistency level stats
        match request.consistency_level {
            ConsistencyLevel::Linearizable => stats.linearizable_reads += 1,
            ConsistencyLevel::Session => stats.session_reads += 1,
            ConsistencyLevel::BoundedStaleness => stats.bounded_staleness_reads += 1,
            ConsistencyLevel::Eventual => stats.eventual_reads += 1,
        }

        // Track read strategy stats (independent of consistency level)
        match request.read_strategy {
            ReadStrategy::ReadIndex => stats.read_index_ops += 1,
            ReadStrategy::LeaseRead => stats.lease_reads += 1,
            ReadStrategy::FollowerRead => stats.follower_reads += 1,
            _ => {}
        }

        let total = stats.total_reads as f64;
        stats.avg_read_latency_ms = (stats.avg_read_latency_ms * (total - 1.0) + latency) / total;

        Ok(response)
    }

    /// Leader read (always linearizable)
    async fn leader_read(&self, request: &ReadRequest) -> Result<ReadResponse, String> {
        let leader = self.current_leader.read().await;

        if leader.is_none() || *leader != Some(self.local_node_id) {
            return Err("Not the leader".to_string());
        }

        let commit_index = *self.commit_index.read().await;

        let token = ReadToken {
            token_id: request.request_id.clone(),
            read_index: commit_index,
            timestamp: SystemTime::now(),
            node_id: self.local_node_id,
            consistency_level: ConsistencyLevel::Linearizable,
        };

        Ok(ReadResponse {
            request_id: request.request_id.clone(),
            success: true,
            read_token: Some(token),
            staleness_ms: 0,
            timestamp: SystemTime::now(),
        })
    }

    /// Read index protocol (linearizable with heartbeat)
    async fn read_index(&self, request: &ReadRequest) -> Result<ReadResponse, String> {
        let leader = self.current_leader.read().await;

        if leader.is_none() {
            return Err("No leader available".to_string());
        }

        let commit_index = *self.commit_index.read().await;

        // In production: send heartbeat to confirm leadership
        // For now, simulate with a short delay
        tokio::time::sleep(Duration::from_millis(10)).await;

        let token = ReadToken {
            token_id: request.request_id.clone(),
            read_index: commit_index,
            timestamp: SystemTime::now(),
            node_id: self.local_node_id,
            consistency_level: ConsistencyLevel::Linearizable,
        };

        // Store token
        let mut tokens = self.read_tokens.write().await;
        tokens.push_back(token.clone());

        // Keep only recent tokens (last 1000)
        if tokens.len() > 1000 {
            tokens.pop_front();
        }

        Ok(ReadResponse {
            request_id: request.request_id.clone(),
            success: true,
            read_token: Some(token),
            staleness_ms: 0,
            timestamp: SystemTime::now(),
        })
    }

    /// Lease-based read (linearizable with lease)
    async fn lease_read(&self, request: &ReadRequest) -> Result<ReadResponse, String> {
        let leases = self.leases.read().await;
        let leader = self.current_leader.read().await;

        if let Some(leader_id) = *leader {
            if let Some(lease) = leases.get(&leader_id) {
                if lease.is_valid() {
                    let commit_index = *self.commit_index.read().await;

                    let token = ReadToken {
                        token_id: request.request_id.clone(),
                        read_index: commit_index,
                        timestamp: SystemTime::now(),
                        node_id: self.local_node_id,
                        consistency_level: ConsistencyLevel::Linearizable,
                    };

                    return Ok(ReadResponse {
                        request_id: request.request_id.clone(),
                        success: true,
                        read_token: Some(token),
                        staleness_ms: 0,
                        timestamp: SystemTime::now(),
                    });
                }
            }
        }

        // Lease expired or not found, fallback to read index
        self.read_index(request).await
    }

    /// Follower read (may be stale)
    async fn follower_read(&self, request: &ReadRequest) -> Result<ReadResponse, String> {
        let commit_index = *self.commit_index.read().await;

        // Check staleness
        let leader = self.current_leader.read().await;
        let staleness_ms = if leader.is_some() {
            // In production: query leader for latest commit index
            // For now, assume some staleness
            50
        } else {
            self.config.max_staleness_ms
        };

        // Check if within bounds
        if request.consistency_level == ConsistencyLevel::BoundedStaleness {
            if let Some(max_staleness) = request.max_staleness {
                if staleness_ms > max_staleness.as_millis() as u64 {
                    return Err("Staleness exceeds bounds".to_string());
                }
            } else if staleness_ms > self.config.max_staleness_ms {
                return Err("Staleness exceeds configured maximum".to_string());
            }
        }

        let token = ReadToken {
            token_id: request.request_id.clone(),
            read_index: commit_index,
            timestamp: SystemTime::now(),
            node_id: self.local_node_id,
            consistency_level: request.consistency_level,
        };

        Ok(ReadResponse {
            request_id: request.request_id.clone(),
            success: true,
            read_token: Some(token),
            staleness_ms,
            timestamp: SystemTime::now(),
        })
    }

    /// Session read (read-your-writes)
    pub async fn session_read(
        &self,
        session_id: &str,
        request: ReadRequest,
    ) -> Result<ReadResponse, String> {
        if !self.config.enable_read_your_writes {
            return self.linearizable_read(request).await;
        }

        let session_tokens = self.session_tokens.read().await;

        if let Some(causality_token) = session_tokens.get(session_id) {
            let commit_index = *self.commit_index.read().await;

            // Ensure we've replicated at least to the session's last observed index
            if commit_index < causality_token.last_commit_index {
                return Err("Session consistency not yet satisfied".to_string());
            }
        }

        self.linearizable_read(request).await
    }

    /// Update causality token for session
    pub async fn update_session_token(&self, session_id: String, commit_index: u64) {
        if !self.config.enable_causality_tracking {
            return;
        }

        let mut session_tokens = self.session_tokens.write().await;

        let token = session_tokens
            .entry(session_id.clone())
            .or_insert_with(|| CausalityToken {
                session_id: session_id.clone(),
                last_commit_index: 0,
                vector_clock: BTreeMap::new(),
            });

        token.last_commit_index = token.last_commit_index.max(commit_index);
        token.vector_clock.insert(self.local_node_id, commit_index);
    }

    /// Update leader information
    pub async fn update_leader(&self, leader_id: Option<OxirsNodeId>, term: u64) {
        *self.current_leader.write().await = leader_id;
        *self.current_term.write().await = term;

        if let Some(leader) = leader_id {
            info!("Leader updated: node {} (term {})", leader, term);

            // Create/renew lease
            if leader == self.local_node_id {
                let lease = LeaseInfo {
                    holder: leader,
                    start_time: SystemTime::now(),
                    expiration: SystemTime::now()
                        + Duration::from_millis(self.config.lease_duration_ms),
                    term,
                };

                self.leases.write().await.insert(leader, lease);
            }
        }
    }

    /// Update commit index
    pub async fn update_commit_index(&self, index: u64) {
        let mut commit_index = self.commit_index.write().await;
        *commit_index = index;
    }

    /// Get statistics
    pub async fn get_stats(&self) -> ConsistencyStats {
        self.stats.read().await.clone()
    }

    /// Clear all data
    pub async fn clear(&self) {
        *self.current_leader.write().await = None;
        *self.current_term.write().await = 0;
        *self.commit_index.write().await = 0;
        self.leases.write().await.clear();
        self.read_tokens.write().await.clear();
        self.session_tokens.write().await.clear();
        *self.stats.write().await = ConsistencyStats::default();
    }
}

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

    #[tokio::test]
    async fn test_consistency_manager_creation() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        let stats = manager.get_stats().await;
        assert_eq!(stats.total_reads, 0);
    }

    #[tokio::test]
    async fn test_leader_read() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        // Set self as leader
        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(100).await;

        let request = ReadRequest {
            request_id: "test-1".to_string(),
            consistency_level: ConsistencyLevel::Linearizable,
            read_strategy: ReadStrategy::LeaderRead,
            causality_token: None,
            max_staleness: None,
        };

        let response = manager.linearizable_read(request).await;
        assert!(response.is_ok());

        let response = response.unwrap();
        assert!(response.success);
        assert_eq!(response.staleness_ms, 0);
    }

    #[tokio::test]
    async fn test_read_index() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(200).await;

        let request = ReadRequest {
            request_id: "test-2".to_string(),
            consistency_level: ConsistencyLevel::Linearizable,
            read_strategy: ReadStrategy::ReadIndex,
            causality_token: None,
            max_staleness: None,
        };

        let response = manager.linearizable_read(request).await;
        assert!(response.is_ok());

        let stats = manager.get_stats().await;
        assert_eq!(stats.read_index_ops, 1);
    }

    #[tokio::test]
    async fn test_lease_read() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(300).await;

        let request = ReadRequest {
            request_id: "test-3".to_string(),
            consistency_level: ConsistencyLevel::Linearizable,
            read_strategy: ReadStrategy::LeaseRead,
            causality_token: None,
            max_staleness: None,
        };

        let response = manager.linearizable_read(request).await;
        assert!(response.is_ok());

        let stats = manager.get_stats().await;
        assert_eq!(stats.lease_reads, 1);
    }

    #[tokio::test]
    async fn test_follower_read() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(2, config); // Not leader

        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(400).await;

        let request = ReadRequest {
            request_id: "test-4".to_string(),
            consistency_level: ConsistencyLevel::BoundedStaleness,
            read_strategy: ReadStrategy::FollowerRead,
            causality_token: None,
            max_staleness: Some(Duration::from_millis(100)),
        };

        let response = manager.linearizable_read(request).await;
        assert!(response.is_ok());

        let stats = manager.get_stats().await;
        assert_eq!(stats.follower_reads, 1);
    }

    #[tokio::test]
    async fn test_session_read() {
        let config = ConsistencyConfig {
            enable_read_your_writes: true,
            ..Default::default()
        };
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(500).await;

        // Update session token
        manager
            .update_session_token("session-1".to_string(), 450)
            .await;

        let request = ReadRequest {
            request_id: "test-5".to_string(),
            consistency_level: ConsistencyLevel::Session,
            read_strategy: ReadStrategy::LeaderRead,
            causality_token: None,
            max_staleness: None,
        };

        let response = manager.session_read("session-1", request).await;
        assert!(response.is_ok());

        let stats = manager.get_stats().await;
        assert_eq!(stats.session_reads, 1);
    }

    #[tokio::test]
    async fn test_consistency_levels() {
        assert!(ConsistencyLevel::Eventual < ConsistencyLevel::Session);
        assert!(ConsistencyLevel::Session < ConsistencyLevel::BoundedStaleness);
        assert!(ConsistencyLevel::BoundedStaleness < ConsistencyLevel::Linearizable);
    }

    #[tokio::test]
    async fn test_lease_validity() {
        let lease = LeaseInfo {
            holder: 1,
            start_time: SystemTime::now(),
            expiration: SystemTime::now() + Duration::from_secs(5),
            term: 1,
        };

        assert!(lease.is_valid());

        let expired_lease = LeaseInfo {
            holder: 1,
            start_time: SystemTime::now() - Duration::from_secs(10),
            expiration: SystemTime::now() - Duration::from_secs(5),
            term: 1,
        };

        assert!(!expired_lease.is_valid());
    }

    #[tokio::test]
    async fn test_update_leader() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 5).await;

        let leader = manager.current_leader.read().await;
        assert_eq!(*leader, Some(1));

        let term = manager.current_term.read().await;
        assert_eq!(*term, 5);
    }

    #[tokio::test]
    async fn test_update_commit_index() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_commit_index(1000).await;

        let index = manager.commit_index.read().await;
        assert_eq!(*index, 1000);
    }

    #[tokio::test]
    async fn test_statistics() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 1).await;

        // Perform various reads
        for i in 0..5 {
            let request = ReadRequest {
                request_id: format!("test-{}", i),
                consistency_level: ConsistencyLevel::Linearizable,
                read_strategy: ReadStrategy::LeaderRead,
                causality_token: None,
                max_staleness: None,
            };

            let _ = manager.linearizable_read(request).await;
        }

        let stats = manager.get_stats().await;
        assert_eq!(stats.total_reads, 5);
        assert_eq!(stats.linearizable_reads, 5);
        assert!(stats.avg_read_latency_ms > 0.0);
    }

    #[tokio::test]
    async fn test_clear() {
        let config = ConsistencyConfig::default();
        let manager = StrongConsistencyManager::new(1, config);

        manager.update_leader(Some(1), 1).await;
        manager.update_commit_index(100).await;

        manager.clear().await;

        let leader = manager.current_leader.read().await;
        assert!(leader.is_none());

        let index = manager.commit_index.read().await;
        assert_eq!(*index, 0);
    }
}