rusty-stack 0.3.1

A comprehensive ML environment installer and platform toolkit optimized for AMD GPUs with ROCm support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Plan types and topological sorting.
//!
//! This module implements:
//! - [`PlanItem`] — a component update plan item with risk tier, dependencies, etc.
//! - [`topological_sort`] — sorts components by dependency order
//! - [`Plan`] — a full update plan with items and summary

use crate::core::types::{RiskTier, ValidationTier};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

// ---------------------------------------------------------------------------
// Plan Item
// ---------------------------------------------------------------------------

/// Input bundle for [`PlanItem::new`].
///
/// Groups the eight construction fields so the constructor stays well under
/// clippy's `too_many_arguments` threshold.
#[derive(Debug, Clone)]
pub struct PlanItemInput {
    /// Component ID.
    pub component_id: String,
    /// Currently installed version (empty if not installed).
    pub current_version: String,
    /// Proposed version to install.
    pub proposed_version: String,
    /// Validation tier of this component.
    pub validation_tier: ValidationTier,
    /// Whether this item is selected for apply.
    pub selected: bool,
    /// Human-readable rationale for this update.
    pub rationale: String,
    /// Component IDs this item depends on.
    pub dependencies: Vec<String>,
    /// Whether this component can be installed in isolation.
    pub isolation_safe: bool,
}

/// A single item in an update plan.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlanItem {
    /// Component ID.
    pub component_id: String,
    /// Currently installed version (empty if not installed).
    pub current_version: String,
    /// Proposed version to install.
    pub proposed_version: String,
    /// Validation tier of this component.
    pub validation_tier: ValidationTier,
    /// Whether this item is selected for apply.
    pub selected: bool,
    /// Human-readable rationale for this update.
    pub rationale: String,
    /// Component IDs this item depends on.
    #[serde(default)]
    pub dependencies: Vec<String>,
    /// Whether this component can be installed in isolation.
    pub isolation_safe: bool,
    /// Risk tier (low/medium/high).
    pub risk_tier: RiskTier,
}

impl PlanItem {
    /// Create a new plan item.
    pub fn new(input: PlanItemInput) -> Self {
        Self {
            component_id: input.component_id,
            current_version: input.current_version,
            proposed_version: input.proposed_version,
            validation_tier: input.validation_tier,
            selected: input.selected,
            rationale: input.rationale,
            dependencies: input.dependencies,
            isolation_safe: input.isolation_safe,
            risk_tier: RiskTier::Medium, // default
        }
    }
}

// ---------------------------------------------------------------------------
// Topological Sort
// ---------------------------------------------------------------------------

/// Sort components topologically by their dependencies.
///
/// Returns a new vector with components ordered such that all dependencies
/// of a component appear before the component itself.
///
/// # Arguments
/// * `items` - Vector of plan items
///
/// # Returns
/// A new vector with items in topological order.
///
/// # Panics
/// Panics if a dependency cycle is detected.
pub fn topological_sort(items: Vec<PlanItem>) -> Vec<PlanItem> {
    // Track remaining dependencies for each node
    let mut remaining_deps: HashMap<String, Vec<String>> = HashMap::new();
    // Track which nodes depend on each node (for cleanup)
    let mut dependents: HashMap<String, Vec<String>> = HashMap::new();
    let mut all_nodes: HashSet<String> = HashSet::new();

    // Initialize tracking structures
    for item in &items {
        all_nodes.insert(item.component_id.clone());
        // Each node starts with all its declared dependencies
        remaining_deps.insert(item.component_id.clone(), item.dependencies.clone());
        // Track dependents for cleanup
        for dep in &item.dependencies {
            dependents
                .entry(dep.clone())
                .or_default()
                .push(item.component_id.clone());
        }
    }

    // Kahn's algorithm
    let mut sorted_nodes = Vec::new();

    // Start with nodes that have no dependencies
    let mut queue: Vec<String> = all_nodes
        .iter()
        .filter(|id| remaining_deps.get(*id).is_none_or(|d| d.is_empty()))
        .cloned()
        .collect();

    while let Some(node) = queue.pop() {
        sorted_nodes.push(node.clone());

        // Find all nodes that depend on this node
        if let Some(dep_on_node) = dependents.get(&node) {
            for dependent in dep_on_node.clone() {
                // Remove this node from dependent's remaining dependencies
                if let Some(deps) = remaining_deps.get_mut(&dependent) {
                    deps.retain(|d| d != &node);
                    // If all dependencies are now satisfied, add to queue
                    if deps.is_empty() {
                        queue.push(dependent);
                    }
                }
            }
        }
    }

    if sorted_nodes.len() != all_nodes.len() {
        panic!("Dependency cycle detected in plan items");
    }

    // Reconstruct plan items in topological order
    let mut item_map: HashMap<String, PlanItem> = items
        .into_iter()
        .map(|item| (item.component_id.clone(), item))
        .collect();

    sorted_nodes
        .into_iter()
        .filter_map(|id| item_map.remove(&id))
        .collect()
}

