Skip to main content

oxirs_rule/
distributed.rs

1//! Distributed Reasoning Foundations
2//!
3//! Provides infrastructure for distributed rule-based reasoning across multiple nodes.
4//! Enables horizontal scaling of reasoning workloads.
5//!
6//! # Features
7//!
8//! - **Node Management**: Register and manage reasoning nodes
9//! - **Work Distribution**: Partition facts and rules across nodes
10//! - **Result Aggregation**: Collect and merge results from distributed execution
11//! - **Fault Tolerance**: Handle node failures gracefully
12//! - **Load Balancing**: Distribute work based on node capacity
13//!
14//! # Example
15//!
16//! ```rust
17//! use oxirs_rule::distributed::{DistributedReasoner, Node, PartitionStrategy};
18//! use oxirs_rule::RuleEngine;
19//!
20//! let reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
21//!
22//! // Register nodes
23//! // reasoner.register_node(Node::new("node1", "localhost:8001"))?;
24//! // reasoner.register_node(Node::new("node2", "localhost:8002"))?;
25//!
26//! // Execute distributed reasoning
27//! // let results = reasoner.execute_distributed(&rules, &facts)?;
28//! # Ok::<(), anyhow::Error>(())
29//! ```
30
31use crate::{Rule, RuleAtom, RuleEngine};
32use anyhow::Result;
33use std::collections::HashMap;
34use tracing::{debug, info, warn};
35
36/// Reasoning node in the distributed system
37#[derive(Debug, Clone)]
38pub struct Node {
39    /// Node identifier
40    pub id: String,
41    /// Node address (host:port)
42    pub address: String,
43    /// Node status
44    pub status: NodeStatus,
45    /// Node capacity (facts per second)
46    pub capacity: usize,
47    /// Current load (0.0 - 1.0)
48    pub load: f64,
49    /// Node role in Raft consensus
50    pub role: NodeRole,
51    /// Current term
52    pub term: u64,
53    /// Last heartbeat received
54    pub last_heartbeat: Option<std::time::SystemTime>,
55    /// Voted for (in current term)
56    pub voted_for: Option<String>,
57}
58
59impl Node {
60    /// Create a new node
61    pub fn new(id: String, address: String) -> Self {
62        Self {
63            id,
64            address,
65            status: NodeStatus::Available,
66            capacity: 1000,
67            load: 0.0,
68            role: NodeRole::Follower,
69            term: 0,
70            last_heartbeat: None,
71            voted_for: None,
72        }
73    }
74
75    /// Set node capacity
76    pub fn with_capacity(mut self, capacity: usize) -> Self {
77        self.capacity = capacity;
78        self
79    }
80
81    /// Check if node is available
82    pub fn is_available(&self) -> bool {
83        matches!(self.status, NodeStatus::Available) && self.load < 0.9
84    }
85
86    /// Update node load
87    pub fn update_load(&mut self, load: f64) {
88        self.load = load.clamp(0.0, 1.0);
89
90        // Update status based on load
91        if self.load > 0.95 {
92            self.status = NodeStatus::Overloaded;
93        } else if self.status == NodeStatus::Overloaded && self.load < 0.8 {
94            self.status = NodeStatus::Available;
95        }
96    }
97
98    /// Promote node to leader
99    pub fn promote_to_leader(&mut self, term: u64) {
100        self.role = NodeRole::Leader;
101        self.term = term;
102        self.voted_for = Some(self.id.clone());
103        info!("Node '{}' promoted to leader (term {})", self.id, term);
104    }
105
106    /// Demote node to follower
107    pub fn demote_to_follower(&mut self) {
108        self.role = NodeRole::Follower;
109        debug!(
110            "Node '{}' demoted to follower (term {})",
111            self.id, self.term
112        );
113    }
114
115    /// Start election
116    pub fn start_election(&mut self) {
117        self.role = NodeRole::Candidate;
118        self.term += 1;
119        self.voted_for = Some(self.id.clone());
120        info!("Node '{}' starting election (term {})", self.id, self.term);
121    }
122
123    /// Receive heartbeat from leader
124    pub fn receive_heartbeat(&mut self, heartbeat: &Heartbeat) {
125        if heartbeat.term >= self.term {
126            self.last_heartbeat = Some(heartbeat.timestamp);
127            self.term = heartbeat.term;
128            if self.role != NodeRole::Follower {
129                self.demote_to_follower();
130            }
131        }
132    }
133
134    /// Check if heartbeat has timed out
135    pub fn heartbeat_timeout(&self, timeout_ms: u64) -> bool {
136        if let Some(last) = self.last_heartbeat {
137            if let Ok(elapsed) = std::time::SystemTime::now().duration_since(last) {
138                return elapsed.as_millis() > timeout_ms as u128;
139            }
140        }
141        true // No heartbeat received yet
142    }
143}
144
145/// Node status
146#[derive(Debug, Clone, PartialEq)]
147pub enum NodeStatus {
148    /// Node is available for work
149    Available,
150    /// Node is processing work
151    Busy,
152    /// Node is overloaded
153    Overloaded,
154    /// Node is offline or failed
155    Offline,
156}
157
158/// Node role in Raft consensus
159#[derive(Debug, Clone, PartialEq)]
160pub enum NodeRole {
161    /// Leader node (coordinates reasoning)
162    Leader,
163    /// Follower node (executes work)
164    Follower,
165    /// Candidate node (election in progress)
166    Candidate,
167}
168
169/// Heartbeat message from leader to followers
170#[derive(Debug, Clone)]
171pub struct Heartbeat {
172    /// Leader node ID
173    pub leader_id: String,
174    /// Current term
175    pub term: u64,
176    /// Timestamp
177    pub timestamp: std::time::SystemTime,
178}
179
180/// Partitioning strategy for distributing work
181#[derive(Debug, Clone, PartialEq)]
182pub enum PartitionStrategy {
183    /// Round-robin distribution
184    RoundRobin,
185    /// Hash-based partitioning
186    HashBased,
187    /// Load-balanced distribution
188    LoadBalanced,
189    /// Random distribution
190    Random,
191}
192
193/// Work partition for a node
194#[derive(Debug, Clone)]
195pub struct WorkPartition {
196    /// Node ID this partition is assigned to
197    pub node_id: String,
198    /// Rules to execute
199    pub rules: Vec<Rule>,
200    /// Facts to process
201    pub facts: Vec<RuleAtom>,
202    /// Partition ID
203    pub partition_id: usize,
204}
205
206impl WorkPartition {
207    /// Create a new work partition
208    pub fn new(node_id: String, partition_id: usize) -> Self {
209        Self {
210            node_id,
211            rules: Vec::new(),
212            facts: Vec::new(),
213            partition_id,
214        }
215    }
216
217    /// Add rules to partition
218    pub fn add_rules(&mut self, rules: Vec<Rule>) {
219        self.rules.extend(rules);
220    }
221
222    /// Add facts to partition
223    pub fn add_facts(&mut self, facts: Vec<RuleAtom>) {
224        self.facts.extend(facts);
225    }
226
227    /// Get estimated work size
228    pub fn work_size(&self) -> usize {
229        self.facts.len() * self.rules.len()
230    }
231}
232
233/// Result from a distributed reasoning task
234#[derive(Debug, Clone)]
235pub struct DistributedResult {
236    /// Node that produced this result
237    pub node_id: String,
238    /// Derived facts
239    pub facts: Vec<RuleAtom>,
240    /// Execution time in milliseconds
241    pub execution_time_ms: u128,
242    /// Whether execution succeeded
243    pub success: bool,
244}
245
246impl DistributedResult {
247    /// Create a new result
248    pub fn new(node_id: String) -> Self {
249        Self {
250            node_id,
251            facts: Vec::new(),
252            execution_time_ms: 0,
253            success: true,
254        }
255    }
256}
257
258/// Distributed reasoner coordinator with Raft consensus
259pub struct DistributedReasoner {
260    /// Registered nodes
261    nodes: HashMap<String, Node>,
262    /// Partitioning strategy
263    strategy: PartitionStrategy,
264    /// Statistics
265    stats: DistributedStats,
266    /// Cached rules (optimization to avoid cloning rules repeatedly)
267    cached_rules: Option<Vec<Rule>>,
268    /// Min facts per partition (to avoid over-partitioning)
269    min_facts_per_partition: usize,
270    /// Current leader node ID
271    leader_id: Option<String>,
272    /// Current term
273    current_term: u64,
274    /// Heartbeat timeout (milliseconds)
275    #[allow(dead_code)]
276    heartbeat_timeout_ms: u64,
277    /// Election timeout (milliseconds)
278    #[allow(dead_code)]
279    election_timeout_ms: u64,
280    /// Last heartbeat sent timestamp
281    last_heartbeat_sent: Option<std::time::SystemTime>,
282}
283
284impl DistributedReasoner {
285    /// Create a new distributed reasoner with Raft consensus
286    pub fn new(strategy: PartitionStrategy) -> Self {
287        Self {
288            nodes: HashMap::new(),
289            strategy,
290            stats: DistributedStats::default(),
291            cached_rules: None,
292            // For simulated local execution, require large datasets to justify overhead
293            // Real distributed systems would use lower thresholds (e.g., 50)
294            min_facts_per_partition: 500,
295            leader_id: None,
296            current_term: 0,
297            heartbeat_timeout_ms: 150,
298            election_timeout_ms: 300,
299            last_heartbeat_sent: None,
300        }
301    }
302
303    /// Set minimum facts per partition (to prevent over-partitioning)
304    pub fn set_min_facts_per_partition(&mut self, min: usize) {
305        self.min_facts_per_partition = min;
306    }
307
308    /// Register a node
309    pub fn register_node(&mut self, node: Node) -> Result<()> {
310        let id = node.id.clone();
311        if self.nodes.contains_key(&id) {
312            return Err(anyhow::anyhow!("Node '{}' already registered", id));
313        }
314
315        info!("Registering node '{}' at {}", id, node.address);
316        self.nodes.insert(id, node);
317        Ok(())
318    }
319
320    /// Unregister a node
321    pub fn unregister_node(&mut self, node_id: &str) -> Option<Node> {
322        info!("Unregistering node '{}'", node_id);
323        self.nodes.remove(node_id)
324    }
325
326    /// Get available nodes
327    pub fn get_available_nodes(&self) -> Vec<&Node> {
328        self.nodes.values().filter(|n| n.is_available()).collect()
329    }
330
331    /// Partition work across available nodes
332    pub fn partition_work(
333        &mut self,
334        rules: &[Rule],
335        facts: &[RuleAtom],
336    ) -> Result<Vec<WorkPartition>> {
337        let available_nodes = self.get_available_nodes();
338
339        if available_nodes.is_empty() {
340            return Err(anyhow::anyhow!(
341                "No available nodes for distributed reasoning"
342            ));
343        }
344
345        debug!(
346            "Partitioning work across {} nodes using {:?} strategy",
347            available_nodes.len(),
348            self.strategy
349        );
350
351        match self.strategy {
352            PartitionStrategy::RoundRobin => self.partition_round_robin(rules, facts),
353            PartitionStrategy::HashBased => self.partition_hash_based(rules, facts),
354            PartitionStrategy::LoadBalanced => self.partition_load_balanced(rules, facts),
355            PartitionStrategy::Random => self.partition_random(rules, facts),
356        }
357    }
358
359    /// Round-robin partitioning
360    fn partition_round_robin(
361        &mut self,
362        rules: &[Rule],
363        facts: &[RuleAtom],
364    ) -> Result<Vec<WorkPartition>> {
365        let available_nodes = self.get_available_nodes();
366        let node_count = available_nodes.len();
367
368        let facts_per_node = (facts.len() + node_count - 1) / node_count;
369        let mut partitions = Vec::new();
370
371        for (i, node) in available_nodes.iter().enumerate() {
372            let start = i * facts_per_node;
373            let end = ((i + 1) * facts_per_node).min(facts.len());
374
375            let mut partition = WorkPartition::new(node.id.clone(), i);
376            partition.add_rules(rules.to_vec());
377            partition.add_facts(facts[start..end].to_vec());
378
379            partitions.push(partition);
380        }
381
382        Ok(partitions)
383    }
384
385    /// Hash-based partitioning
386    fn partition_hash_based(
387        &self,
388        rules: &[Rule],
389        facts: &[RuleAtom],
390    ) -> Result<Vec<WorkPartition>> {
391        let available_nodes = self.get_available_nodes();
392        let node_count = available_nodes.len();
393
394        let mut partitions: Vec<WorkPartition> = available_nodes
395            .iter()
396            .enumerate()
397            .map(|(i, node)| WorkPartition::new(node.id.clone(), i))
398            .collect();
399
400        // Hash each fact to a partition
401        for fact in facts {
402            let hash = self.hash_atom(fact);
403            let partition_idx = hash % node_count;
404            partitions[partition_idx].add_facts(vec![fact.clone()]);
405        }
406
407        // Add all rules to all partitions
408        for partition in &mut partitions {
409            partition.add_rules(rules.to_vec());
410        }
411
412        Ok(partitions)
413    }
414
415    /// Load-balanced partitioning
416    fn partition_load_balanced(
417        &self,
418        rules: &[Rule],
419        facts: &[RuleAtom],
420    ) -> Result<Vec<WorkPartition>> {
421        let available_nodes = self.get_available_nodes();
422        let _node_count = available_nodes.len();
423
424        // Calculate capacity-based weights
425        let total_capacity: usize = available_nodes.iter().map(|n| n.capacity).sum();
426
427        let mut partitions = Vec::new();
428        let mut fact_idx = 0;
429
430        for (i, node) in available_nodes.iter().enumerate() {
431            let weight = node.capacity as f64 / total_capacity as f64;
432            let facts_for_node = ((facts.len() as f64) * weight).ceil() as usize;
433
434            let end = (fact_idx + facts_for_node).min(facts.len());
435
436            let mut partition = WorkPartition::new(node.id.clone(), i);
437            partition.add_rules(rules.to_vec());
438            partition.add_facts(facts[fact_idx..end].to_vec());
439
440            partitions.push(partition);
441            fact_idx = end;
442
443            if fact_idx >= facts.len() {
444                break;
445            }
446        }
447
448        Ok(partitions)
449    }
450
451    /// Random partitioning
452    fn partition_random(
453        &mut self,
454        rules: &[Rule],
455        facts: &[RuleAtom],
456    ) -> Result<Vec<WorkPartition>> {
457        // For simplicity, use round-robin as fallback
458        // In a full implementation, we would use random assignment
459        self.partition_round_robin(rules, facts)
460    }
461
462    /// Simple hash function for atoms
463    fn hash_atom(&self, atom: &RuleAtom) -> usize {
464        match atom {
465            RuleAtom::Triple {
466                subject,
467                predicate,
468                object,
469            } => {
470                let mut hash = 0;
471                hash ^= self.hash_term(subject);
472                hash ^= self.hash_term(predicate);
473                hash ^= self.hash_term(object);
474                hash
475            }
476            _ => 0,
477        }
478    }
479
480    fn hash_term(&self, term: &crate::Term) -> usize {
481        match term {
482            crate::Term::Constant(s) | crate::Term::Literal(s) | crate::Term::Variable(s) => s
483                .bytes()
484                .fold(0, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize)),
485            _ => 0,
486        }
487    }
488
489    /// Execute distributed reasoning (optimized)
490    pub fn execute_distributed(
491        &mut self,
492        rules: &[Rule],
493        facts: &[RuleAtom],
494    ) -> Result<Vec<RuleAtom>> {
495        self.stats.total_executions += 1;
496        let start = std::time::Instant::now();
497
498        // Check if distributed execution is worthwhile
499        // Calculate how many partitions we would actually create
500        let ideal_partitions = (facts.len() / self.min_facts_per_partition)
501            .max(1)
502            .min(self.nodes.len());
503
504        if ideal_partitions <= 1 || self.nodes.is_empty() {
505            // Not enough work to justify distribution overhead - use single engine
506            debug!(
507                "Workload too small for distribution ({} facts -> {} partitions) - using single engine",
508                facts.len(),
509                ideal_partitions
510            );
511            return self.execute_single_engine(rules, facts);
512        }
513
514        // Cache rules once (optimization to avoid repeated cloning)
515        self.cached_rules = Some(rules.to_vec());
516
517        // Partition work with smart sizing
518        let partitions = self.partition_work_smart(rules, facts)?;
519        self.stats.partitions_created += partitions.len();
520
521        // Execute partitions with cached rules
522        let results = self.execute_partitions_optimized(partitions)?;
523
524        // Aggregate results
525        let aggregated = self.aggregate_results(results)?;
526
527        self.stats.total_time_ms += start.elapsed().as_millis();
528        info!(
529            "Distributed execution complete: {} facts derived across {} partitions",
530            aggregated.len(),
531            self.stats.partitions_created
532        );
533
534        Ok(aggregated)
535    }
536
537    /// Execute on single engine (fallback for small workloads)
538    fn execute_single_engine(&self, rules: &[Rule], facts: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
539        let mut engine = RuleEngine::new();
540        for rule in rules {
541            engine.add_rule(rule.clone());
542        }
543        engine.forward_chain(facts)
544    }
545
546    /// Smart partitioning that avoids over-partitioning
547    fn partition_work_smart(
548        &mut self,
549        rules: &[Rule],
550        facts: &[RuleAtom],
551    ) -> Result<Vec<WorkPartition>> {
552        // Calculate optimal number of partitions
553        let ideal_partitions = (facts.len() / self.min_facts_per_partition).min(self.nodes.len());
554        let effective_nodes = ideal_partitions.max(1);
555
556        debug!(
557            "Smart partitioning: {} facts across {} nodes (min {} facts/partition)",
558            facts.len(),
559            effective_nodes,
560            self.min_facts_per_partition
561        );
562
563        // Use round-robin but with effective node count
564        let available_nodes: Vec<_> = self
565            .get_available_nodes()
566            .into_iter()
567            .take(effective_nodes)
568            .collect();
569        let node_count = available_nodes.len();
570
571        if node_count == 0 {
572            return Err(anyhow::anyhow!("No available nodes"));
573        }
574
575        let facts_per_node = (facts.len() + node_count - 1) / node_count;
576        let mut partitions = Vec::new();
577
578        for (i, node) in available_nodes.iter().enumerate() {
579            let start = i * facts_per_node;
580            let end = ((i + 1) * facts_per_node).min(facts.len());
581
582            if start >= facts.len() {
583                break;
584            }
585
586            let mut partition = WorkPartition::new(node.id.clone(), i);
587            partition.add_rules(rules.to_vec());
588            partition.add_facts(facts[start..end].to_vec());
589
590            debug!(
591                "Partition {} -> node '{}': {} facts",
592                i,
593                node.id,
594                end - start
595            );
596
597            partitions.push(partition);
598        }
599
600        Ok(partitions)
601    }
602
603    /// Execute partitions with optimized rule handling
604    fn execute_partitions_optimized(
605        &mut self,
606        partitions: Vec<WorkPartition>,
607    ) -> Result<Vec<DistributedResult>> {
608        let mut results = Vec::new();
609
610        // Get cached rules once
611        let rules = self
612            .cached_rules
613            .as_ref()
614            .ok_or_else(|| anyhow::anyhow!("Rules not cached"))?;
615
616        for partition in partitions {
617            debug!(
618                "Executing partition {} on node '{}' ({} facts)",
619                partition.partition_id,
620                partition.node_id,
621                partition.facts.len()
622            );
623
624            let start = std::time::Instant::now();
625
626            // Create engine and add cached rules efficiently
627            let mut engine = RuleEngine::new();
628            for rule in rules {
629                engine.add_rule(rule.clone());
630            }
631
632            let derived = engine.forward_chain(&partition.facts)?;
633
634            let mut result = DistributedResult::new(partition.node_id.clone());
635            result.facts = derived;
636            result.execution_time_ms = start.elapsed().as_millis();
637            result.success = true;
638
639            // Update node load (simulated)
640            if let Some(node) = self.nodes.get_mut(&partition.node_id) {
641                let load = partition.work_size() as f64 / node.capacity as f64;
642                node.update_load(load);
643            }
644
645            results.push(result);
646            self.stats.successful_executions += 1;
647        }
648
649        Ok(results)
650    }
651
652    /// Aggregate results from distributed execution
653    fn aggregate_results(&mut self, results: Vec<DistributedResult>) -> Result<Vec<RuleAtom>> {
654        let mut all_facts = Vec::new();
655
656        for result in results {
657            if result.success {
658                all_facts.extend(result.facts);
659                debug!(
660                    "Aggregating {} facts from node '{}' ({}ms)",
661                    all_facts.len(),
662                    result.node_id,
663                    result.execution_time_ms
664                );
665            } else {
666                warn!("Node '{}' execution failed", result.node_id);
667                self.stats.failed_executions += 1;
668            }
669        }
670
671        // Deduplicate facts
672        all_facts.sort_by(|a, b| format!("{:?}", a).cmp(&format!("{:?}", b)));
673        all_facts.dedup_by(|a, b| format!("{:?}", a) == format!("{:?}", b));
674
675        Ok(all_facts)
676    }
677
678    /// Get statistics
679    pub fn get_stats(&self) -> &DistributedStats {
680        &self.stats
681    }
682
683    /// Reset statistics
684    pub fn reset_stats(&mut self) {
685        self.stats = DistributedStats::default();
686    }
687
688    /// Get node count
689    pub fn node_count(&self) -> usize {
690        self.nodes.len()
691    }
692
693    /// Elect leader using simplified Raft algorithm
694    pub fn elect_leader(&mut self) -> Result<String> {
695        if self.nodes.is_empty() {
696            return Err(anyhow::anyhow!("No nodes available for election"));
697        }
698
699        // Increment term
700        self.current_term += 1;
701
702        // Simple leader election: choose node with highest capacity
703        let leader = self
704            .nodes
705            .values_mut()
706            .filter(|n| matches!(n.status, NodeStatus::Available | NodeStatus::Busy))
707            .max_by_key(|n| n.capacity)
708            .ok_or_else(|| anyhow::anyhow!("No available nodes for election"))?;
709
710        let leader_id = leader.id.clone();
711        leader.promote_to_leader(self.current_term);
712
713        // Set all other nodes as followers
714        for node in self.nodes.values_mut() {
715            if node.id != leader_id {
716                node.demote_to_follower();
717                node.term = self.current_term;
718            }
719        }
720
721        self.leader_id = Some(leader_id.clone());
722        info!(
723            "Leader elected: '{}' (term {}, capacity {})",
724            leader_id,
725            self.current_term,
726            self.nodes.get(&leader_id).map(|n| n.capacity).unwrap_or(0)
727        );
728
729        Ok(leader_id)
730    }
731
732    /// Send heartbeat from leader to all followers
733    pub fn send_heartbeat(&mut self) -> Result<()> {
734        let leader_id = self
735            .leader_id
736            .clone()
737            .ok_or_else(|| anyhow::anyhow!("No leader elected"))?;
738
739        let heartbeat = Heartbeat {
740            leader_id: leader_id.clone(),
741            term: self.current_term,
742            timestamp: std::time::SystemTime::now(),
743        };
744
745        self.last_heartbeat_sent = Some(heartbeat.timestamp);
746
747        // Send to all followers
748        let mut heartbeat_count = 0;
749        for node in self.nodes.values_mut() {
750            if node.id != leader_id {
751                node.receive_heartbeat(&heartbeat);
752                heartbeat_count += 1;
753            }
754        }
755
756        debug!(
757            "Leader '{}' sent heartbeat to {} followers (term {})",
758            leader_id, heartbeat_count, self.current_term
759        );
760
761        Ok(())
762    }
763
764    /// Check for heartbeat timeout and trigger election if needed
765    pub fn check_heartbeat_timeout(&mut self) -> Result<bool> {
766        if self.leader_id.is_none() {
767            // No leader, trigger election
768            info!("No leader present, triggering election");
769            self.elect_leader()?;
770            return Ok(true);
771        }
772
773        // Check if leader is still alive
774        if let Some(leader_id) = &self.leader_id {
775            if let Some(leader) = self.nodes.get(leader_id) {
776                if matches!(leader.status, NodeStatus::Offline) {
777                    warn!("Leader '{}' is offline, triggering election", leader_id);
778                    self.leader_id = None;
779                    self.elect_leader()?;
780                    return Ok(true);
781                }
782            }
783        }
784
785        Ok(false)
786    }
787
788    /// Get current leader
789    pub fn get_leader(&self) -> Option<&Node> {
790        self.leader_id.as_ref().and_then(|id| self.nodes.get(id))
791    }
792
793    /// Execute distributed reasoning with Raft consensus
794    pub fn execute_distributed_with_consensus(
795        &mut self,
796        rules: &[Rule],
797        facts: &[RuleAtom],
798    ) -> Result<Vec<RuleAtom>> {
799        // Ensure we have a leader
800        if self.leader_id.is_none() {
801            info!("No leader present, electing leader");
802            self.elect_leader()?;
803        }
804
805        // Send heartbeat to maintain leadership
806        self.send_heartbeat()?;
807
808        // Execute distributed reasoning (existing logic)
809        self.execute_distributed(rules, facts)
810    }
811
812    /// Handle node failure
813    pub fn handle_node_failure(&mut self, node_id: &str) -> Result<()> {
814        if let Some(node) = self.nodes.get_mut(node_id) {
815            warn!("Marking node '{}' as offline", node_id);
816            node.status = NodeStatus::Offline;
817
818            // If failed node was leader, trigger election
819            if self.leader_id.as_ref() == Some(&node_id.to_string()) {
820                warn!("Leader '{}' failed, triggering election", node_id);
821                self.leader_id = None;
822                self.elect_leader()?;
823            }
824        }
825
826        Ok(())
827    }
828
829    /// Recover node from failure
830    pub fn recover_node(&mut self, node_id: &str) -> Result<()> {
831        if let Some(node) = self.nodes.get_mut(node_id) {
832            info!("Recovering node '{}' from failure", node_id);
833            node.status = NodeStatus::Available;
834            node.load = 0.0;
835            node.demote_to_follower();
836
837            // Send heartbeat to sync state
838            self.send_heartbeat()?;
839        }
840
841        Ok(())
842    }
843
844    /// Get cluster health status
845    pub fn get_cluster_health(&self) -> ClusterHealth {
846        let total_nodes = self.nodes.len();
847        let available_nodes = self
848            .nodes
849            .values()
850            .filter(|n| matches!(n.status, NodeStatus::Available))
851            .count();
852        let offline_nodes = self
853            .nodes
854            .values()
855            .filter(|n| matches!(n.status, NodeStatus::Offline))
856            .count();
857
858        let health_ratio = if total_nodes > 0 {
859            available_nodes as f64 / total_nodes as f64
860        } else {
861            0.0
862        };
863
864        let status = if health_ratio >= 0.8 {
865            ClusterHealthStatus::Healthy
866        } else if health_ratio >= 0.5 {
867            ClusterHealthStatus::Degraded
868        } else {
869            ClusterHealthStatus::Critical
870        };
871
872        ClusterHealth {
873            status,
874            total_nodes,
875            available_nodes,
876            offline_nodes,
877            leader_id: self.leader_id.clone(),
878            current_term: self.current_term,
879        }
880    }
881}
882
883/// Cluster health status
884#[derive(Debug, Clone, PartialEq)]
885pub enum ClusterHealthStatus {
886    /// Cluster is healthy (>=80% nodes available)
887    Healthy,
888    /// Cluster is degraded (50-80% nodes available)
889    Degraded,
890    /// Cluster is critical (<50% nodes available)
891    Critical,
892}
893
894/// Cluster health information
895#[derive(Debug, Clone)]
896pub struct ClusterHealth {
897    /// Health status
898    pub status: ClusterHealthStatus,
899    /// Total nodes
900    pub total_nodes: usize,
901    /// Available nodes
902    pub available_nodes: usize,
903    /// Offline nodes
904    pub offline_nodes: usize,
905    /// Current leader
906    pub leader_id: Option<String>,
907    /// Current term
908    pub current_term: u64,
909}
910
911/// Distributed reasoning statistics
912#[derive(Debug, Clone, Default)]
913pub struct DistributedStats {
914    /// Total distributed executions
915    pub total_executions: usize,
916    /// Successful executions
917    pub successful_executions: usize,
918    /// Failed executions
919    pub failed_executions: usize,
920    /// Total partitions created
921    pub partitions_created: usize,
922    /// Total execution time in milliseconds
923    pub total_time_ms: u128,
924}
925
926impl std::fmt::Display for DistributedStats {
927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928        write!(
929            f,
930            "Executions: {} (success: {}, failed: {}), Partitions: {}, Time: {}ms",
931            self.total_executions,
932            self.successful_executions,
933            self.failed_executions,
934            self.partitions_created,
935            self.total_time_ms
936        )
937    }
938}
939
940#[cfg(test)]
941mod tests {
942    use super::*;
943    use crate::Term;
944
945    #[test]
946    fn test_node_creation() {
947        let node = Node::new("node1".to_string(), "localhost:8001".to_string());
948
949        assert_eq!(node.id, "node1");
950        assert_eq!(node.address, "localhost:8001");
951        assert!(node.is_available());
952    }
953
954    #[test]
955    fn test_node_load_update() {
956        let mut node = Node::new("node1".to_string(), "localhost:8001".to_string());
957
958        node.update_load(0.5);
959        assert_eq!(node.load, 0.5);
960        assert_eq!(node.status, NodeStatus::Available);
961
962        node.update_load(0.96);
963        assert_eq!(node.status, NodeStatus::Overloaded);
964    }
965
966    #[test]
967    fn test_work_partition_creation() {
968        let mut partition = WorkPartition::new("node1".to_string(), 0);
969
970        partition.add_facts(vec![RuleAtom::Triple {
971            subject: Term::Constant("a".to_string()),
972            predicate: Term::Constant("p".to_string()),
973            object: Term::Constant("b".to_string()),
974        }]);
975
976        assert_eq!(partition.facts.len(), 1);
977        assert_eq!(partition.work_size(), 0); // 1 fact * 0 rules
978    }
979
980    #[test]
981    fn test_distributed_reasoner_creation() {
982        let reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
983
984        assert_eq!(reasoner.node_count(), 0);
985    }
986
987    #[test]
988    fn test_node_registration() -> Result<(), Box<dyn std::error::Error>> {
989        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
990
991        let node = Node::new("node1".to_string(), "localhost:8001".to_string());
992        reasoner.register_node(node)?;
993
994        assert_eq!(reasoner.node_count(), 1);
995        Ok(())
996    }
997
998    #[test]
999    fn test_node_unregistration() -> Result<(), Box<dyn std::error::Error>> {
1000        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1001
1002        let node = Node::new("node1".to_string(), "localhost:8001".to_string());
1003        reasoner.register_node(node)?;
1004
1005        let removed = reasoner.unregister_node("node1");
1006        assert!(removed.is_some());
1007        assert_eq!(reasoner.node_count(), 0);
1008        Ok(())
1009    }
1010
1011    #[test]
1012    fn test_work_partitioning() -> Result<(), Box<dyn std::error::Error>> {
1013        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1014
1015        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1016        reasoner.register_node(Node::new("node2".to_string(), "localhost:8002".to_string()))?;
1017
1018        let rules = vec![];
1019        let facts = vec![
1020            RuleAtom::Triple {
1021                subject: Term::Constant("a".to_string()),
1022                predicate: Term::Constant("p".to_string()),
1023                object: Term::Constant("b".to_string()),
1024            },
1025            RuleAtom::Triple {
1026                subject: Term::Constant("c".to_string()),
1027                predicate: Term::Constant("q".to_string()),
1028                object: Term::Constant("d".to_string()),
1029            },
1030        ];
1031
1032        let partitions = reasoner.partition_work(&rules, &facts)?;
1033
1034        assert_eq!(partitions.len(), 2);
1035        Ok(())
1036    }
1037
1038    #[test]
1039    fn test_distributed_execution() -> Result<(), Box<dyn std::error::Error>> {
1040        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1041
1042        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1043
1044        let rule = Rule {
1045            name: "test_rule".to_string(),
1046            body: vec![],
1047            head: vec![],
1048        };
1049
1050        let facts = vec![RuleAtom::Triple {
1051            subject: Term::Constant("a".to_string()),
1052            predicate: Term::Constant("p".to_string()),
1053            object: Term::Constant("b".to_string()),
1054        }];
1055
1056        let results = reasoner.execute_distributed(&[rule], &facts)?;
1057
1058        assert!(!results.is_empty());
1059        Ok(())
1060    }
1061
1062    #[test]
1063    fn test_leader_election() -> Result<(), Box<dyn std::error::Error>> {
1064        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1065
1066        reasoner.register_node(
1067            Node::new("node1".to_string(), "localhost:8001".to_string()).with_capacity(100),
1068        )?;
1069        reasoner.register_node(
1070            Node::new("node2".to_string(), "localhost:8002".to_string()).with_capacity(200),
1071        )?;
1072        reasoner.register_node(
1073            Node::new("node3".to_string(), "localhost:8003".to_string()).with_capacity(150),
1074        )?;
1075
1076        let leader_id = reasoner.elect_leader()?;
1077
1078        // Node with highest capacity should be elected
1079        assert_eq!(leader_id, "node2");
1080        assert_eq!(reasoner.current_term, 1);
1081
1082        // Check leader role
1083        let leader = reasoner.get_leader().ok_or("expected Some value")?;
1084        assert_eq!(leader.role, NodeRole::Leader);
1085        Ok(())
1086    }
1087
1088    #[test]
1089    fn test_heartbeat() -> Result<(), Box<dyn std::error::Error>> {
1090        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1091
1092        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1093        reasoner.register_node(Node::new("node2".to_string(), "localhost:8002".to_string()))?;
1094
1095        reasoner.elect_leader()?;
1096        reasoner.send_heartbeat()?;
1097
1098        // Check that followers received heartbeat
1099        for node in reasoner.nodes.values() {
1100            if node.role == NodeRole::Follower {
1101                assert!(node.last_heartbeat.is_some());
1102            }
1103        }
1104        Ok(())
1105    }
1106
1107    #[test]
1108    fn test_node_failure_handling() -> Result<(), Box<dyn std::error::Error>> {
1109        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1110
1111        reasoner.register_node(
1112            Node::new("node1".to_string(), "localhost:8001".to_string()).with_capacity(100),
1113        )?;
1114        reasoner.register_node(
1115            Node::new("node2".to_string(), "localhost:8002".to_string()).with_capacity(200),
1116        )?;
1117
1118        let leader_id = reasoner.elect_leader()?;
1119
1120        // Simulate leader failure
1121        reasoner.handle_node_failure(&leader_id)?;
1122
1123        // New leader should be elected
1124        assert!(reasoner.leader_id.is_some());
1125        assert_ne!(
1126            reasoner.leader_id.as_ref().ok_or("expected Some value")?,
1127            &leader_id
1128        );
1129        Ok(())
1130    }
1131
1132    #[test]
1133    fn test_node_recovery() -> Result<(), Box<dyn std::error::Error>> {
1134        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1135
1136        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1137        reasoner.register_node(Node::new("node2".to_string(), "localhost:8002".to_string()))?;
1138
1139        reasoner.elect_leader()?;
1140
1141        // Simulate node1 failure
1142        reasoner.handle_node_failure("node1")?;
1143
1144        assert_eq!(
1145            reasoner
1146                .nodes
1147                .get("node1")
1148                .ok_or("expected Some value")?
1149                .status,
1150            NodeStatus::Offline
1151        );
1152
1153        // Recover node1
1154        reasoner.recover_node("node1")?;
1155
1156        assert_eq!(
1157            reasoner
1158                .nodes
1159                .get("node1")
1160                .ok_or("expected Some value")?
1161                .status,
1162            NodeStatus::Available
1163        );
1164        assert_eq!(
1165            reasoner
1166                .nodes
1167                .get("node1")
1168                .ok_or("expected Some value")?
1169                .role,
1170            NodeRole::Follower
1171        );
1172        Ok(())
1173    }
1174
1175    #[test]
1176    fn test_cluster_health() -> Result<(), Box<dyn std::error::Error>> {
1177        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1178
1179        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1180        reasoner.register_node(Node::new("node2".to_string(), "localhost:8002".to_string()))?;
1181        reasoner.register_node(Node::new("node3".to_string(), "localhost:8003".to_string()))?;
1182
1183        reasoner.elect_leader()?;
1184
1185        let health = reasoner.get_cluster_health();
1186
1187        assert_eq!(health.status, ClusterHealthStatus::Healthy);
1188        assert_eq!(health.total_nodes, 3);
1189        assert_eq!(health.available_nodes, 3);
1190        assert_eq!(health.offline_nodes, 0);
1191        assert!(health.leader_id.is_some());
1192
1193        // Simulate node failure
1194        reasoner.handle_node_failure("node1")?;
1195
1196        let health_degraded = reasoner.get_cluster_health();
1197
1198        // 2/3 = 66.7% available (Degraded, because <80%)
1199        assert_eq!(health_degraded.status, ClusterHealthStatus::Degraded);
1200        assert_eq!(health_degraded.available_nodes, 2);
1201        assert_eq!(health_degraded.offline_nodes, 1);
1202        Ok(())
1203    }
1204
1205    #[test]
1206    fn test_distributed_execution_with_consensus() -> Result<(), Box<dyn std::error::Error>> {
1207        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1208
1209        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1210        reasoner.register_node(Node::new("node2".to_string(), "localhost:8002".to_string()))?;
1211
1212        let rule = Rule {
1213            name: "test_rule".to_string(),
1214            body: vec![],
1215            head: vec![],
1216        };
1217
1218        let facts = vec![RuleAtom::Triple {
1219            subject: Term::Constant("a".to_string()),
1220            predicate: Term::Constant("p".to_string()),
1221            object: Term::Constant("b".to_string()),
1222        }];
1223
1224        let results = reasoner.execute_distributed_with_consensus(&[rule], &facts)?;
1225
1226        assert!(!results.is_empty());
1227        assert!(reasoner.leader_id.is_some());
1228        Ok(())
1229    }
1230
1231    #[test]
1232    fn test_heartbeat_timeout() -> Result<(), Box<dyn std::error::Error>> {
1233        let mut reasoner = DistributedReasoner::new(PartitionStrategy::RoundRobin);
1234
1235        reasoner.register_node(Node::new("node1".to_string(), "localhost:8001".to_string()))?;
1236
1237        // Check heartbeat timeout when no leader
1238        let election_triggered = reasoner.check_heartbeat_timeout()?;
1239
1240        assert!(election_triggered);
1241        assert!(reasoner.leader_id.is_some());
1242        Ok(())
1243    }
1244
1245    #[test]
1246    fn test_node_role_transitions() {
1247        let mut node = Node::new("test_node".to_string(), "localhost:8001".to_string());
1248
1249        assert_eq!(node.role, NodeRole::Follower);
1250        assert_eq!(node.term, 0);
1251
1252        // Promote to leader
1253        node.promote_to_leader(1);
1254        assert_eq!(node.role, NodeRole::Leader);
1255        assert_eq!(node.term, 1);
1256
1257        // Demote to follower
1258        node.demote_to_follower();
1259        assert_eq!(node.role, NodeRole::Follower);
1260
1261        // Start election
1262        node.start_election();
1263        assert_eq!(node.role, NodeRole::Candidate);
1264        assert_eq!(node.term, 2);
1265    }
1266}