Skip to main content

ghostlink_core/
load_balance.rs

1//! Tensor Distribution and Load Balancing for Ghost-Link Cluster
2//!
3//! This module provides:
4//! - Tensor distribution across nodes based on VRAM capacity
5//! - Dynamic load shedding
6//! - Deadlock prevention with timeout
7//! - Dynamic reconfiguration on hardware changes via `SystemProfileWatcher`.
8
9use crate::accelerator::ExecutionBackend;
10use crate::cluster::{ClusterState, NodeMetrics};
11use crate::host::{AccelerationMode, RuntimeProfile};
12use crate::system_profile::SystemProfile;
13use crate::watcher::ProfileChange;
14use std::sync::Arc;
15
16/// Load balancing configuration
17#[derive(Clone, Copy, Debug)]
18pub struct LoadBalanceConfig {
19    /// Maximum time to wait for lock acquisition (microseconds)
20    pub lock_timeout_us: u64,
21    /// Minimum load threshold for rebalancing
22    pub min_load_threshold: f32,
23    /// Maximum layers per node for single assignment
24    pub max_layers_per_assignment: usize,
25    /// Maximum concurrent rebalance transfers.
26    pub max_concurrent_rebalances: usize,
27}
28
29impl Default for LoadBalanceConfig {
30    fn default() -> Self {
31        Self {
32            lock_timeout_us: 1000, // 1ms
33            min_load_threshold: 1.25,
34            max_layers_per_assignment: 100,
35            max_concurrent_rebalances: 1,
36        }
37    }
38}
39
40impl LoadBalanceConfig {
41    /// Auto-tune load balancing thresholds from the detected runtime profile.
42    pub fn autotuned(profile: &RuntimeProfile) -> Self {
43        let base_timeout = match profile.acceleration_mode {
44            AccelerationMode::Gpu => 500,
45            AccelerationMode::Avx512 => 750,
46            _ => 1000,
47        };
48        // skew_ratio (max_available / min_available) is mathematically always
49        // >= 1.0, so a threshold below 1.0 here made rebalance() return true
50        // unconditionally for this tier — including the all-zero-VRAM CPU-only
51        // case (skew_ratio pinned to exactly 1.0), which a threshold of 1.0
52        // itself would still have wrongly matched. Must stay strictly > 1.0.
53        let min_load_threshold = match profile.acceleration_mode {
54            AccelerationMode::Gpu => 1.15,
55            AccelerationMode::Avx512 => 1.05,
56            _ => 1.02,
57        };
58        let max_layers_per_assignment = profile.recommended_workers.max(1) * 2;
59
60        Self {
61            lock_timeout_us: base_timeout,
62            min_load_threshold,
63            max_layers_per_assignment,
64            max_concurrent_rebalances: profile.recommended_workers.clamp(1, 8),
65        }
66    }
67}
68
69/// Tensor slice specification
70#[derive(Clone, Debug)]
71pub struct TensorSlice {
72    /// Layer index range for this tensor slice
73    pub layer_range: (usize, usize), // (start, end) exclusive
74    /// Size in GB
75    pub size_gb: f32,
76    /// Number of weights
77    pub num_weights: u32,
78}
79
80impl TensorSlice {
81    /// Create new tensor slice
82    pub fn new(layer_range: (usize, usize), size_gb: f32) -> Self {
83        Self {
84            layer_range,
85            size_gb,
86            num_weights: 0,
87        }
88    }
89}
90
91/// Load distribution plan across nodes
92#[derive(Clone, Debug)]
93pub struct LoadDistributionPlan {
94    /// Distribution of tensor slices per node
95    pub distributions: Vec<(String, Vec<TensorSlice>)>,
96    /// Total layers in plan
97    pub total_layers: usize,
98    /// Nodes participating
99    pub participating_nodes: Vec<String>,
100}
101
102impl LoadDistributionPlan {
103    /// Create new distribution plan
104    pub fn new(distributions: Vec<(String, Vec<TensorSlice>)>, total_layers: usize) -> Self {
105        let participating_nodes = distributions
106            .iter()
107            .map(|(node_id, _)| node_id.clone())
108            .collect();
109
110        Self {
111            distributions,
112            total_layers,
113            participating_nodes,
114        }
115    }
116
117    /// Generate human-readable plan summary
118    pub fn summary(&self) -> String {
119        let mut output = String::from("Load Distribution Plan\n");
120        output.push_str("======================\n\n");
121
122        for (node_id, slices) in &self.distributions {
123            output.push_str(&format!("Node: {node_id}\n"));
124
125            let total_size_gb: f32 = slices.iter().map(|s| s.size_gb).sum();
126
127            output.push_str(&format!("  Total size: {total_size_gb:.1} GB\n"));
128            output.push_str(&format!(
129                "  Layers: {}-{}\n",
130                slices.first().map(|s| s.layer_range.0).unwrap_or(0),
131                slices.last().map(|s| s.layer_range.1).unwrap_or(0)
132            ));
133            output.push('\n');
134        }
135
136        output.push_str(&format!("Total layers: {}\n", self.total_layers));
137        output.push_str(&format!("Nodes: {}\n", self.participating_nodes.join(", ")));
138
139        output
140    }
141}
142
143/// Load balancer for tensor distribution
144#[derive(Clone, Debug)]
145pub struct LoadBalancer {
146    /// Cluster state
147    cluster: Arc<ClusterState>,
148    /// Configuration (behind Mutex for atomic re-tune from watcher)
149    config: Arc<std::sync::Mutex<LoadBalanceConfig>>,
150}
151
152impl LoadBalancer {
153    /// Create new load balancer
154    pub fn new(cluster: Arc<ClusterState>, config: LoadBalanceConfig) -> Self {
155        Self {
156            cluster,
157            config: Arc::new(std::sync::Mutex::new(config)),
158        }
159    }
160
161    /// Create a load balancer with configuration derived from the local runtime profile.
162    pub fn with_runtime_profile(cluster: Arc<ClusterState>, profile: &RuntimeProfile) -> Self {
163        Self::new(cluster, LoadBalanceConfig::autotuned(profile))
164    }
165
166    /// Access the current configuration.
167    pub fn config(&self) -> LoadBalanceConfig {
168        self.config
169            .lock()
170            .ok()
171            .as_deref()
172            .copied()
173            .unwrap_or_default()
174    }
175
176    /// Distribute tensor layers across nodes based on VRAM capacity.
177    ///
178    /// Optimized using cursor-based index traversal instead of costly vector draining
179    /// and shifting elements, improving complexity from O(N^2) to O(N).
180    /// Further optimized by sorting references to NodeResources instead of cloning them,
181    /// and dynamically avoiding layer cloning/sorting if they are already in sequential order.
182    pub fn distribute_layers(
183        &self,
184        layers: &[crate::planning::LayerSpec],
185    ) -> Result<LoadDistributionPlan, String> {
186        let nodes_snapshot = self.cluster.nodes_snapshot();
187        if nodes_snapshot.is_empty() {
188            return Err("no nodes available".into());
189        }
190
191        // Sort references to nodes by VRAM capacity (descending) to avoid copying heap-allocated IDs and strings
192        let mut sorted_nodes: Vec<&crate::protocol::NodeResources> =
193            nodes_snapshot.iter().collect();
194        sorted_nodes.sort_by(|a, b| {
195            b.vram_gb
196                .partial_cmp(&a.vram_gb)
197                .unwrap_or(std::cmp::Ordering::Equal)
198        });
199
200        // Zero-copy shortcut: check if layers are already sorted (nearly always true).
201        // If already sorted, borrow instead of allocating/sorting a new vector.
202        let is_sorted = layers.windows(2).all(|w| w[0].index <= w[1].index);
203        let sorted_layers: std::borrow::Cow<'_, [crate::planning::LayerSpec]> = if is_sorted {
204            std::borrow::Cow::Borrowed(layers)
205        } else {
206            let mut all_layers = layers.to_vec();
207            all_layers.sort_by_key(|l| l.index);
208            std::borrow::Cow::Owned(all_layers)
209        };
210        let total_layer_count = sorted_layers.len();
211
212        // Greedy assignment: assign contiguous layers to nodes based on VRAM using O(1) indices
213        let mut distributions = Vec::with_capacity(sorted_nodes.len());
214        let mut current_layer_idx = 0usize;
215
216        for node in &sorted_nodes {
217            if current_layer_idx >= sorted_layers.len() {
218                break;
219            }
220
221            let mut used_vram = 0.0f32;
222            let start_idx = current_layer_idx;
223            let mut end_idx = current_layer_idx;
224
225            for layer in &sorted_layers[current_layer_idx..] {
226                if used_vram + layer.vram_gb > node.vram_gb {
227                    break;
228                }
229                end_idx += 1;
230                used_vram += layer.vram_gb;
231            }
232
233            if end_idx > start_idx {
234                let slices: Vec<TensorSlice> = sorted_layers[start_idx..end_idx]
235                    .iter()
236                    .map(|l| TensorSlice::new((l.index, l.index + 1), l.vram_gb))
237                    .collect();
238
239                distributions.push((node.id.clone(), slices));
240                current_layer_idx = end_idx;
241            }
242        }
243
244        if current_layer_idx >= sorted_layers.len() {
245            Ok(LoadDistributionPlan::new(distributions, total_layer_count))
246        } else {
247            Err(format!(
248                "insufficient VRAM: {} layers remain",
249                sorted_layers.len() - current_layer_idx
250            ))
251        }
252    }
253
254    /// Distribute layers and then chunk large node allocations to match worker parallelism.
255    pub fn distribute_layers_with_runtime_profile(
256        &self,
257        layers: &[crate::planning::LayerSpec],
258        profile: &RuntimeProfile,
259    ) -> Result<LoadDistributionPlan, String> {
260        let cfg = self.config();
261        let plan = self.distribute_layers(layers)?;
262        let backend = ExecutionBackend::from_runtime_profile(profile);
263        let vector_bias = (backend.vector_width_bits / 128).max(1);
264        let max_layers_per_slice = cfg
265            .max_layers_per_assignment
266            .min(profile.recommended_workers.max(1).saturating_mul(2))
267            .min(backend.preferred_batch_size / vector_bias)
268            .max(1);
269        Ok(chunk_distribution_plan(plan, max_layers_per_slice))
270    }
271
272    /// Rebalance load based on current node metrics
273    pub fn rebalance(&self) -> bool {
274        let cfg = self.config();
275        let active_nodes = self.cluster.active_nodes();
276
277        if active_nodes.is_empty() {
278            return false;
279        }
280
281        let mut min_available = f32::MAX;
282        let mut max_available = 0.0_f32;
283
284        for node in &active_nodes {
285            min_available = min_available.min(node.available_vram_gb.max(0.0));
286            max_available = max_available.max(node.available_vram_gb.max(0.0));
287        }
288
289        // A large spread in available VRAM indicates load imbalance.
290        let skew_ratio = if min_available <= f32::EPSILON {
291            if max_available > 0.0 {
292                f32::INFINITY
293            } else {
294                1.0
295            }
296        } else {
297            max_available / min_available
298        };
299
300        if skew_ratio >= cfg.min_load_threshold {
301            tracing::info!(
302                "Detected load skew ratio {:.2} (threshold {:.2})",
303                skew_ratio,
304                cfg.min_load_threshold
305            );
306            return true;
307        }
308
309        false
310    }
311
312    /// Shed load from overloaded nodes to underloaded ones
313    pub fn shed_load(&self) -> Vec<(String, String)> {
314        let cfg = self.config();
315        let mut transfers: Vec<(String, String)> = Vec::new();
316
317        // Overloaded nodes are close to exhausted VRAM (low available headroom).
318        let overloaded_nodes: Vec<_> = self
319            .cluster
320            .active_nodes()
321            .into_iter()
322            .filter(|m| m.available_vram_gb < m.total_vram_gb * 0.2)
323            .collect();
324
325        // Underloaded nodes have enough available headroom to receive load.
326        let underloaded_nodes: Vec<_> = self
327            .cluster
328            .active_nodes()
329            .into_iter()
330            .filter(|m| m.available_vram_gb > m.total_vram_gb * 0.5)
331            .collect();
332
333        // For each overloaded node, find a suitable underloaded target
334        for overloaded in &overloaded_nodes {
335            if transfers.len() >= cfg.max_concurrent_rebalances {
336                break;
337            }
338            if let Some(target) = self.find_best_target(underloaded_nodes.as_slice(), overloaded) {
339                transfers.push((overloaded.name.clone(), target.name.clone()));
340            }
341        }
342
343        transfers
344    }
345
346    /// Find best target node for load transfer
347    fn find_best_target(
348        &self,
349        targets: &[NodeMetrics],
350        source: &NodeMetrics,
351    ) -> Option<NodeMetrics> {
352        // Find node with most available VRAM that's different from source
353        let mut best_target: Option<&NodeMetrics> = None;
354        let mut max_available = 0.0f32;
355
356        for target in targets {
357            if target.name == source.name {
358                continue;
359            }
360
361            if target.available_vram_gb > max_available {
362                max_available = target.available_vram_gb;
363                best_target = Some(target);
364            }
365        }
366
367        best_target.cloned()
368    }
369
370    // ------------------------------------------------------------------
371    // SystemProfileWatcher integration
372    // ------------------------------------------------------------------
373
374    /// Re-tune load-balancing thresholds from a system profile detected at runtime.
375    pub fn reconfigure_from_system_profile(&self, profile: &SystemProfile) {
376        let rp: RuntimeProfile = profile.into();
377        if let Ok(mut guard) = self.config.lock() {
378            *guard = LoadBalanceConfig::autotuned(&rp);
379        }
380    }
381
382    /// Subscribe to a `SystemProfileWatcher`'s broadcast channel and
383    /// automatically re-tune whenever hardware changes are detected.
384    ///
385    /// Returns a `JoinHandle` that can be cancelled by dropping it.
386    pub fn subscribe_to_watcher(
387        self: &Arc<Self>,
388        watcher: &crate::watcher::SystemProfileWatcher,
389    ) -> tokio::task::JoinHandle<()> {
390        let this = self.clone();
391        let mut rx = watcher.subscribe();
392        tokio::spawn(async move {
393            while let Ok(event) = rx.recv().await {
394                if let ProfileChange::Updated(profile) = event {
395                    this.reconfigure_from_system_profile(&profile);
396                    tracing::info!(
397                        "load balancer re-tuned from profile: {} workers, {:?} accel",
398                        profile.recommended_workers,
399                        profile.acceleration_mode,
400                    );
401                }
402            }
403        })
404    }
405
406    /// Distribute layers with deadlock prevention
407    pub fn distribute_with_deadlock_prevention(
408        &self,
409        layers: &[crate::planning::LayerSpec],
410    ) -> Result<LoadDistributionPlan, String> {
411        let cfg = self.config();
412        // Use timeout-based acquisition to prevent deadlocks
413        let start_time = std::time::Instant::now();
414
415        while start_time.elapsed().as_micros() < cfg.lock_timeout_us as u128 {
416            match self.distribute_layers(layers) {
417                Ok(plan) => return Ok(plan),
418                Err(_) => {
419                    // Retry with backoff
420                    std::thread::sleep(std::time::Duration::from_millis(10));
421                }
422            }
423        }
424
425        Err("deadlock prevention timeout".into())
426    }
427}
428
429fn chunk_distribution_plan(
430    plan: LoadDistributionPlan,
431    max_layers_per_slice: usize,
432) -> LoadDistributionPlan {
433    let slice_limit = max_layers_per_slice.max(1);
434    let distributions = plan
435        .distributions
436        .into_iter()
437        .map(|(node_id, slices)| {
438            let estimated_chunks = slices
439                .iter()
440                .map(|slice| {
441                    let total_layers = slice.layer_range.1.saturating_sub(slice.layer_range.0);
442                    total_layers.div_ceil(slice_limit).max(1)
443                })
444                .sum();
445            let mut chunked = Vec::with_capacity(estimated_chunks);
446            for slice in slices {
447                let total_layers = slice.layer_range.1.saturating_sub(slice.layer_range.0);
448                if total_layers <= slice_limit {
449                    chunked.push(slice);
450                    continue;
451                }
452
453                let avg_size = if total_layers == 0 {
454                    0.0
455                } else {
456                    slice.size_gb / total_layers as f32
457                };
458                let mut start = slice.layer_range.0;
459                while start < slice.layer_range.1 {
460                    let end = (start + slice_limit).min(slice.layer_range.1);
461                    let layers_in_chunk = end - start;
462                    let mut chunk =
463                        TensorSlice::new((start, end), avg_size * layers_in_chunk as f32);
464                    chunk.num_weights = slice.num_weights;
465                    chunked.push(chunk);
466                    start = end;
467                }
468            }
469            (node_id, chunked)
470        })
471        .collect();
472
473    LoadDistributionPlan::new(distributions, plan.total_layers)
474}
475
476/// Load statistics collector
477#[derive(Clone, Debug, Default)]
478pub struct LoadStats {
479    /// Total layers distributed
480    pub total_layers_distributed: usize,
481    /// Total VRAM used across cluster
482    pub total_vram_used_gb: f32,
483    /// Average load balance ratio (0.0 to 1.0)
484    pub avg_load_balance_ratio: f32,
485    /// Number of rebalancing operations
486    pub rebalancing_count: usize,
487    /// Whether avg_load_balance_ratio has received its first sample yet.
488    balance_ratio_initialized: bool,
489}
490
491impl LoadStats {
492    /// Create new statistics collector
493    pub fn new() -> Self {
494        Self::default()
495    }
496
497    /// Record layer distribution
498    pub fn record_distribution(&mut self, num_layers: usize, vram_gb: f32) {
499        self.total_layers_distributed += num_layers;
500        self.total_vram_used_gb += vram_gb;
501    }
502
503    /// Update load balance ratio
504    pub fn update_balance_ratio(&mut self, ratio: f32) {
505        if !self.balance_ratio_initialized {
506            // First call - initialize directly
507            self.avg_load_balance_ratio = ratio;
508            self.balance_ratio_initialized = true;
509        } else {
510            // EMA with alpha=0.1
511            self.avg_load_balance_ratio = self.avg_load_balance_ratio * 0.9 + ratio * 0.1;
512        }
513    }
514
515    /// Record rebalancing operation
516    pub fn record_rebalancing(&mut self) {
517        self.rebalancing_count += 1;
518    }
519
520    /// Get load report
521    pub fn report(&self) -> String {
522        format!(
523            "Load Statistics\n\
524             ==========\n\
525             Total layers distributed: {}\n\
526             Total VRAM used: {:.1} GB\n\
527             Avg load balance ratio: {:.2}\n\
528             Rebalancing operations: {}",
529            self.total_layers_distributed,
530            self.total_vram_used_gb,
531            self.avg_load_balance_ratio,
532            self.rebalancing_count
533        )
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540    use crate::cluster::ClusterState;
541    use crate::host::AccelerationMode;
542    use crate::protocol::NodeResources;
543    use std::sync::Arc;
544
545    fn sample_layers(count: usize, vram_gb: f32) -> Vec<crate::planning::LayerSpec> {
546        (0..count)
547            .map(|index| crate::planning::LayerSpec {
548                index,
549                vram_gb,
550                num_weights: 0,
551            })
552            .collect()
553    }
554
555    fn sample_nodes(count: usize, base_vram: f32) -> Vec<NodeResources> {
556        (0..count)
557            .map(|i| {
558                NodeResources::new(
559                    format!("node-{i}"),
560                    base_vram + (i as f32 * 6.0),
561                    64.0,
562                    "8.9".to_string(),
563                    None,
564                )
565            })
566            .collect()
567    }
568
569    #[test]
570    fn load_balancer_distributes_layers() {
571        let cluster = ClusterState::new();
572        for node in sample_nodes(2, 24.0) {
573            cluster.register(node);
574        }
575
576        let layers = sample_layers(33, 1.0);
577        let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
578
579        let plan = balancer.distribute_layers(&layers).unwrap();
580        assert_eq!(plan.total_layers, 33);
581    }
582
583    #[test]
584    fn load_balancer_generates_summary() {
585        let cluster = ClusterState::new();
586        for node in sample_nodes(2, 24.0) {
587            cluster.register(node);
588        }
589
590        let layers = sample_layers(33, 1.0);
591        let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
592
593        let plan = balancer.distribute_layers(&layers).unwrap();
594        let summary = plan.summary();
595
596        assert!(summary.contains("Total layers: 33"));
597    }
598
599    #[test]
600    fn load_stats_records_distribution() {
601        let mut stats = LoadStats::new();
602
603        stats.record_distribution(24, 24.0);
604        stats.record_distribution(9, 9.0);
605
606        assert_eq!(stats.total_layers_distributed, 33);
607        assert!((stats.total_vram_used_gb - 33.0).abs() < 0.01);
608    }
609
610    #[test]
611    fn load_stats_updates_balance_ratio() {
612        let mut stats = LoadStats::new();
613
614        stats.update_balance_ratio(0.95);
615        assert!((stats.avg_load_balance_ratio - 0.95).abs() < 1e-6);
616
617        stats.update_balance_ratio(0.85);
618        // EMA: 0.95 * 0.9 + 0.85 * 0.1 = 0.855 + 0.085 = 0.94
619        assert!((stats.avg_load_balance_ratio - 0.94).abs() < 1e-6);
620    }
621
622    #[test]
623    fn load_stats_first_balance_ratio_not_diluted_by_prior_distribution() {
624        // Regression: the "first call" check for update_balance_ratio used
625        // total_layers_distributed == 0 as a proxy for "never updated
626        // before". If record_distribution() ran first (the normal order:
627        // record layer placements, then periodically report a balance
628        // ratio), the very first update_balance_ratio() call fell through
629        // to the EMA branch and diluted the true first sample by 10x
630        // (0.0 * 0.9 + ratio * 0.1) instead of setting it directly.
631        let mut stats = LoadStats::new();
632
633        stats.record_distribution(24, 24.0);
634        stats.update_balance_ratio(0.95);
635
636        assert!(
637            (stats.avg_load_balance_ratio - 0.95).abs() < 1e-6,
638            "first balance ratio sample must be set directly, got {}",
639            stats.avg_load_balance_ratio
640        );
641    }
642
643    #[test]
644    fn load_stats_reports() {
645        let mut stats = LoadStats::new();
646
647        stats.record_distribution(24, 24.0);
648        stats.update_balance_ratio(0.95);
649
650        let report = stats.report();
651        assert!(report.contains("Total layers distributed: 24"));
652    }
653
654    #[test]
655    fn autotuned_config_reflects_runtime_profile() {
656        let profile = RuntimeProfile {
657            node_resources: NodeResources::new("node-a", 24.0, 64.0, "8.9", None),
658            logical_cores: 16,
659            recommended_workers: 6,
660            acceleration_mode: AccelerationMode::Gpu,
661            gpu_backend: crate::host::GpuBackend::Cuda,
662            xdp_supported: true,
663            detection_source: String::from("test"),
664            probe_mode: crate::host::ProbeMode::Fast,
665        };
666
667        let config = LoadBalanceConfig::autotuned(&profile);
668        assert_eq!(config.lock_timeout_us, 500);
669        assert_eq!(config.max_layers_per_assignment, 12);
670        assert_eq!(config.max_concurrent_rebalances, 6);
671        assert!(config.min_load_threshold > 1.0);
672    }
673
674    #[test]
675    fn autotuned_cpu_threshold_stays_above_one() {
676        // Regression: the CPU/generic tier's min_load_threshold was 0.95,
677        // below the mathematical minimum of skew_ratio (always >= 1.0), so
678        // rebalance() always returned true regardless of actual balance.
679        let profile = RuntimeProfile {
680            node_resources: NodeResources::new("node-a", 0.0, 16.0, "generic", None),
681            logical_cores: 4,
682            recommended_workers: 2,
683            acceleration_mode: AccelerationMode::Generic,
684            gpu_backend: crate::host::GpuBackend::Cpu,
685            xdp_supported: false,
686            detection_source: String::from("test"),
687            probe_mode: crate::host::ProbeMode::Fast,
688        };
689        let config = LoadBalanceConfig::autotuned(&profile);
690        assert!(
691            config.min_load_threshold > 1.0,
692            "CPU-tier threshold {} must exceed skew_ratio's mathematical floor of 1.0",
693            config.min_load_threshold
694        );
695    }
696
697    #[test]
698    fn rebalance_does_not_always_trigger_on_balanced_cpu_cluster() {
699        let cluster = Arc::new(ClusterState::new());
700        cluster.register(NodeResources::new("node-a", 0.0, 16.0, "generic", None));
701        cluster.register(NodeResources::new("node-b", 0.0, 16.0, "generic", None));
702
703        let profile = RuntimeProfile {
704            node_resources: NodeResources::new("node-a", 0.0, 16.0, "generic", None),
705            logical_cores: 4,
706            recommended_workers: 2,
707            acceleration_mode: AccelerationMode::Generic,
708            gpu_backend: crate::host::GpuBackend::Cpu,
709            xdp_supported: false,
710            detection_source: String::from("test"),
711            probe_mode: crate::host::ProbeMode::Fast,
712        };
713        let balancer = LoadBalancer::new(cluster, LoadBalanceConfig::autotuned(&profile));
714        assert!(
715            !balancer.rebalance(),
716            "a perfectly balanced (zero-VRAM) CPU cluster must not be reported as needing rebalance"
717        );
718    }
719
720    #[test]
721    fn runtime_profile_chunks_large_distribution_slices() {
722        let plan = LoadDistributionPlan::new(
723            vec![("node-a".into(), vec![TensorSlice::new((0, 10), 10.0)])],
724            10,
725        );
726
727        let chunked = chunk_distribution_plan(plan, 4);
728        assert_eq!(chunked.distributions[0].1.len(), 3);
729        assert_eq!(chunked.distributions[0].1[0].layer_range, (0, 4));
730        assert_eq!(chunked.distributions[0].1[2].layer_range, (8, 10));
731    }
732
733    #[test]
734    fn shed_load_moves_from_low_headroom_to_high_headroom_nodes() {
735        let cluster = ClusterState::new();
736        cluster.register(NodeResources::new("node-hot", 24.0, 64.0, "8.9", None));
737        cluster.register(NodeResources::new("node-cool", 24.0, 64.0, "8.9", None));
738
739        // node-hot is overloaded (very low available VRAM)
740        cluster.get_metrics_mut("node-hot", |m| {
741            m.available_vram_gb = 2.0;
742            m.total_vram_gb = 24.0;
743        });
744
745        // node-cool has enough headroom to receive work
746        cluster.get_metrics_mut("node-cool", |m| {
747            m.available_vram_gb = 20.0;
748            m.total_vram_gb = 24.0;
749        });
750
751        let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
752        let transfers = balancer.shed_load();
753
754        assert_eq!(transfers.len(), 1);
755        assert_eq!(transfers[0].0, "node-hot");
756        assert_eq!(transfers[0].1, "node-cool");
757    }
758}