1use std::collections::HashMap;
7
8#[derive(Debug, Clone, PartialEq)]
10pub enum NodeState {
11 Active,
12 Suspected,
13 Unreachable,
14 Partitioned,
15}
16
17#[derive(Debug, Clone)]
19pub struct ClusterView {
20 pub node_id: String,
21 pub known_nodes: HashMap<String, NodeState>,
22 pub last_updated: u64,
23}
24
25impl ClusterView {
26 pub fn new(node_id: impl Into<String>, last_updated: u64) -> Self {
27 ClusterView {
28 node_id: node_id.into(),
29 known_nodes: HashMap::new(),
30 last_updated,
31 }
32 }
33
34 pub fn with_node(mut self, id: impl Into<String>, state: NodeState) -> Self {
35 self.known_nodes.insert(id.into(), state);
36 self
37 }
38}
39
40#[derive(Debug, Clone)]
42pub struct PartitionReport {
43 pub detected_at: u64,
44 pub partition_a: Vec<String>,
45 pub partition_b: Vec<String>,
46 pub confidence: f64,
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub enum SplitBrainAction {
52 NoAction,
54 WaitForHealing,
56 ForcePrimary(String),
58 Shutdown,
60}
61
62pub struct SplitBrainDetector {
64 quorum_size: usize,
65 views: HashMap<String, ClusterView>,
66 partition_timeout_ms: u64,
67}
68
69impl SplitBrainDetector {
70 pub fn new(quorum_size: usize, partition_timeout_ms: u64) -> Self {
75 SplitBrainDetector {
76 quorum_size,
77 views: HashMap::new(),
78 partition_timeout_ms,
79 }
80 }
81
82 pub fn update_view(&mut self, view: ClusterView) {
84 self.views.insert(view.node_id.clone(), view);
85 }
86
87 pub fn active_node_count(&self) -> usize {
89 self.views
90 .values()
91 .filter(|v| {
92 v.known_nodes
93 .get(&v.node_id)
94 .map(|s| *s == NodeState::Active)
95 .unwrap_or(true) })
97 .count()
98 }
99
100 pub fn detect_partitions(&self) -> Vec<PartitionReport> {
103 let mut reports: Vec<PartitionReport> = Vec::new();
104 let node_ids: Vec<String> = self.views.keys().cloned().collect();
105 let total = node_ids.len();
106 if total < 2 {
107 return reports;
108 }
109
110 let can_see = |a: &str, b: &str| -> bool {
112 if let Some(view) = self.views.get(a) {
113 match view.known_nodes.get(b) {
114 Some(NodeState::Active) | Some(NodeState::Suspected) | None => true,
115 Some(NodeState::Unreachable) | Some(NodeState::Partitioned) => false,
116 }
117 } else {
118 false
119 }
120 };
121
122 let mut partition_pairs: Vec<(&str, &str)> = Vec::new();
124 for i in 0..node_ids.len() {
125 for j in (i + 1)..node_ids.len() {
126 let a = &node_ids[i];
127 let b = &node_ids[j];
128 if !can_see(a, b) && !can_see(b, a) {
129 partition_pairs.push((a.as_str(), b.as_str()));
130 }
131 }
132 }
133
134 if partition_pairs.is_empty() {
135 return reports;
136 }
137
138 let groups = find_connected_groups(&node_ids, &self.views, can_see);
141
142 if groups.len() < 2 {
143 return reports;
144 }
145
146 let now = self
147 .views
148 .values()
149 .map(|v| v.last_updated)
150 .max()
151 .unwrap_or(0);
152
153 for i in 0..groups.len() {
155 for j in (i + 1)..groups.len() {
156 let partition_a = groups[i].clone();
157 let partition_b = groups[j].clone();
158 let confidence = compute_confidence(&partition_a, &partition_b, total);
159 reports.push(PartitionReport {
160 detected_at: now,
161 partition_a,
162 partition_b,
163 confidence,
164 });
165 }
166 }
167
168 reports
169 }
170
171 pub fn has_quorum(&self, node_ids: &[String]) -> bool {
173 let active_count = node_ids
174 .iter()
175 .filter(|id| {
176 self.views
177 .get(*id)
178 .map(|v| {
179 v.known_nodes
180 .get(*id)
181 .map(|s| matches!(s, NodeState::Active | NodeState::Suspected))
182 .unwrap_or(true)
183 })
184 .unwrap_or(false)
185 })
186 .count();
187 active_count >= self.quorum_size
188 }
189
190 pub fn recommend_action(&self) -> SplitBrainAction {
192 let partitions = self.detect_partitions();
193 if partitions.is_empty() {
194 return SplitBrainAction::NoAction;
195 }
196
197 let largest = partitions
199 .iter()
200 .map(|p| p.partition_a.len().max(p.partition_b.len()))
201 .max()
202 .unwrap_or(0);
203
204 if largest >= self.quorum_size {
205 let primary_partition = partitions
207 .iter()
208 .max_by_key(|p| p.partition_a.len().max(p.partition_b.len()))
209 .map(|p| {
210 if p.partition_a.len() >= p.partition_b.len() {
211 &p.partition_a
212 } else {
213 &p.partition_b
214 }
215 });
216
217 if let Some(part) = primary_partition {
218 if let Some(primary) = part.iter().min() {
219 return SplitBrainAction::ForcePrimary(primary.clone());
220 }
221 }
222 }
223
224 let total_views = self.views.len();
225 if total_views > 0 && self.active_node_count() * 2 < total_views {
226 return SplitBrainAction::Shutdown;
227 }
228
229 SplitBrainAction::WaitForHealing
230 }
231
232 pub fn is_stale(&self, node_id: &str, now_ms: u64) -> bool {
234 self.views
235 .get(node_id)
236 .map(|v| now_ms.saturating_sub(v.last_updated) > self.partition_timeout_ms)
237 .unwrap_or(false)
238 }
239
240 pub fn remove_view(&mut self, node_id: &str) {
242 self.views.remove(node_id);
243 }
244
245 pub fn known_nodes(&self) -> Vec<String> {
247 let mut nodes: Vec<String> = self.views.keys().cloned().collect();
248 nodes.sort();
249 nodes
250 }
251}
252
253fn find_connected_groups<F>(
258 node_ids: &[String],
259 _views: &HashMap<String, ClusterView>,
260 can_see: F,
261) -> Vec<Vec<String>>
262where
263 F: Fn(&str, &str) -> bool,
264{
265 let n = node_ids.len();
266 let mut component: Vec<usize> = (0..n).collect();
267
268 for i in 0..n {
270 for j in (i + 1)..n {
271 let a = &node_ids[i];
272 let b = &node_ids[j];
273 if can_see(a, b) || can_see(b, a) {
274 let ci = component[i];
276 let cj = component[j];
277 for c in component.iter_mut() {
278 if *c == cj {
279 *c = ci;
280 }
281 }
282 }
283 }
284 }
285
286 let mut groups: HashMap<usize, Vec<String>> = HashMap::new();
288 for (i, &comp) in component.iter().enumerate() {
289 groups.entry(comp).or_default().push(node_ids[i].clone());
290 }
291
292 let mut result: Vec<Vec<String>> = groups.into_values().collect();
293 for group in &mut result {
294 group.sort();
295 }
296 result.sort_by(|a, b| a[0].cmp(&b[0]));
297 result
298}
299
300fn compute_confidence(a: &[String], b: &[String], total: usize) -> f64 {
301 if total == 0 {
302 return 0.0;
303 }
304 let ratio_a = a.len() as f64 / total as f64;
306 let ratio_b = b.len() as f64 / total as f64;
307 (ratio_a + ratio_b).min(1.0)
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 fn make_active_view(node_id: &str, peers: &[&str], ts: u64) -> ClusterView {
315 let mut view = ClusterView::new(node_id, ts);
316 view.known_nodes
317 .insert(node_id.to_string(), NodeState::Active);
318 for &peer in peers {
319 view.known_nodes.insert(peer.to_string(), NodeState::Active);
320 }
321 view
322 }
323
324 fn make_partitioned_view(
325 node_id: &str,
326 visible: &[&str],
327 invisible: &[&str],
328 ts: u64,
329 ) -> ClusterView {
330 let mut view = ClusterView::new(node_id, ts);
331 view.known_nodes
332 .insert(node_id.to_string(), NodeState::Active);
333 for &peer in visible {
334 view.known_nodes.insert(peer.to_string(), NodeState::Active);
335 }
336 for &peer in invisible {
337 view.known_nodes
338 .insert(peer.to_string(), NodeState::Partitioned);
339 }
340 view
341 }
342
343 #[test]
344 fn test_new_detector() {
345 let det = SplitBrainDetector::new(3, 5000);
346 assert_eq!(det.active_node_count(), 0);
347 }
348
349 #[test]
350 fn test_update_view() {
351 let mut det = SplitBrainDetector::new(2, 5000);
352 det.update_view(make_active_view("n1", &["n2"], 1000));
353 assert_eq!(det.known_nodes().len(), 1);
354 }
355
356 #[test]
357 fn test_known_nodes_sorted() {
358 let mut det = SplitBrainDetector::new(2, 5000);
359 det.update_view(make_active_view("n3", &["n1", "n2"], 1000));
360 det.update_view(make_active_view("n1", &["n2", "n3"], 1000));
361 det.update_view(make_active_view("n2", &["n1", "n3"], 1000));
362 let nodes = det.known_nodes();
363 assert_eq!(nodes, vec!["n1", "n2", "n3"]);
364 }
365
366 #[test]
367 fn test_no_partition_healthy_cluster() {
368 let mut det = SplitBrainDetector::new(2, 5000);
369 det.update_view(make_active_view("n1", &["n2", "n3"], 1000));
370 det.update_view(make_active_view("n2", &["n1", "n3"], 1000));
371 det.update_view(make_active_view("n3", &["n1", "n2"], 1000));
372 let parts = det.detect_partitions();
373 assert!(parts.is_empty());
374 }
375
376 #[test]
377 fn test_detect_partition_two_groups() {
378 let mut det = SplitBrainDetector::new(2, 5000);
379 det.update_view(make_partitioned_view("n1", &["n2"], &["n3", "n4"], 1000));
381 det.update_view(make_partitioned_view("n2", &["n1"], &["n3", "n4"], 1000));
382 det.update_view(make_partitioned_view("n3", &["n4"], &["n1", "n2"], 1000));
383 det.update_view(make_partitioned_view("n4", &["n3"], &["n1", "n2"], 1000));
384 let parts = det.detect_partitions();
385 assert!(!parts.is_empty());
386 }
387
388 #[test]
389 fn test_detect_partition_confidence_positive() {
390 let mut det = SplitBrainDetector::new(2, 5000);
391 det.update_view(make_partitioned_view("n1", &[], &["n2"], 1000));
392 det.update_view(make_partitioned_view("n2", &[], &["n1"], 1000));
393 let parts = det.detect_partitions();
394 if !parts.is_empty() {
395 assert!(parts[0].confidence > 0.0);
396 assert!(parts[0].confidence <= 1.0);
397 }
398 }
399
400 #[test]
401 fn test_has_quorum_true() {
402 let mut det = SplitBrainDetector::new(2, 5000);
403 det.update_view(make_active_view("n1", &["n2"], 1000));
404 det.update_view(make_active_view("n2", &["n1"], 1000));
405 let nodes: Vec<String> = vec!["n1".to_string(), "n2".to_string()];
406 assert!(det.has_quorum(&nodes));
407 }
408
409 #[test]
410 fn test_has_quorum_false_insufficient() {
411 let mut det = SplitBrainDetector::new(3, 5000);
412 det.update_view(make_active_view("n1", &[], 1000));
413 let nodes = vec!["n1".to_string()];
414 assert!(!det.has_quorum(&nodes));
415 }
416
417 #[test]
418 fn test_has_quorum_empty_set() {
419 let det = SplitBrainDetector::new(1, 5000);
420 assert!(!det.has_quorum(&[]));
421 }
422
423 #[test]
424 fn test_recommend_no_action_healthy() {
425 let mut det = SplitBrainDetector::new(2, 5000);
426 det.update_view(make_active_view("n1", &["n2"], 1000));
427 det.update_view(make_active_view("n2", &["n1"], 1000));
428 assert_eq!(det.recommend_action(), SplitBrainAction::NoAction);
429 }
430
431 #[test]
432 fn test_recommend_force_primary_on_partition() {
433 let mut det = SplitBrainDetector::new(2, 5000);
434 det.update_view(make_partitioned_view("n1", &["n2"], &["n3", "n4"], 1000));
435 det.update_view(make_partitioned_view("n2", &["n1"], &["n3", "n4"], 1000));
436 det.update_view(make_partitioned_view("n3", &["n4"], &["n1", "n2"], 1000));
437 det.update_view(make_partitioned_view("n4", &["n3"], &["n1", "n2"], 1000));
438 let action = det.recommend_action();
439 assert!(matches!(
441 action,
442 SplitBrainAction::ForcePrimary(_)
443 | SplitBrainAction::WaitForHealing
444 | SplitBrainAction::Shutdown
445 ));
446 }
447
448 #[test]
449 fn test_active_node_count_all_active() {
450 let mut det = SplitBrainDetector::new(2, 5000);
451 det.update_view(make_active_view("n1", &["n2"], 1000));
452 det.update_view(make_active_view("n2", &["n1"], 1000));
453 assert_eq!(det.active_node_count(), 2);
454 }
455
456 #[test]
457 fn test_is_stale_true() {
458 let mut det = SplitBrainDetector::new(2, 1000);
459 det.update_view(make_active_view("n1", &[], 0));
460 assert!(det.is_stale("n1", 2000));
461 }
462
463 #[test]
464 fn test_is_stale_false() {
465 let mut det = SplitBrainDetector::new(2, 5000);
466 det.update_view(make_active_view("n1", &[], 1000));
467 assert!(!det.is_stale("n1", 1500));
468 }
469
470 #[test]
471 fn test_is_stale_unknown_node() {
472 let det = SplitBrainDetector::new(2, 5000);
473 assert!(!det.is_stale("unknown", 9999));
474 }
475
476 #[test]
477 fn test_remove_view() {
478 let mut det = SplitBrainDetector::new(2, 5000);
479 det.update_view(make_active_view("n1", &[], 1000));
480 det.remove_view("n1");
481 assert!(det.known_nodes().is_empty());
482 }
483
484 #[test]
485 fn test_single_node_no_partition() {
486 let mut det = SplitBrainDetector::new(1, 5000);
487 det.update_view(make_active_view("n1", &[], 1000));
488 assert!(det.detect_partitions().is_empty());
489 }
490
491 #[test]
492 fn test_update_view_overwrites() {
493 let mut det = SplitBrainDetector::new(2, 5000);
494 det.update_view(make_active_view("n1", &["n2"], 1000));
495 det.update_view(make_active_view("n1", &["n2", "n3"], 2000));
496 let view = det.views.get("n1").unwrap();
497 assert_eq!(view.last_updated, 2000);
498 }
499
500 #[test]
501 fn test_cluster_view_builder() {
502 let view = ClusterView::new("n1", 500)
503 .with_node("n2", NodeState::Active)
504 .with_node("n3", NodeState::Unreachable);
505 assert_eq!(view.known_nodes.len(), 2);
506 }
507
508 #[test]
509 fn test_node_state_variants() {
510 assert_ne!(NodeState::Active, NodeState::Suspected);
511 assert_ne!(NodeState::Unreachable, NodeState::Partitioned);
512 }
513
514 #[test]
515 fn test_split_brain_action_debug() {
516 let a = SplitBrainAction::ForcePrimary("n1".to_string());
517 let s = format!("{a:?}");
518 assert!(s.contains("ForcePrimary"));
519 }
520
521 #[test]
522 fn test_compute_confidence_zero_total() {
523 assert_eq!(compute_confidence(&[], &[], 0), 0.0);
524 }
525
526 #[test]
527 fn test_compute_confidence_full_coverage() {
528 let a = vec!["n1".to_string(), "n2".to_string()];
529 let b = vec!["n3".to_string(), "n4".to_string()];
530 let conf = compute_confidence(&a, &b, 4);
531 assert!((conf - 1.0).abs() < 0.001);
532 }
533
534 #[test]
535 fn test_partition_report_fields() {
536 let report = PartitionReport {
537 detected_at: 1000,
538 partition_a: vec!["n1".to_string()],
539 partition_b: vec!["n2".to_string()],
540 confidence: 0.8,
541 };
542 assert_eq!(report.detected_at, 1000);
543 assert_eq!(report.confidence, 0.8);
544 }
545
546 #[test]
547 fn test_recommend_no_action_no_views() {
548 let det = SplitBrainDetector::new(3, 5000);
549 assert_eq!(det.recommend_action(), SplitBrainAction::NoAction);
550 }
551
552 #[test]
553 fn test_three_node_partition_asymmetric() {
554 let mut det = SplitBrainDetector::new(2, 5000);
555 det.update_view(make_partitioned_view("n1", &["n2"], &["n3"], 1000));
557 det.update_view(make_partitioned_view("n2", &["n1"], &["n3"], 1000));
558 det.update_view(make_partitioned_view("n3", &[], &["n1", "n2"], 1000));
559 let parts = det.detect_partitions();
560 assert!(!parts.is_empty());
561 }
562}