// ---------------------------------------------------------------------------
// Plan
// ---------------------------------------------------------------------------

/// A full update plan with items and summary.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Plan {
    /// Plan items in execution order.
    pub items: Vec<PlanItem>,
    /// Summary statistics.
    pub summary: PlanSummary,
}

/// Summary statistics for a plan.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlanSummary {
    pub total: usize,
    pub selected: usize,
    pub safe: usize,
    pub guarded: usize,
    pub candidate: usize,
    pub experimental: usize,
    pub blocked: usize,
}

impl Plan {
    /// Create a new plan from items.
    pub fn new(items: Vec<PlanItem>) -> Self {
        let items = topological_sort(items);
        let summary = PlanSummary::from_items(&items);
        Self { items, summary }
    }
}

impl PlanSummary {
    /// Compute summary from a list of plan items.
    pub fn from_items(items: &[PlanItem]) -> Self {
        Self {
            total: items.len(),
            selected: items.iter().filter(|i| i.selected).count(),
            safe: items
                .iter()
                .filter(|i| i.risk_tier == RiskTier::Low)
                .count(),
            guarded: items
                .iter()
                .filter(|i| i.risk_tier == RiskTier::Medium)
                .count(),
            candidate: items
                .iter()
                .filter(|i| i.risk_tier == RiskTier::High)
                .count(),
            experimental: items
                .iter()
                .filter(|i| i.validation_tier == ValidationTier::Experimental)
                .count(),
            blocked: 0, // blocked items are filtered out
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::{RiskTier, ValidationTier};

    // -----------------------------------------------------------------------
    // VAL-PLAN-001: Topological sort orders dependencies before dependents
    // -----------------------------------------------------------------------

    #[test]
    fn test_topological_sort_simple_dependency() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
        ];

        let sorted = topological_sort(items);
        assert_eq!(sorted[0].component_id, "rocm");
        assert_eq!(sorted[1].component_id, "pytorch");
    }

    #[test]
    fn test_topological_sort_complex_dependency_chain() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "triton".into(),
                current_version: "3.0.0".into(),
                proposed_version: "3.1.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update triton".into(),
                dependencies: vec!["pytorch".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
        ];

