Skip to main content

alien_core/resources/
compute_cluster.rs

1//! ComputeCluster resource for long-running container workloads.
2//!
3//! A ComputeCluster represents the setup-owned compute boundary for containers.
4//! Setup provisions:
5//! - Auto Scaling Groups (AWS), Managed Instance Groups (GCP), or VM Scale Sets (Azure)
6//! - IAM roles/service accounts for machine authentication
7//! - Security groups/firewall rules
8//! - Launch templates/instance configurations
9
10use crate::error::{ErrorData, Result};
11use crate::instance_catalog::{find_instance_type, is_same_architecture_machine, Architecture};
12use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef};
13use crate::{PermissionProfile, Platform, ResourceType};
14use alien_error::AlienError;
15use bon::Builder;
16use serde::{Deserialize, Serialize};
17use std::any::Any;
18use std::collections::BTreeMap;
19use std::fmt::Debug;
20
21/// GPU specification for a capacity group.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
24#[serde(rename_all = "camelCase")]
25pub struct GpuSpec {
26    /// GPU type identifier (e.g., "nvidia-a100", "nvidia-t4")
27    #[serde(rename = "type")]
28    pub gpu_type: String,
29    /// Number of GPUs per machine
30    pub count: u32,
31}
32
33/// Machine resource profile for a capacity group.
34///
35/// Represents the hardware specifications for machines in a capacity group.
36/// These are hardware totals (what the instance type advertises), not allocatable
37/// capacity. The managed container scheduler internally subtracts system reserves for planning.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
40#[serde(rename_all = "camelCase")]
41pub struct MachineProfile {
42    /// CPU cores per machine (hardware total) - stored as string to preserve precision
43    /// (e.g., "8.0", "4.5")
44    pub cpu: String,
45    /// Memory in bytes (hardware total)
46    pub memory_bytes: u64,
47    /// Ephemeral storage in bytes (hardware total)
48    pub ephemeral_storage_bytes: u64,
49    /// CPU architecture required or provided by this machine profile.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub architecture: Option<Architecture>,
52    /// GPU specification (optional)
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub gpu: Option<GpuSpec>,
55    /// Additional empty block device each machine must provide, besides the
56    /// disk holding the operating system. On AWS, GCP and Azure the runtime
57    /// controller attaches one to every machine; on Machines, `join` refuses a
58    /// host without one. Kubernetes rejects it.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub data_disk: Option<DataDiskRequirement>,
61}
62
63/// An additional block device a machine must provide with no partitions,
64/// no filesystem signature, and no mounts, so the workload can format it.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
67#[serde(rename_all = "camelCase")]
68pub struct DataDiskRequirement {
69    /// Minimum device size in bytes.
70    pub size_bytes: u64,
71}
72
73/// Allowed range and default for a count selected by the installer.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
76#[serde(rename_all = "camelCase")]
77pub struct ComputeChoiceRange {
78    /// Lowest allowed value.
79    pub min: u32,
80    /// Highest allowed value.
81    pub max: u32,
82    /// Default value recommended when no installer override is supplied.
83    pub default: u32,
84}
85
86impl ComputeChoiceRange {
87    /// Returns whether a selected value is inside the allowed range.
88    pub fn contains(&self, value: u32) -> bool {
89        self.min <= value && value <= self.max
90    }
91}
92
93/// Source-declared scale policy for a capacity group.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
96#[serde(rename_all = "camelCase", tag = "type")]
97pub enum CapacityGroupScalePolicy {
98    /// A fixed-size pool where the installer can choose the fixed machine count.
99    Fixed {
100        /// Allowed fixed machine count range.
101        machines: ComputeChoiceRange,
102    },
103    /// An autoscaling pool with separately bounded min and max counts.
104    Autoscale {
105        /// Allowed minimum machine count range.
106        min: ComputeChoiceRange,
107        /// Allowed maximum machine count range.
108        max: ComputeChoiceRange,
109    },
110}
111
112impl CapacityGroupScalePolicy {
113    /// Derive the legacy policy represented by selected min/max values.
114    pub fn from_selected_bounds(min_size: u32, max_size: u32) -> Self {
115        if min_size == max_size {
116            Self::Fixed {
117                machines: ComputeChoiceRange {
118                    min: min_size,
119                    max: max_size,
120                    default: min_size,
121                },
122            }
123        } else {
124            Self::Autoscale {
125                min: ComputeChoiceRange {
126                    min: min_size,
127                    max: min_size,
128                    default: min_size,
129                },
130                max: ComputeChoiceRange {
131                    min: max_size,
132                    max: max_size,
133                    default: max_size,
134                },
135            }
136        }
137    }
138
139    /// Default selected min bound.
140    pub fn default_min_size(&self) -> u32 {
141        match self {
142            Self::Fixed { machines } => machines.default,
143            Self::Autoscale { min, .. } => min.default,
144        }
145    }
146
147    /// Default selected max bound.
148    pub fn default_max_size(&self) -> u32 {
149        match self {
150            Self::Fixed { machines } => machines.default,
151            Self::Autoscale { max, .. } => max.default,
152        }
153    }
154}
155
156/// Capacity group definition.
157///
158/// A capacity group represents machines with identical hardware profiles.
159/// Each group becomes a separate Auto Scaling Group (AWS), Managed Instance Group (GCP),
160/// or VM Scale Set (Azure).
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
163#[serde(rename_all = "camelCase")]
164pub struct CapacityGroup {
165    /// Unique identifier for this capacity group (must be lowercase alphanumeric with hyphens)
166    pub group_id: String,
167    /// Provider machine selected at deployment time.
168    /// `alien.ts` should declare portable requirements; preflight materialization
169    /// fills this field from `StackSettings.compute`.
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub instance_type: Option<String>,
172    /// Machine resource profile (auto-derived from instance_type if not specified)
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub profile: Option<MachineProfile>,
175    /// Minimum number of machines (can be 0 for scale-to-zero)
176    pub min_size: u32,
177    /// Maximum number of machines (must be ≤ 10)
178    pub max_size: u32,
179    /// Source-declared scale policy and installer-editable bounds.
180    ///
181    /// Older stacks only have `minSize` and `maxSize`; planners derive an exact
182    /// fixed/autoscale policy from those selected bounds when this field is absent.
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub scale_policy: Option<CapacityGroupScalePolicy>,
185    /// Require instance types that expose nested virtualization (VT-x/EPT)
186    /// to guest VMs. This is needed by workloads that boot nested VMs inside
187    /// containers.
188    /// When true, the controller's instance-type selector is constrained
189    /// to a vetted nested-virt-capable allowlist.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub nested_virtualization: Option<bool>,
192    /// Data disk sizes, in GiB, a deployment may choose from. Present only when
193    /// the source declares a range; `profile.data_disk` then holds the default
194    /// (absent when the default is 0, which means no data disk). Preflight
195    /// writes the deployment's choice into `profile.data_disk`.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub data_disk_gib_range: Option<ComputeChoiceRange>,
198}
199
200impl CapacityGroup {
201    /// AWS root volume size, including filesystem headroom and runtime overhead.
202    pub fn aws_root_volume_size_gib(&self) -> i32 {
203        self.aws_filesystem_size_gib()
204            .saturating_add(12)
205            .max(20)
206            .min(i32::MAX as u64) as i32
207    }
208
209    /// AWS second EBS volume: the declared data disk, or for a nested
210    /// virtualization pool without one, the volume such pools have always
211    /// received, sized from ephemeral storage.
212    pub fn aws_runtime_data_volume_size_gib(&self) -> Option<i32> {
213        if let Some(size_gib) = self.data_disk_size_gib() {
214            return Some(size_gib.min(i32::MAX as u64) as i32);
215        }
216        (self.nested_virtualization == Some(true))
217            .then(|| self.aws_filesystem_size_gib().max(20).min(i32::MAX as u64) as i32)
218    }
219
220    /// The `CpuOptions.NestedVirtualization` value an AWS launch template for this group
221    /// sends when it names `instance_type`, or `None` for no CPU options.
222    ///
223    /// Bare metal gives guests KVM from the hardware and AWS rejects the option there, so it
224    /// gets an explicit `disabled`: a version created with `SourceVersion` inherits every
225    /// field it omits and would otherwise keep `enabled`.
226    pub fn aws_nested_virtualization(&self, instance_type: &str) -> Option<&'static str> {
227        let bare_metal = find_instance_type(Platform::Aws, instance_type)
228            .is_some_and(|spec| spec.bare_metal);
229        if bare_metal {
230            Some("disabled")
231        } else if self.nested_virtualization == Some(true) {
232            Some("enabled")
233        } else {
234            None
235        }
236    }
237
238    /// Whether `other` asks for different disks than this group: another root
239    /// storage size or data disk. Runtime controllers replace machines for it.
240    pub fn disks_differ(&self, other: &CapacityGroup) -> bool {
241        let disks = |group: &CapacityGroup| {
242            group
243                .profile
244                .as_ref()
245                .map(|profile| (profile.ephemeral_storage_bytes, profile.data_disk.clone()))
246        };
247        disks(self) != disks(other)
248    }
249
250    /// Data disk sizes a deployment may choose, in GiB: the declared range, or
251    /// just the declared size. `None` when the pool declares no data disk.
252    pub fn data_disk_choices(&self) -> Option<ComputeChoiceRange> {
253        if let Some(range) = &self.data_disk_gib_range {
254            return Some(range.clone());
255        }
256        let size_gib = u32::try_from(self.data_disk_size_gib()?).unwrap_or(u32::MAX);
257        Some(ComputeChoiceRange {
258            min: size_gib,
259            max: size_gib,
260            default: size_gib,
261        })
262    }
263
264    /// Data disk size, in GiB, this pool runs with for a deployment that chose
265    /// `selected` (`None` uses the default). 0 means no data disk.
266    pub fn effective_data_disk_gib(
267        &self,
268        selected: Option<u32>,
269    ) -> std::result::Result<Option<u32>, String> {
270        let Some(choices) = self.data_disk_choices() else {
271            return match selected {
272                None | Some(0) => Ok(None),
273                Some(size) => Err(format!(
274                    "pool '{}' declares no data disk, so dataDiskGib {size} cannot be chosen",
275                    self.group_id
276                )),
277            };
278        };
279        let size = selected.unwrap_or(choices.default);
280        if !choices.contains(size) {
281            return Err(if choices.min == choices.max {
282                format!(
283                    "pool '{}' has a fixed {} GiB data disk; dataDiskGib {size} cannot be chosen",
284                    self.group_id, choices.min
285                )
286            } else {
287                format!(
288                    "pool '{}' data disk must be between {} and {} GiB; dataDiskGib {size} is outside that range",
289                    self.group_id, choices.min, choices.max
290                )
291            });
292        }
293        Ok(Some(size))
294    }
295
296    /// The data disk this pool's machines get for a deployment that chose
297    /// `selected` GiB (`None` uses the default; 0 means none).
298    pub fn selected_data_disk(
299        &self,
300        selected: Option<u32>,
301    ) -> std::result::Result<Option<DataDiskRequirement>, String> {
302        let size_gib = self.effective_data_disk_gib(selected)?;
303        if self.data_disk_gib_range.is_none() {
304            // A fixed size stands as declared, to the byte: "500G" must keep
305            // accepting a 500 GB disk rather than the 466 GiB it rounds up to.
306            return Ok(self
307                .profile
308                .as_ref()
309                .and_then(|profile| profile.data_disk.clone()));
310        }
311        Ok(size_gib
312            .filter(|size_gib| *size_gib > 0)
313            .map(|size_gib| DataDiskRequirement {
314                size_bytes: u64::from(size_gib) * 1024 * 1024 * 1024,
315            }))
316    }
317
318    /// Declared data disk size, rounded up to a whole GiB.
319    pub fn data_disk_size_gib(&self) -> Option<u64> {
320        let data_disk = self.profile.as_ref()?.data_disk.as_ref()?;
321        Some(data_disk.size_bytes.div_ceil(1024 * 1024 * 1024))
322    }
323
324    fn aws_filesystem_size_gib(&self) -> u64 {
325        self.profile
326            .as_ref()
327            .map_or(0, |profile| profile.ephemeral_storage_bytes)
328            .div_ceil(1024 * 1024 * 1024)
329            .saturating_mul(5)
330            .div_ceil(4)
331    }
332}
333
334/// ComputeCluster resource for running long-running container workloads.
335///
336/// A ComputeCluster provides the setup-owned machine boundary for containers.
337/// Alien may manage the worker fleet inside that boundary when setup grants
338/// `compute-cluster/management`.
339///
340/// ## Architecture
341///
342/// - **Setup** creates cloud resources: ASGs/MIGs/VMSSs, IAM roles, security groups
343/// - **Alien** manages allowed fleet operations: machine count, runtime
344///   machine image rollout and, on AWS, the machine type within one CPU architecture
345/// - A node agent runs on each machine from the selected runtime image channel
346///
347/// ## Example
348///
349/// ```rust
350/// use alien_core::{CapacityGroup, ComputeCluster, MachineProfile};
351///
352/// let cluster = ComputeCluster::new("compute".to_string())
353///     .capacity_group(CapacityGroup {
354///         group_id: "general".to_string(),
355///         instance_type: None,
356///         profile: Some(MachineProfile {
357///             cpu: "4.0".to_string(),
358///             memory_bytes: 16 * 1024 * 1024 * 1024,
359///             ephemeral_storage_bytes: 20 * 1024 * 1024 * 1024,
360///             architecture: None,
361///             gpu: None,
362///             data_disk: None,
363///         }),
364///         min_size: 1,
365///         max_size: 5,
366///         scale_policy: None,
367///         nested_virtualization: None,
368///         data_disk_gib_range: None,
369///     })
370///     .build();
371/// ```
372#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
373#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
374#[serde(rename_all = "camelCase", deny_unknown_fields)]
375#[builder(start_fn = new)]
376pub struct ComputeCluster {
377    /// Unique identifier for the container cluster.
378    /// Must contain only alphanumeric characters, hyphens, and underscores.
379    #[builder(start_fn)]
380    pub id: String,
381
382    /// Capacity groups defining the machine pools for this cluster.
383    /// Each group becomes a separate ASG/MIG/VMSS.
384    #[builder(field)]
385    pub capacity_groups: Vec<CapacityGroup>,
386
387    /// Explicit grants for the node identity, keyed by concrete resource ID.
388    /// Independent of workload permission profiles; absent grants no data access.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub node_permissions: Option<PermissionProfile>,
391
392    /// Cloud platforms on which the explicit node grants apply; absent applies everywhere.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub node_permissions_platforms: Option<Vec<Platform>>,
395
396    /// Pool reserved for containers created after a deployment is installed.
397    /// If absent, the runtime uses the `general` pool when it exists.
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub dynamic_container_pool: Option<String>,
400
401    /// Concrete provider failure domains selected during setup, keyed by capacity group.
402    /// Empty preserves the existing aggregate layout when no spread policy is configured.
403    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
404    #[builder(default)]
405    pub selected_failure_domains: BTreeMap<String, Vec<String>>,
406
407    /// Requested failure-domain spread keyed by capacity group.
408    /// Empty preserves the existing aggregate layout.
409    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
410    #[builder(default)]
411    pub failure_domain_spread: BTreeMap<String, u8>,
412
413    /// Container CIDR block for internal container networking.
414    /// Auto-generated as "10.244.0.0/16" if not specified.
415    /// Each machine gets a /24 subnet from this range.
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub container_cidr: Option<String>,
418}
419
420impl ComputeCluster {
421    /// The resource type identifier for ComputeCluster
422    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("compute-cluster");
423
424    /// Returns the cluster's unique identifier.
425    pub fn id(&self) -> &str {
426        &self.id
427    }
428
429    /// Returns the container CIDR, defaulting to "10.244.0.0/16" if not specified.
430    pub fn container_cidr(&self) -> &str {
431        self.container_cidr.as_deref().unwrap_or("10.244.0.0/16")
432    }
433}
434
435impl<S: compute_cluster_builder::State> ComputeClusterBuilder<S> {
436    /// Adds a capacity group to the cluster.
437    pub fn capacity_group(mut self, group: CapacityGroup) -> Self {
438        self.capacity_groups.push(group);
439        self
440    }
441}
442
443/// Status of a single capacity group within a ComputeCluster.
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
446#[serde(rename_all = "camelCase")]
447pub struct CapacityGroupStatus {
448    /// Capacity group ID
449    pub group_id: String,
450    /// Current number of machines
451    pub current_machines: u32,
452    /// Desired number of machines (from the managed container capacity plan)
453    pub desired_machines: u32,
454    /// Instance type being used
455    pub instance_type: String,
456}
457
458/// Outputs generated by a successfully provisioned ComputeCluster.
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
461#[serde(rename_all = "camelCase")]
462pub struct ComputeClusterOutputs {
463    /// Managed container cluster ID (workspace/project/deployment/resourceid format)
464    pub cluster_id: String,
465    /// Whether the managed container cluster is ready
466    pub horizon_ready: bool,
467    /// Status of each capacity group
468    pub capacity_group_statuses: Vec<CapacityGroupStatus>,
469    /// Total number of machines across all capacity groups
470    pub total_machines: u32,
471}
472
473impl ResourceOutputsDefinition for ComputeClusterOutputs {
474    fn get_resource_type(&self) -> ResourceType {
475        ComputeCluster::RESOURCE_TYPE.clone()
476    }
477
478    fn as_any(&self) -> &dyn Any {
479        self
480    }
481
482    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
483        Box::new(self.clone())
484    }
485
486    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
487        other.as_any().downcast_ref::<ComputeClusterOutputs>() == Some(self)
488    }
489
490    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
491        serde_json::to_value(self)
492    }
493}
494
495impl ResourceDefinition for ComputeCluster {
496    fn get_resource_type(&self) -> ResourceType {
497        Self::RESOURCE_TYPE
498    }
499
500    fn id(&self) -> &str {
501        &self.id
502    }
503
504    fn replace_after_failed_create_is_safe(&self) -> bool {
505        // A create that failed waiting for instances may already run some; deleting it terminates
506        // them, and in a capacity-starved zone the capacity may not come back.
507        false
508    }
509
510    fn get_dependencies(&self) -> Vec<ResourceRef> {
511        // ComputeCluster has no static dependencies.
512        // Network dependency is platform-specific:
513        // - AWS/GCP/Azure: Added by ComputeClusterMutation
514        // - Local/Kubernetes: Not needed (Docker/K8s handles networking)
515        // Platform controllers use require_dependency() at runtime to access Network state.
516        Vec::new()
517    }
518
519    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
520        let new_cluster = new_config
521            .as_any()
522            .downcast_ref::<ComputeCluster>()
523            .ok_or_else(|| {
524                AlienError::new(ErrorData::UnexpectedResourceType {
525                    resource_id: self.id.clone(),
526                    expected: Self::RESOURCE_TYPE,
527                    actual: new_config.get_resource_type(),
528                })
529            })?;
530
531        if self.id != new_cluster.id {
532            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
533                resource_id: self.id.clone(),
534                reason: "the 'id' field is immutable".to_string(),
535            }));
536        }
537
538        // Container CIDR is immutable once set
539        if self.container_cidr.is_some()
540            && new_cluster.container_cidr.is_some()
541            && self.container_cidr != new_cluster.container_cidr
542        {
543            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
544                resource_id: self.id.clone(),
545                reason: "the 'containerCidr' field is immutable once set".to_string(),
546            }));
547        }
548
549        // Validate capacity groups
550        for new_group in &new_cluster.capacity_groups {
551            if let Some(existing_group) = self
552                .capacity_groups
553                .iter()
554                .find(|g| g.group_id == new_group.group_id)
555            {
556                // The controller rolls the fleet onto another machine of the same architecture;
557                // the stack's images may not run on any other machine. Preflights also limit
558                // this to the installed cloud, which this check can't see.
559                if let (Some(old), Some(new)) = (
560                    existing_group.instance_type.as_deref(),
561                    new_group.instance_type.as_deref(),
562                ) {
563                    if old != new
564                        && ![Platform::Aws, Platform::Gcp, Platform::Azure]
565                            .into_iter()
566                            .any(|platform| is_same_architecture_machine(platform, old, new))
567                    {
568                        return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
569                            resource_id: self.id.clone(),
570                            reason: format!(
571                                "capacity group '{}' can't change machine from '{old}' to '{new}': only a catalog machine in the same cloud and of the same CPU architecture can replace it",
572                                new_group.group_id
573                            ),
574                        }));
575                    }
576                }
577            }
578        }
579
580        Ok(())
581    }
582
583    fn as_any(&self) -> &dyn Any {
584        self
585    }
586
587    fn as_any_mut(&mut self) -> &mut dyn Any {
588        self
589    }
590
591    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
592        Box::new(self.clone())
593    }
594
595    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
596        other.as_any().downcast_ref::<ComputeCluster>() == Some(self)
597    }
598
599    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
600        serde_json::to_value(self)
601    }
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607
608    #[test]
609    fn aws_nested_virtualization_follows_the_machine() {
610        let group = |nested: Option<bool>| CapacityGroup {
611            group_id: "general".into(),
612            instance_type: None,
613            profile: None,
614            min_size: 1,
615            max_size: 1,
616            scale_policy: None,
617            nested_virtualization: nested,
618            data_disk_gib_range: None,
619        };
620        for (instance_type, nested, expected) in [
621            ("c8id.4xlarge", Some(true), Some("enabled")),
622            ("c8id.4xlarge", None, None),
623            ("m7g.large", Some(false), None),
624            ("c8id.metal-48xl", Some(true), Some("disabled")),
625            ("m8id.metal-96xl", None, Some("disabled")),
626            ("c5.metal", Some(true), Some("disabled")),
627        ] {
628            assert_eq!(
629                group(nested).aws_nested_virtualization(instance_type),
630                expected,
631                "{instance_type} nested={nested:?}"
632            );
633        }
634    }
635
636    #[test]
637    fn aws_disk_sizing_preserves_rounding_minimums_and_saturation() {
638        let gib = 1024 * 1024 * 1024;
639        for (bytes, root, data) in [
640            (0, 20, 20),
641            (gib, 20, 20),
642            (20 * gib, 37, 25),
643            (20 * gib + 1, 39, 27),
644            (u64::MAX, i32::MAX, i32::MAX),
645        ] {
646            let mut group = CapacityGroup {
647                group_id: "general".into(),
648                instance_type: None,
649                profile: Some(MachineProfile {
650                    cpu: "4.0".into(),
651                    memory_bytes: 8 * gib,
652                    ephemeral_storage_bytes: bytes,
653                    architecture: None,
654                    gpu: None,
655                    data_disk: None,
656                }),
657                min_size: 1,
658                max_size: 1,
659                scale_policy: None,
660                nested_virtualization: None,
661                data_disk_gib_range: None,
662            };
663            assert_eq!(group.aws_root_volume_size_gib(), root);
664            assert_eq!(group.aws_runtime_data_volume_size_gib(), None);
665            group.nested_virtualization = Some(true);
666            assert_eq!(group.aws_root_volume_size_gib(), root);
667            assert_eq!(group.aws_runtime_data_volume_size_gib(), Some(data));
668        }
669    }
670
671    /// A fixed size keeps its declared bytes, so a host disk that met it still
672    /// does; a size picked from a range is whole GiB.
673    #[test]
674    fn a_fixed_data_disk_keeps_its_declared_bytes() {
675        let gib: u64 = 1024 * 1024 * 1024;
676        let declared = DataDiskRequirement {
677            size_bytes: 500_000_000_000,
678        };
679        let mut group = CapacityGroup {
680            group_id: "general".into(),
681            instance_type: None,
682            profile: Some(MachineProfile {
683                cpu: "4.0".into(),
684                memory_bytes: 8 * gib,
685                ephemeral_storage_bytes: 20 * gib,
686                architecture: None,
687                gpu: None,
688                data_disk: Some(declared.clone()),
689            }),
690            min_size: 1,
691            max_size: 1,
692            scale_policy: None,
693            nested_virtualization: None,
694            data_disk_gib_range: None,
695        };
696        // 500 GB rounds up to 466 GiB, which is the one size a deployment may name.
697        assert_eq!(group.selected_data_disk(None), Ok(Some(declared.clone())));
698        assert_eq!(group.selected_data_disk(Some(466)), Ok(Some(declared)));
699        assert!(group.selected_data_disk(Some(500)).is_err());
700
701        group.data_disk_gib_range = Some(ComputeChoiceRange {
702            min: 0,
703            max: 1024,
704            default: 466,
705        });
706        assert_eq!(
707            group.selected_data_disk(None),
708            Ok(Some(DataDiskRequirement {
709                size_bytes: 466 * gib
710            }))
711        );
712        assert_eq!(group.selected_data_disk(Some(0)), Ok(None));
713    }
714
715    #[test]
716    fn declared_data_disk_replaces_the_nested_virtualization_volume() {
717        let gib = 1024 * 1024 * 1024;
718        let group = |nested: Option<bool>, data_disk_bytes: u64| CapacityGroup {
719            group_id: "general".into(),
720            instance_type: None,
721            profile: Some(MachineProfile {
722                cpu: "4.0".into(),
723                memory_bytes: 8 * gib,
724                ephemeral_storage_bytes: 20 * gib,
725                architecture: None,
726                gpu: None,
727                data_disk: Some(DataDiskRequirement {
728                    size_bytes: data_disk_bytes,
729                }),
730            }),
731            min_size: 1,
732            max_size: 1,
733            scale_policy: None,
734            nested_virtualization: nested,
735            data_disk_gib_range: None,
736        };
737        for nested in [None, Some(false), Some(true)] {
738            // Root keeps the ephemeral storage formula; the second volume is
739            // exactly the declared size, not the 25 GiB implicit volume.
740            assert_eq!(group(nested, 30 * gib).aws_root_volume_size_gib(), 37);
741            assert_eq!(
742                group(nested, 30 * gib).aws_runtime_data_volume_size_gib(),
743                Some(30)
744            );
745            assert_eq!(
746                group(nested, 30 * gib + 1).aws_runtime_data_volume_size_gib(),
747                Some(31)
748            );
749        }
750        assert_eq!(group(None, 512 * 1024 * 1024).data_disk_size_gib(), Some(1));
751    }
752
753    #[test]
754    fn test_compute_cluster_creation() {
755        let cluster = ComputeCluster::new("compute".to_string())
756            .capacity_group(CapacityGroup {
757                group_id: "general".to_string(),
758                instance_type: Some("m7g.xlarge".to_string()),
759                profile: None,
760                min_size: 1,
761                max_size: 5,
762                scale_policy: None,
763                nested_virtualization: None,
764                data_disk_gib_range: None,
765            })
766            .build();
767
768        assert_eq!(cluster.id(), "compute");
769        assert_eq!(cluster.capacity_groups.len(), 1);
770        assert_eq!(cluster.capacity_groups[0].group_id, "general");
771        assert_eq!(cluster.container_cidr(), "10.244.0.0/16");
772    }
773
774    #[test]
775    fn test_compute_cluster_multiple_capacity_groups() {
776        let cluster = ComputeCluster::new("multi-pool".to_string())
777            .capacity_group(CapacityGroup {
778                group_id: "general".to_string(),
779                instance_type: Some("m7g.xlarge".to_string()),
780                profile: None,
781                min_size: 1,
782                max_size: 3,
783                scale_policy: None,
784                nested_virtualization: None,
785                data_disk_gib_range: None,
786            })
787            .capacity_group(CapacityGroup {
788                group_id: "gpu".to_string(),
789                instance_type: Some("g5.xlarge".to_string()),
790                profile: Some(MachineProfile {
791                    cpu: "4.0".to_string(),
792                    memory_bytes: 17179869184,             // 16 GiB
793                    ephemeral_storage_bytes: 214748364800, // 200 GiB
794                    architecture: None,
795                    gpu: Some(GpuSpec {
796                        gpu_type: "nvidia-a10g".to_string(),
797                        count: 1,
798                    }),
799                    data_disk: None,
800                }),
801                min_size: 0,
802                max_size: 2,
803                scale_policy: None,
804                nested_virtualization: None,
805                data_disk_gib_range: None,
806            })
807            .build();
808
809        assert_eq!(cluster.capacity_groups.len(), 2);
810        assert_eq!(cluster.capacity_groups[0].group_id, "general");
811        assert_eq!(cluster.capacity_groups[1].group_id, "gpu");
812        assert!(cluster.capacity_groups[1]
813            .profile
814            .as_ref()
815            .unwrap()
816            .gpu
817            .is_some());
818    }
819
820    #[test]
821    fn test_compute_cluster_custom_cidr() {
822        let cluster = ComputeCluster::new("custom-net".to_string())
823            .container_cidr("172.30.0.0/16".to_string())
824            .capacity_group(CapacityGroup {
825                group_id: "general".to_string(),
826                instance_type: None,
827                profile: None,
828                min_size: 1,
829                max_size: 5,
830                scale_policy: None,
831                nested_virtualization: None,
832                data_disk_gib_range: None,
833            })
834            .build();
835
836        assert_eq!(cluster.container_cidr(), "172.30.0.0/16");
837    }
838
839    #[test]
840    fn test_compute_cluster_validate_update_immutable_id() {
841        let cluster1 = ComputeCluster::new("cluster-1".to_string())
842            .capacity_group(CapacityGroup {
843                group_id: "general".to_string(),
844                instance_type: None,
845                profile: None,
846                min_size: 1,
847                max_size: 5,
848                scale_policy: None,
849                nested_virtualization: None,
850                data_disk_gib_range: None,
851            })
852            .build();
853
854        let cluster2 = ComputeCluster::new("cluster-2".to_string())
855            .capacity_group(CapacityGroup {
856                group_id: "general".to_string(),
857                instance_type: None,
858                profile: None,
859                min_size: 1,
860                max_size: 5,
861                scale_policy: None,
862                nested_virtualization: None,
863                data_disk_gib_range: None,
864            })
865            .build();
866
867        let result = cluster1.validate_update(&cluster2);
868        assert!(result.is_err());
869    }
870
871    #[test]
872    fn test_compute_cluster_validate_update_scale_change() {
873        let cluster1 = ComputeCluster::new("compute".to_string())
874            .capacity_group(CapacityGroup {
875                group_id: "general".to_string(),
876                instance_type: Some("m7g.xlarge".to_string()),
877                profile: None,
878                min_size: 1,
879                max_size: 5,
880                scale_policy: None,
881                nested_virtualization: None,
882                data_disk_gib_range: None,
883            })
884            .build();
885
886        let cluster2 = ComputeCluster::new("compute".to_string())
887            .capacity_group(CapacityGroup {
888                group_id: "general".to_string(),
889                instance_type: Some("m7g.xlarge".to_string()),
890                profile: None,
891                min_size: 2,
892                max_size: 10,
893                scale_policy: None,
894                nested_virtualization: None,
895                data_disk_gib_range: None,
896            })
897            .build();
898
899        // Scale changes should be allowed
900        let result = cluster1.validate_update(&cluster2);
901        assert!(result.is_ok());
902    }
903
904    #[test]
905    fn machine_changes_stay_within_one_cloud_and_architecture() {
906        let cluster = |machine: &str| {
907            ComputeCluster::new("compute".to_string())
908                .capacity_group(CapacityGroup {
909                    group_id: "general".to_string(),
910                    instance_type: Some(machine.to_string()),
911                    profile: None,
912                    min_size: 1,
913                    max_size: 5,
914                    scale_policy: None,
915                    nested_virtualization: None,
916                    data_disk_gib_range: None,
917                })
918                .build()
919        };
920        for (old, new) in [
921            ("t4g.small", "t4g.medium"),
922            ("e2-medium", "n2-standard-4"),
923            ("Standard_D2s_v5", "Standard_D4s_v5"),
924        ] {
925            cluster(old)
926                .validate_update(&cluster(new))
927                .expect("same cloud and architecture");
928        }
929        for (old, new) in [
930            ("t4g.small", "m7i.large"),
931            ("t4g.small", "t4g.unknown"),
932            ("n2-standard-2", "m7i.large"),
933            ("Standard_D2s_v5", "n2-standard-4"),
934        ] {
935            let error = cluster(old)
936                .validate_update(&cluster(new))
937                .expect_err("needs setup");
938            assert_eq!(error.code, "INVALID_RESOURCE_UPDATE", "{old} -> {new}");
939        }
940    }
941
942    #[test]
943    fn node_permissions_are_inline_optional_and_roundtrip_exactly() {
944        let mut cluster = ComputeCluster::new("compute".to_string()).build();
945        let absent = serde_json::to_value(&cluster).unwrap();
946        assert!(absent.get("nodePermissions").is_none());
947        assert_eq!(
948            serde_json::from_value::<ComputeCluster>(absent).unwrap(),
949            cluster
950        );
951        cluster.node_permissions =
952            Some(PermissionProfile::new().resource("objects", ["storage/data-read"]));
953        let json = serde_json::to_value(&cluster).unwrap();
954        assert_eq!(
955            json["nodePermissions"],
956            serde_json::json!({"objects": ["storage/data-read"]})
957        );
958        assert_eq!(
959            serde_json::from_value::<ComputeCluster>(json).unwrap(),
960            cluster
961        );
962        assert_eq!(ResourceDefinition::get_permissions(&cluster), None);
963    }
964
965    #[test]
966    fn test_compute_cluster_serialization() {
967        let cluster = ComputeCluster::new("test-cluster".to_string())
968            .capacity_group(CapacityGroup {
969                group_id: "general".to_string(),
970                instance_type: Some("m7g.xlarge".to_string()),
971                profile: None,
972                min_size: 1,
973                max_size: 5,
974                scale_policy: None,
975                nested_virtualization: None,
976                data_disk_gib_range: None,
977            })
978            .build();
979
980        let json = serde_json::to_string(&cluster).unwrap();
981        let deserialized: ComputeCluster = serde_json::from_str(&json).unwrap();
982        assert_eq!(cluster, deserialized);
983    }
984}