@feltdb/core 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,769 @@
1
+ //! Authority Failover Protocol
2
+ //!
3
+ //! This module implements automatic authority election, failover, and recovery
4
+ //! for distributed FeltDB clusters. The design follows these principles:
5
+ //!
6
+ //! 1. **Single Authority**: At any time, exactly one node holds authority.
7
+ //! Operations flow through the authority, which coordinates replication.
8
+ //!
9
+ //! 2. **Fencing**: A stale authority cannot accept writes after a new authority
10
+ //! is elected. Fencing tokens prevent split-brain scenarios.
11
+ //!
12
+ //! 3. **Automatic Failover**: When the authority fails, surviving nodes detect
13
+ //! the failure and elect a new authority without application intervention.
14
+ //!
15
+ //! 4. **Recovery**: A previously-failed authority can rejoin as a replica and
16
+ //! catch up to the current state.
17
+ //!
18
+ //! ## Consistency Contract
19
+ //!
20
+ //! - A write is **committed** when the authority has persisted it durably
21
+ //! and at least one other active replica has acknowledged receipt.
22
+ //! - A committed write survives any single node failure.
23
+ //! - During failover, a brief period of unavailability occurs while
24
+ //! the new authority is elected.
25
+ //! - The protocol prevents two nodes from believing they are authority
26
+ //! simultaneously through monotonic fencing tokens.
27
+ //!
28
+ //! ## Failover Sequence
29
+ //!
30
+ //! ```text
31
+ //! Authority A fails
32
+ //! │
33
+ //! ▼
34
+ //! Replicas detect failure (heartbeat timeout)
35
+ //! │
36
+ //! ▼
37
+ //! Election: highest-priority surviving replica
38
+ //! │
39
+ //! ▼
40
+ //! New authority B claims with fencing token
41
+ //! │
42
+ //! ▼
43
+ //! B broadcasts authority change
44
+ //! │
45
+ //! ▼
46
+ //! Replicas acknowledge new authority
47
+ //! │
48
+ //! ▼
49
+ //! B begins accepting writes
50
+ //! │
51
+ //! ▼
52
+ //! Old authority A rejoins as replica
53
+ //! ```
54
+
55
+ use serde::{Deserialize, Serialize};
56
+ use std::collections::{BTreeMap, HashSet};
57
+ use std::path::{Path, PathBuf};
58
+ use std::time::{Duration, SystemTime, UNIX_EPOCH};
59
+
60
+ fn now_ms() -> u64 {
61
+ SystemTime::now()
62
+ .duration_since(UNIX_EPOCH)
63
+ .map(|elapsed| elapsed.as_millis() as u64)
64
+ .unwrap_or(0)
65
+ }
66
+
67
+ /// Authority role of a node in the cluster.
68
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
69
+ #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
70
+ pub enum AuthorityRole {
71
+ /// This node is the authority and accepts writes.
72
+ Authority,
73
+ /// This node is a replica and forwards writes to the authority.
74
+ Replica,
75
+ /// This node is a candidate seeking to become authority.
76
+ Candidate,
77
+ /// This node has been fenced (stale authority).
78
+ Fenced,
79
+ }
80
+
81
+ /// A fencing token that prevents stale authorities from operating.
82
+ ///
83
+ /// Monotonically increasing: a higher token always supersedes a lower one.
84
+ /// The fencing token is durably stored and survives restarts.
85
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
86
+ pub struct FencingToken(pub u64);
87
+
88
+ impl FencingToken {
89
+ pub fn initial() -> Self {
90
+ Self(1)
91
+ }
92
+
93
+ pub fn next(&self) -> Self {
94
+ Self(self.0.saturating_add(1))
95
+ }
96
+
97
+ pub fn supersedes(&self, other: &FencingToken) -> bool {
98
+ self.0 > other.0
99
+ }
100
+ }
101
+
102
+ impl std::fmt::Display for FencingToken {
103
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104
+ write!(f, "FT:{}", self.0)
105
+ }
106
+ }
107
+
108
+ /// Record of an authority election.
109
+ #[derive(Clone, Debug, Serialize, Deserialize)]
110
+ pub struct AuthorityRecord {
111
+ /// The node ID of the authority.
112
+ pub node_id: String,
113
+ /// The fencing token for this authority term.
114
+ pub fencing_token: FencingToken,
115
+ /// When this authority was elected.
116
+ pub elected_at_ms: u64,
117
+ /// The previous authority (if any).
118
+ pub previous_authority: Option<String>,
119
+ /// Nodes that acknowledged this authority.
120
+ pub acknowledgements: HashSet<String>,
121
+ }
122
+
123
+ impl AuthorityRecord {
124
+ pub fn new(node_id: String, fencing_token: FencingToken, previous: Option<String>) -> Self {
125
+ Self {
126
+ node_id,
127
+ fencing_token,
128
+ elected_at_ms: now_ms(),
129
+ previous_authority: previous,
130
+ acknowledgements: HashSet::new(),
131
+ }
132
+ }
133
+ }
134
+
135
+ /// Heartbeat tracking for failure detection.
136
+ #[derive(Clone, Debug, Serialize, Deserialize)]
137
+ pub struct HeartbeatState {
138
+ /// Last heartbeat received from each peer.
139
+ pub last_seen: BTreeMap<String, u64>,
140
+ /// Heartbeat interval in milliseconds.
141
+ pub interval_ms: u64,
142
+ /// How many missed heartbeats before a node is considered failed.
143
+ pub failure_threshold: u32,
144
+ }
145
+
146
+ impl HeartbeatState {
147
+ pub fn new(interval_ms: u64, failure_threshold: u32) -> Self {
148
+ Self {
149
+ last_seen: BTreeMap::new(),
150
+ interval_ms,
151
+ failure_threshold,
152
+ }
153
+ }
154
+
155
+ /// Record a heartbeat from a peer.
156
+ pub fn record_heartbeat(&mut self, node_id: &str) {
157
+ self.last_seen.insert(node_id.to_string(), now_ms());
158
+ }
159
+
160
+ /// Check if a node appears to have failed.
161
+ pub fn is_failed(&self, node_id: &str) -> bool {
162
+ let Some(last) = self.last_seen.get(node_id) else {
163
+ // Never seen = not yet known, not necessarily failed
164
+ return false;
165
+ };
166
+ let deadline = self.interval_ms * self.failure_threshold as u64;
167
+ now_ms().saturating_sub(*last) > deadline
168
+ }
169
+
170
+ /// Get all nodes that appear to have failed.
171
+ pub fn failed_nodes(&self) -> Vec<String> {
172
+ self.last_seen
173
+ .keys()
174
+ .filter(|node_id| self.is_failed(node_id))
175
+ .cloned()
176
+ .collect()
177
+ }
178
+ }
179
+
180
+ /// Election priority for a node.
181
+ /// Higher priority wins the election when multiple candidates exist.
182
+ #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
183
+ pub struct ElectionPriority {
184
+ /// Operations applied (higher is better - more up-to-date).
185
+ pub operations_applied: u64,
186
+ /// Static priority assigned to the node (for tie-breaking).
187
+ pub static_priority: u32,
188
+ /// Node ID (for deterministic tie-breaking).
189
+ pub node_id: String,
190
+ }
191
+
192
+ impl ElectionPriority {
193
+ pub fn new(operations_applied: u64, static_priority: u32, node_id: String) -> Self {
194
+ Self {
195
+ operations_applied,
196
+ static_priority,
197
+ node_id,
198
+ }
199
+ }
200
+ }
201
+
202
+ /// The result of an authority claim attempt.
203
+ #[derive(Clone, Debug)]
204
+ pub enum ClaimResult {
205
+ /// Successfully claimed authority with this fencing token.
206
+ Granted { token: FencingToken },
207
+ /// Another node already has a higher fencing token.
208
+ Rejected {
209
+ current_authority: String,
210
+ current_token: FencingToken,
211
+ },
212
+ /// This node is fenced and cannot claim authority.
213
+ Fenced { token: FencingToken },
214
+ }
215
+
216
+ /// Authority state that is durably persisted.
217
+ #[derive(Clone, Debug, Serialize, Deserialize)]
218
+ pub struct AuthorityState {
219
+ /// The cluster ID this authority state belongs to.
220
+ pub cluster_id: String,
221
+ /// Current authority record, if any.
222
+ pub current_authority: Option<AuthorityRecord>,
223
+ /// This node's role.
224
+ pub local_role: AuthorityRole,
225
+ /// This node's ID.
226
+ pub local_node_id: String,
227
+ /// The highest fencing token this node has seen.
228
+ pub highest_seen_token: FencingToken,
229
+ /// Election priority for this node.
230
+ pub local_priority: u32,
231
+ }
232
+
233
+ impl AuthorityState {
234
+ pub fn new(cluster_id: String, local_node_id: String, local_priority: u32) -> Self {
235
+ Self {
236
+ cluster_id,
237
+ current_authority: None,
238
+ local_role: AuthorityRole::Replica,
239
+ local_node_id,
240
+ highest_seen_token: FencingToken::initial(),
241
+ local_priority,
242
+ }
243
+ }
244
+
245
+ /// Check if this node is currently the authority.
246
+ pub fn is_authority(&self) -> bool {
247
+ self.local_role == AuthorityRole::Authority
248
+ }
249
+
250
+ /// Check if this node is fenced.
251
+ pub fn is_fenced(&self) -> bool {
252
+ self.local_role == AuthorityRole::Fenced
253
+ }
254
+
255
+ /// Get the current authority node ID.
256
+ pub fn authority_node(&self) -> Option<&str> {
257
+ self.current_authority.as_ref().map(|r| r.node_id.as_str())
258
+ }
259
+
260
+ /// Get the current fencing token.
261
+ pub fn current_token(&self) -> FencingToken {
262
+ self.current_authority
263
+ .as_ref()
264
+ .map(|r| r.fencing_token)
265
+ .unwrap_or(FencingToken::initial())
266
+ }
267
+ }
268
+
269
+ /// Persistent authority store.
270
+ pub struct AuthorityStore {
271
+ path: PathBuf,
272
+ state: AuthorityState,
273
+ heartbeats: HeartbeatState,
274
+ }
275
+
276
+ #[derive(Debug)]
277
+ pub enum AuthorityError {
278
+ NoCluster,
279
+ AlreadyAuthority(String),
280
+ NotAuthority,
281
+ Fenced(FencingToken),
282
+ StaleToken {
283
+ provided: FencingToken,
284
+ current: FencingToken,
285
+ },
286
+ Io(String),
287
+ }
288
+
289
+ impl std::fmt::Display for AuthorityError {
290
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291
+ match self {
292
+ Self::NoCluster => write!(f, "no cluster has been created"),
293
+ Self::AlreadyAuthority(id) => write!(f, "node {id} is already authority"),
294
+ Self::NotAuthority => write!(f, "this node is not the authority"),
295
+ Self::Fenced(token) => write!(f, "this node is fenced at {token}"),
296
+ Self::StaleToken { provided, current } => {
297
+ write!(f, "stale token {provided}, current is {current}")
298
+ }
299
+ Self::Io(msg) => write!(f, "authority store: {msg}"),
300
+ }
301
+ }
302
+ }
303
+
304
+ impl AuthorityStore {
305
+ /// Open or create an authority store.
306
+ pub fn open<P: AsRef<Path>>(
307
+ path: P,
308
+ cluster_id: &str,
309
+ local_node_id: &str,
310
+ local_priority: u32,
311
+ ) -> Result<Self, AuthorityError> {
312
+ let path = path.as_ref().to_path_buf();
313
+ let state = if path.exists() {
314
+ let bytes = std::fs::read(&path).map_err(|e| AuthorityError::Io(e.to_string()))?;
315
+ serde_json::from_slice(&bytes).map_err(|e| AuthorityError::Io(e.to_string()))?
316
+ } else {
317
+ AuthorityState::new(
318
+ cluster_id.to_string(),
319
+ local_node_id.to_string(),
320
+ local_priority,
321
+ )
322
+ };
323
+ Ok(Self {
324
+ path,
325
+ state,
326
+ heartbeats: HeartbeatState::new(1000, 5), // 1s heartbeat, 5 missed = failure
327
+ })
328
+ }
329
+
330
+ /// Persist the authority state durably.
331
+ fn persist(&self) -> Result<(), AuthorityError> {
332
+ if let Some(parent) = self.path.parent() {
333
+ std::fs::create_dir_all(parent).map_err(|e| AuthorityError::Io(e.to_string()))?;
334
+ }
335
+ let temp = self.path.with_extension("tmp");
336
+ let bytes =
337
+ serde_json::to_vec_pretty(&self.state).map_err(|e| AuthorityError::Io(e.to_string()))?;
338
+ {
339
+ use std::io::Write;
340
+ let mut file =
341
+ std::fs::File::create(&temp).map_err(|e| AuthorityError::Io(e.to_string()))?;
342
+ file.write_all(&bytes)
343
+ .map_err(|e| AuthorityError::Io(e.to_string()))?;
344
+ file.sync_all()
345
+ .map_err(|e| AuthorityError::Io(e.to_string()))?;
346
+ }
347
+ std::fs::rename(&temp, &self.path).map_err(|e| AuthorityError::Io(e.to_string()))?;
348
+ if let Some(parent) = self.path.parent() {
349
+ if let Ok(dir) = std::fs::File::open(parent) {
350
+ let _ = dir.sync_all();
351
+ }
352
+ }
353
+ Ok(())
354
+ }
355
+
356
+ /// Get the current authority state.
357
+ pub fn state(&self) -> &AuthorityState {
358
+ &self.state
359
+ }
360
+
361
+ /// Record a heartbeat from a peer.
362
+ pub fn heartbeat(&mut self, node_id: &str) {
363
+ self.heartbeats.record_heartbeat(node_id);
364
+ }
365
+
366
+ /// Check if the current authority has failed.
367
+ pub fn authority_failed(&self) -> bool {
368
+ if let Some(ref authority) = self.state.current_authority {
369
+ if authority.node_id == self.state.local_node_id {
370
+ return false; // We are authority, we haven't failed
371
+ }
372
+ return self.heartbeats.is_failed(&authority.node_id);
373
+ }
374
+ false
375
+ }
376
+
377
+ /// Get all nodes that appear to have failed.
378
+ pub fn failed_nodes(&self) -> Vec<String> {
379
+ self.heartbeats.failed_nodes()
380
+ }
381
+
382
+ /// Claim authority with a new fencing token.
383
+ ///
384
+ /// This node attempts to become the authority. If successful:
385
+ /// - A new fencing token is assigned (one higher than any seen)
386
+ /// - This node becomes authority
387
+ /// - The previous authority (if any) is recorded
388
+ ///
389
+ /// If another node has a higher token, the claim is rejected.
390
+ pub fn claim_authority(&mut self) -> Result<ClaimResult, AuthorityError> {
391
+ if self.state.is_fenced() {
392
+ return Ok(ClaimResult::Fenced {
393
+ token: self.state.highest_seen_token,
394
+ });
395
+ }
396
+
397
+ // If there's already an authority with a higher token, reject
398
+ if let Some(ref current) = self.state.current_authority {
399
+ if current.node_id != self.state.local_node_id
400
+ && !self.heartbeats.is_failed(&current.node_id)
401
+ {
402
+ return Ok(ClaimResult::Rejected {
403
+ current_authority: current.node_id.clone(),
404
+ current_token: current.fencing_token,
405
+ });
406
+ }
407
+ }
408
+
409
+ // Claim with a new token
410
+ let new_token = self.state.highest_seen_token.next();
411
+ let previous = self
412
+ .state
413
+ .current_authority
414
+ .as_ref()
415
+ .map(|r| r.node_id.clone());
416
+
417
+ let mut record =
418
+ AuthorityRecord::new(self.state.local_node_id.clone(), new_token, previous);
419
+ record.acknowledgements.insert(self.state.local_node_id.clone());
420
+
421
+ self.state.current_authority = Some(record);
422
+ self.state.local_role = AuthorityRole::Authority;
423
+ self.state.highest_seen_token = new_token;
424
+
425
+ self.persist()?;
426
+
427
+ Ok(ClaimResult::Granted { token: new_token })
428
+ }
429
+
430
+ /// Accept a new authority announcement.
431
+ ///
432
+ /// If the fencing token is higher than any we've seen, accept the new
433
+ /// authority and update our role accordingly.
434
+ pub fn accept_authority(
435
+ &mut self,
436
+ authority_node: &str,
437
+ token: FencingToken,
438
+ ) -> Result<(), AuthorityError> {
439
+ // Check if token is valid
440
+ if !token.supersedes(&self.state.highest_seen_token)
441
+ && token != self.state.highest_seen_token
442
+ {
443
+ return Err(AuthorityError::StaleToken {
444
+ provided: token,
445
+ current: self.state.highest_seen_token,
446
+ });
447
+ }
448
+
449
+ // Update our state
450
+ self.state.highest_seen_token = token;
451
+
452
+ // If we were authority with a lower token, we are now fenced
453
+ if self.state.local_role == AuthorityRole::Authority
454
+ && authority_node != self.state.local_node_id
455
+ {
456
+ self.state.local_role = AuthorityRole::Fenced;
457
+ } else if authority_node != self.state.local_node_id {
458
+ self.state.local_role = AuthorityRole::Replica;
459
+ }
460
+
461
+ // Record the new authority
462
+ self.state.current_authority = Some(AuthorityRecord::new(
463
+ authority_node.to_string(),
464
+ token,
465
+ self.state
466
+ .current_authority
467
+ .as_ref()
468
+ .map(|r| r.node_id.clone()),
469
+ ));
470
+
471
+ // Start tracking heartbeats from the new authority.
472
+ // This allows failure detection to work even if we've never received
473
+ // a heartbeat yet - the clock starts now.
474
+ if authority_node != self.state.local_node_id {
475
+ self.heartbeats.record_heartbeat(authority_node);
476
+ }
477
+
478
+ self.persist()
479
+ }
480
+
481
+ /// Acknowledge the current authority.
482
+ pub fn acknowledge_authority(&mut self, from_node: &str) -> Result<(), AuthorityError> {
483
+ if let Some(ref mut authority) = self.state.current_authority {
484
+ authority.acknowledgements.insert(from_node.to_string());
485
+ self.persist()?;
486
+ }
487
+ Ok(())
488
+ }
489
+
490
+ /// Validate a write operation against the current fencing token.
491
+ ///
492
+ /// Returns Ok if the token is valid (current or not provided for local writes).
493
+ /// Returns Err if the token is stale.
494
+ pub fn validate_write(&self, token: Option<FencingToken>) -> Result<(), AuthorityError> {
495
+ if self.state.is_fenced() {
496
+ return Err(AuthorityError::Fenced(self.state.highest_seen_token));
497
+ }
498
+
499
+ if !self.state.is_authority() {
500
+ return Err(AuthorityError::NotAuthority);
501
+ }
502
+
503
+ if let Some(provided) = token {
504
+ if provided != self.state.current_token() {
505
+ return Err(AuthorityError::StaleToken {
506
+ provided,
507
+ current: self.state.current_token(),
508
+ });
509
+ }
510
+ }
511
+
512
+ Ok(())
513
+ }
514
+
515
+ /// Step down from authority role (voluntary).
516
+ pub fn step_down(&mut self) -> Result<(), AuthorityError> {
517
+ if self.state.local_role == AuthorityRole::Authority {
518
+ self.state.local_role = AuthorityRole::Replica;
519
+ self.persist()?;
520
+ }
521
+ Ok(())
522
+ }
523
+
524
+ /// Recover from fenced state (after catching up).
525
+ pub fn recover_from_fenced(&mut self) -> Result<(), AuthorityError> {
526
+ if self.state.local_role == AuthorityRole::Fenced {
527
+ self.state.local_role = AuthorityRole::Replica;
528
+ self.persist()?;
529
+ }
530
+ Ok(())
531
+ }
532
+
533
+ /// Compute election priority for this node.
534
+ pub fn election_priority(&self, operations_applied: u64) -> ElectionPriority {
535
+ ElectionPriority::new(
536
+ operations_applied,
537
+ self.state.local_priority,
538
+ self.state.local_node_id.clone(),
539
+ )
540
+ }
541
+
542
+ /// Determine the winner of an election given a set of candidates.
543
+ pub fn elect_authority(candidates: &[ElectionPriority]) -> Option<&ElectionPriority> {
544
+ candidates.iter().max()
545
+ }
546
+ }
547
+
548
+ /// Authority announcement message.
549
+ #[derive(Clone, Debug, Serialize, Deserialize)]
550
+ pub struct AuthorityAnnouncement {
551
+ pub authority_node: String,
552
+ pub fencing_token: FencingToken,
553
+ pub elected_at_ms: u64,
554
+ pub cluster_id: String,
555
+ }
556
+
557
+ /// Heartbeat message.
558
+ #[derive(Clone, Debug, Serialize, Deserialize)]
559
+ pub struct Heartbeat {
560
+ pub from_node: String,
561
+ pub is_authority: bool,
562
+ pub fencing_token: FencingToken,
563
+ pub operations_applied: u64,
564
+ pub timestamp_ms: u64,
565
+ }
566
+
567
+ impl Heartbeat {
568
+ pub fn new(
569
+ from_node: String,
570
+ is_authority: bool,
571
+ fencing_token: FencingToken,
572
+ operations_applied: u64,
573
+ ) -> Self {
574
+ Self {
575
+ from_node,
576
+ is_authority,
577
+ fencing_token,
578
+ operations_applied,
579
+ timestamp_ms: now_ms(),
580
+ }
581
+ }
582
+ }
583
+
584
+ /// Election request message.
585
+ #[derive(Clone, Debug, Serialize, Deserialize)]
586
+ pub struct ElectionRequest {
587
+ pub candidate_node: String,
588
+ pub priority: ElectionPriority,
589
+ pub proposed_token: FencingToken,
590
+ pub timestamp_ms: u64,
591
+ }
592
+
593
+ /// Election response message.
594
+ #[derive(Clone, Debug, Serialize, Deserialize)]
595
+ pub struct ElectionResponse {
596
+ pub from_node: String,
597
+ pub vote_granted: bool,
598
+ pub reason: String,
599
+ }
600
+
601
+ #[cfg(test)]
602
+ mod tests {
603
+ use super::*;
604
+
605
+ #[test]
606
+ fn fencing_token_ordering() {
607
+ let t1 = FencingToken::initial();
608
+ let t2 = t1.next();
609
+ let t3 = t2.next();
610
+
611
+ assert!(t2.supersedes(&t1));
612
+ assert!(t3.supersedes(&t2));
613
+ assert!(t3.supersedes(&t1));
614
+ assert!(!t1.supersedes(&t2));
615
+ }
616
+
617
+ #[test]
618
+ fn authority_claim_and_fencing() {
619
+ let dir = tempfile::tempdir().unwrap();
620
+ let path = dir.path().join("authority.json");
621
+
622
+ // Node A claims authority
623
+ let mut store_a =
624
+ AuthorityStore::open(&path, "test-cluster", "A", 10).expect("open store A");
625
+ let result = store_a.claim_authority().expect("claim");
626
+ match result {
627
+ ClaimResult::Granted { token } => {
628
+ assert_eq!(token, FencingToken(2)); // initial is 1, next is 2
629
+ }
630
+ _ => panic!("expected Granted"),
631
+ }
632
+ assert!(store_a.state().is_authority());
633
+
634
+ // Node B sees A's authority
635
+ let path_b = dir.path().join("authority_b.json");
636
+ let mut store_b =
637
+ AuthorityStore::open(&path_b, "test-cluster", "B", 5).expect("open store B");
638
+ store_b
639
+ .accept_authority("A", FencingToken(2))
640
+ .expect("accept");
641
+ assert!(!store_b.state().is_authority());
642
+ assert_eq!(store_b.state().authority_node(), Some("A"));
643
+
644
+ // Node B tries to claim - should be rejected since A is still up
645
+ let result_b = store_b.claim_authority().expect("claim B");
646
+ match result_b {
647
+ ClaimResult::Rejected {
648
+ current_authority,
649
+ current_token,
650
+ } => {
651
+ assert_eq!(current_authority, "A");
652
+ assert_eq!(current_token, FencingToken(2));
653
+ }
654
+ _ => panic!("expected Rejected"),
655
+ }
656
+ }
657
+
658
+ #[test]
659
+ fn failover_when_authority_dies() {
660
+ let dir = tempfile::tempdir().unwrap();
661
+
662
+ // Node A is authority
663
+ let path_a = dir.path().join("authority_a.json");
664
+ let mut store_a =
665
+ AuthorityStore::open(&path_a, "test-cluster", "A", 10).expect("open store A");
666
+ store_a.claim_authority().expect("claim A");
667
+
668
+ // Node B knows about A
669
+ let path_b = dir.path().join("authority_b.json");
670
+ let mut store_b =
671
+ AuthorityStore::open(&path_b, "test-cluster", "B", 5).expect("open store B");
672
+ store_b
673
+ .accept_authority("A", FencingToken(2))
674
+ .expect("accept A");
675
+
676
+ // Simulate A dying - mark heartbeat as very old
677
+ store_b.heartbeats.last_seen.insert("A".to_string(), 0);
678
+
679
+ // Now B should be able to claim
680
+ assert!(store_b.authority_failed());
681
+ let result_b = store_b.claim_authority().expect("claim B after failover");
682
+ match result_b {
683
+ ClaimResult::Granted { token } => {
684
+ assert_eq!(token, FencingToken(3)); // higher than A's token
685
+ }
686
+ _ => panic!("expected Granted after failover"),
687
+ }
688
+ }
689
+
690
+ #[test]
691
+ fn stale_authority_is_fenced() {
692
+ let dir = tempfile::tempdir().unwrap();
693
+
694
+ // A is authority with token 2
695
+ let path_a = dir.path().join("authority_a.json");
696
+ let mut store_a =
697
+ AuthorityStore::open(&path_a, "test-cluster", "A", 10).expect("open store A");
698
+ store_a.claim_authority().expect("claim A");
699
+ assert!(store_a.state().is_authority());
700
+
701
+ // A receives announcement that B is now authority with token 3
702
+ store_a
703
+ .accept_authority("B", FencingToken(3))
704
+ .expect("accept B");
705
+
706
+ // A should now be fenced
707
+ assert!(store_a.state().is_fenced());
708
+ assert!(!store_a.state().is_authority());
709
+
710
+ // A's writes should be rejected
711
+ let result = store_a.validate_write(None);
712
+ assert!(matches!(result, Err(AuthorityError::Fenced(_))));
713
+ }
714
+
715
+ #[test]
716
+ fn election_priority_ordering() {
717
+ let p1 = ElectionPriority::new(100, 5, "A".to_string());
718
+ let p2 = ElectionPriority::new(100, 10, "B".to_string());
719
+ let p3 = ElectionPriority::new(150, 5, "C".to_string());
720
+
721
+ // Higher operations wins
722
+ assert!(p3 > p1);
723
+ assert!(p3 > p2);
724
+
725
+ // Same operations, higher priority wins
726
+ assert!(p2 > p1);
727
+
728
+ // Election selects highest priority
729
+ let candidates = vec![p1.clone(), p2.clone(), p3.clone()];
730
+ let winner = AuthorityStore::elect_authority(&candidates);
731
+ assert_eq!(winner.map(|w| &w.node_id), Some(&"C".to_string()));
732
+ }
733
+
734
+ #[test]
735
+ fn heartbeat_failure_detection() {
736
+ let mut heartbeats = HeartbeatState::new(1000, 3); // 1s interval, 3 missed = failure
737
+
738
+ // Record a heartbeat
739
+ heartbeats.record_heartbeat("A");
740
+ assert!(!heartbeats.is_failed("A"));
741
+
742
+ // Manually set an old timestamp
743
+ heartbeats.last_seen.insert("A".to_string(), 0);
744
+
745
+ // Should now be detected as failed (current time is way past 3 intervals)
746
+ assert!(heartbeats.is_failed("A"));
747
+ }
748
+
749
+ #[test]
750
+ fn recovery_from_fenced() {
751
+ let dir = tempfile::tempdir().unwrap();
752
+ let path = dir.path().join("authority.json");
753
+
754
+ let mut store =
755
+ AuthorityStore::open(&path, "test-cluster", "A", 10).expect("open store");
756
+ store.claim_authority().expect("claim");
757
+
758
+ // Get fenced
759
+ store
760
+ .accept_authority("B", FencingToken(3))
761
+ .expect("accept B");
762
+ assert!(store.state().is_fenced());
763
+
764
+ // Recover
765
+ store.recover_from_fenced().expect("recover");
766
+ assert!(!store.state().is_fenced());
767
+ assert_eq!(store.state().local_role, AuthorityRole::Replica);
768
+ }
769
+ }