        let sorted = topological_sort(items);
        assert_eq!(sorted[0].component_id, "rocm");
        assert_eq!(sorted[1].component_id, "pytorch");
        assert_eq!(sorted[2].component_id, "triton");
    }

    #[test]
    fn test_topological_sort_empty_dependencies() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
        ];

        let sorted = topological_sort(items);
        // Order of independent items is not guaranteed, but all should be present
        let ids: HashSet<_> = sorted.iter().map(|i| i.component_id.clone()).collect();
        assert!(ids.contains("pytorch"));
        assert!(ids.contains("rocm"));
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-002: Topological sort detects dependency cycles
    // -----------------------------------------------------------------------

    #[test]
    #[should_panic(expected = "Dependency cycle detected")]
    fn test_topological_sort_detects_cycle() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec!["triton".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "triton".into(),
                current_version: "3.0.0".into(),
                proposed_version: "3.1.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update triton".into(),
                dependencies: vec!["pytorch".to_string()],
                isolation_safe: true,
            }),
        ];

        topological_sort(items);
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-003: Plan creation applies topological sort
    // -----------------------------------------------------------------------

    #[test]
    fn test_plan_creation_applies_topological_sort() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
        ];

        let plan = Plan::new(items);
        assert_eq!(plan.items[0].component_id, "rocm");
        assert_eq!(plan.items[1].component_id, "pytorch");
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-004: Plan summary counts are accurate
    // -----------------------------------------------------------------------

    #[test]
    fn test_plan_summary_counts() {
        let items = vec![
            PlanItem {
                component_id: "rocm".to_string(),
                current_version: "7.2.0".to_string(),
                proposed_version: "7.3.0".to_string(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".to_string(),
                dependencies: vec![],
                isolation_safe: true,
                risk_tier: RiskTier::Low,
            },
            PlanItem {
                component_id: "pytorch".to_string(),
                current_version: "2.4.0".to_string(),
                proposed_version: "2.5.0".to_string(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".to_string(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
                risk_tier: RiskTier::Medium,
            },
            PlanItem {
                component_id: "deepspeed".to_string(),
                current_version: "".to_string(),
                proposed_version: "0.15.0".to_string(),
                validation_tier: ValidationTier::Experimental,
                selected: false,
                rationale: "new experimental".to_string(),
                dependencies: vec!["pytorch".to_string()],
                isolation_safe: true,
                risk_tier: RiskTier::High,
            },
        ];

        let plan = Plan::new(items);
        assert_eq!(plan.summary.total, 3);
        assert_eq!(plan.summary.selected, 2);
        assert_eq!(plan.summary.safe, 1);
        assert_eq!(plan.summary.guarded, 1);
        assert_eq!(plan.summary.candidate, 1);
        assert_eq!(plan.summary.experimental, 1);
        assert_eq!(plan.summary.blocked, 0);
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-005: PlanItem serde roundtrip
    // -----------------------------------------------------------------------

    #[test]
    fn test_plan_item_serde_roundtrip() {
        let item = PlanItem {
            component_id: "pytorch".to_string(),
            current_version: "2.4.0".to_string(),
            proposed_version: "2.5.0".to_string(),
            validation_tier: ValidationTier::Validated,
            selected: true,
            rationale: "update pytorch".to_string(),
            dependencies: vec!["rocm".to_string()],
            isolation_safe: true,
            risk_tier: RiskTier::Medium,
        };

        let json = serde_json::to_string(&item).unwrap();
        let back: PlanItem = serde_json::from_str(&json).unwrap();
        assert_eq!(item, back);
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-006: Plan serde roundtrip
    // -----------------------------------------------------------------------

    #[test]
    fn test_plan_serde_roundtrip() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "pytorch".into(),
                current_version: "2.4.0".into(),
                proposed_version: "2.5.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update pytorch".into(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
            }),
        ];

        let plan = Plan::new(items);
        let json = serde_json::to_string(&plan).unwrap();
        let back: Plan = serde_json::from_str(&json).unwrap();
        assert_eq!(plan.items, back.items);
        assert_eq!(plan.summary, back.summary);
    }

    // -----------------------------------------------------------------------
    // VAL-PLAN-007: Topological sort with dependencies from baseline manifest
    // -----------------------------------------------------------------------

    #[test]
    fn test_topological_sort_with_llama_cpp_dependencies() {
        let items = vec![
            PlanItem::new(PlanItemInput {
                component_id: "llama-cpp".into(),
                current_version: "".into(),
                proposed_version: "latest".into(),
                validation_tier: ValidationTier::Experimental,
                selected: true,
                rationale: "install llama-cpp".into(),
                dependencies: vec!["rocm".to_string()],
                isolation_safe: true,
            }),
            PlanItem::new(PlanItemInput {
                component_id: "rocm".into(),
                current_version: "7.2.0".into(),
                proposed_version: "7.3.0".into(),
                validation_tier: ValidationTier::Validated,
                selected: true,
                rationale: "update rocm".into(),
                dependencies: vec![],
                isolation_safe: true,
            }),
        ];

        let sorted = topological_sort(items);
        assert_eq!(sorted[0].component_id, "rocm");
        assert_eq!(sorted[1].component_id, "llama-cpp");
    }
}