Skip to main content

alien_core/
instance_catalog.rs

1//! Instance type catalog and selection algorithm for cloud compute infrastructure.
2//!
3//! This module provides:
4//! - A static catalog of known instance types across AWS, GCP, and Azure
5//! - Resource quantity parsing (CPU strings, Kubernetes-style memory/storage quantities)
6//! - An algorithm to select the optimal instance type for a given workload
7//!
8//! The catalog is the single source of truth for instance type specifications.
9//! It is used by the preflights system to automatically populate `CapacityGroup.instance_type`
10//! and `CapacityGroup.profile` based on the containers in a stack.
11
12use crate::{GpuSpec, MachineProfile, Platform};
13use serde::{Deserialize, Serialize};
14
15// ---------------------------------------------------------------------------
16// Resource quantity parsing
17// ---------------------------------------------------------------------------
18
19/// Parse a CPU quantity string to f64.
20///
21/// Accepts plain numbers ("1", "0.5", "2.0") and millicore suffixes ("500m" = 0.5).
22pub fn parse_cpu(s: &str) -> Result<f64, String> {
23    let s = s.trim();
24    if s.is_empty() {
25        return Err("empty CPU string".to_string());
26    }
27
28    if let Some(millis) = s.strip_suffix('m') {
29        let v: f64 = millis
30            .parse()
31            .map_err(|_| format!("invalid CPU millicore value: '{s}'"))?;
32        Ok(v / 1000.0)
33    } else {
34        s.parse().map_err(|_| format!("invalid CPU value: '{s}'"))
35    }
36}
37
38/// Parse a memory or storage quantity string to bytes.
39///
40/// Supports Kubernetes-style binary suffixes (Ki, Mi, Gi, Ti) and
41/// decimal suffixes (k, M, G, T). Plain numbers are interpreted as bytes.
42pub fn parse_memory_bytes(s: &str) -> Result<u64, String> {
43    let s = s.trim();
44    if s.is_empty() {
45        return Err("empty memory/storage string".to_string());
46    }
47
48    for (suffix, multiplier) in [
49        ("Ti", 1024_f64.powi(4)),
50        ("Gi", 1024_f64.powi(3)),
51        ("Mi", 1024_f64.powi(2)),
52        ("Ki", 1024_f64),
53        ("T", 1_000_000_000_000_f64),
54        ("G", 1_000_000_000_f64),
55        ("M", 1_000_000_f64),
56        ("k", 1_000_f64),
57    ] {
58        if let Some(number) = s.strip_suffix(suffix) {
59            let value: f64 = number
60                .parse()
61                .map_err(|_| format!("invalid memory value: '{s}'"))?;
62            let bytes = value * multiplier;
63            // Float-to-integer casts saturate negatives, infinity and NaN instead of
64            // returning an error. Reject them before a sizing request reaches a provider.
65            if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
66                return Err(format!("memory value is out of range: '{s}'"));
67            }
68            return Ok(bytes as u64);
69        }
70    }
71    s.parse()
72        .map_err(|_| format!("invalid memory value: '{s}'"))
73}
74
75// ---------------------------------------------------------------------------
76// Instance type catalog
77// ---------------------------------------------------------------------------
78
79/// Instance family classification.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
82#[serde(rename_all = "camelCase")]
83pub enum InstanceFamily {
84    Burstable,
85    GeneralPurpose,
86    ComputeOptimized,
87    MemoryOptimized,
88    StorageOptimized,
89    GpuCompute,
90}
91
92/// CPU architecture.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
95#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
96#[serde(rename_all = "snake_case")]
97pub enum Architecture {
98    Arm64,
99    X86_64,
100}
101
102/// Default machine architecture for images built for a managed cloud.
103pub fn default_architecture(platform: Platform) -> Option<Architecture> {
104    match platform {
105        Platform::Aws => Some(Architecture::Arm64),
106        Platform::Gcp | Platform::Azure => Some(Architecture::X86_64),
107        Platform::Kubernetes | Platform::Machines | Platform::Local | Platform::Test => None,
108    }
109}
110
111/// Static GPU specification for catalog entries (no heap allocation).
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct CatalogGpu {
114    pub gpu_type: &'static str,
115    pub count: u32,
116}
117
118/// A known instance type with its hardware specifications.
119///
120/// All fields are compile-time constants. The catalog is a flat array of these.
121#[derive(Debug, Clone)]
122pub struct InstanceTypeSpec {
123    pub name: &'static str,
124    pub platform: Platform,
125    /// The category the machine's series belongs to.
126    pub family: InstanceFamily,
127    /// The provider series the machine belongs to (`m8i`, `n2-standard`, `Dsv5`).
128    pub series: &'static str,
129    /// How the series is shown to people choosing a machine.
130    pub label: &'static str,
131    pub architecture: Architecture,
132    /// vCPU count (hardware total)
133    pub vcpu: u32,
134    /// Memory in bytes (hardware total)
135    pub memory_bytes: u64,
136    /// Ephemeral storage in bytes (hardware total, NVMe for storage-optimized)
137    pub ephemeral_storage_bytes: u64,
138    /// Local instance disk the provider reports for the machine, in bytes; 0 when it has none.
139    pub local_disk_bytes: u64,
140    /// The provider's machine type for this row. It differs from `name` only for a catalog
141    /// row that adds an accelerator to a machine type, such as `n1-standard-4-t4`.
142    pub machine_type: &'static str,
143    /// GPU specification (for GPU instances)
144    pub gpu: Option<CatalogGpu>,
145    /// Whether the machine exposes nested virtualization (VT-x/EPT) to guest VMs. On bare
146    /// metal, guests get KVM from the hardware instead.
147    pub nested_virt: bool,
148    /// Whether the machine is a bare-metal host rather than a virtual machine.
149    pub bare_metal: bool,
150    /// Whether automatic selection may pick the machine. The set is fixed so that adding a
151    /// machine to the catalog never changes what an existing stack gets; any other machine is
152    /// used only when someone chooses it.
153    pub auto_select: bool,
154    /// Whether the machine picker lists the series first: on AWS the current plain, `d` and `-flex`
155    /// families of the newest generation those reach in their category and processor, their bare
156    /// metal, and every GPU series; every GCP and Azure series.
157    pub primary: bool,
158}
159
160impl InstanceTypeSpec {
161    /// Whether ephemeral storage is a provider disk that can be sized at
162    /// deployment time instead of fixed local instance storage.
163    pub fn has_configurable_ephemeral_storage(&self) -> bool {
164        matches!(
165            self.family,
166            InstanceFamily::Burstable
167                | InstanceFamily::GeneralPurpose
168                | InstanceFamily::ComputeOptimized
169                | InstanceFamily::MemoryOptimized
170        )
171    }
172
173    /// Whether this instance type supports nested virtualization.
174    ///
175    /// GCP still requires the instance template to opt in; Azure exposes the
176    /// capability automatically on supported VM sizes.
177    pub fn is_nested_virt_capable(&self) -> bool {
178        self.nested_virt
179    }
180
181    /// Convert this catalog entry into a `MachineProfile` for use in `CapacityGroup`.
182    pub fn to_machine_profile(&self) -> MachineProfile {
183        MachineProfile {
184            cpu: format!("{}.0", self.vcpu),
185            memory_bytes: self.memory_bytes,
186            ephemeral_storage_bytes: self.ephemeral_storage_bytes,
187            architecture: Some(self.architecture),
188            gpu: self.gpu.map(|g| GpuSpec {
189                gpu_type: g.gpu_type.to_string(),
190                count: g.count,
191            }),
192            data_disk: None,
193        }
194    }
195
196    /// Convert this entry to the profile controllers should provision for a
197    /// workload. Configurable cloud disks grow to the requested capacity;
198    /// fixed local disks retain their catalog capacity.
199    pub fn to_machine_profile_for_storage(&self, requested_bytes: u64) -> MachineProfile {
200        let mut profile = self.to_machine_profile();
201        if self.has_configurable_ephemeral_storage() {
202            profile.ephemeral_storage_bytes = profile.ephemeral_storage_bytes.max(requested_bytes);
203        }
204        profile
205    }
206}
207
208// Helpers for readable byte constants
209const KI: u64 = 1024;
210const MI: u64 = KI * 1024;
211const GI: u64 = MI * 1024;
212const TI: u64 = GI * 1024;
213
214/// Maximum workload storage that the current cloud controllers can turn into
215/// their provider-backed root disk after adding 25% filesystem headroom and
216/// 12 GiB of runtime overhead. Keep these bounds in sync with the provider
217/// controller contract; rejecting here is preferable to failing after cloud
218/// resources have already been created.
219pub fn max_configurable_ephemeral_storage_bytes(platform: Platform) -> Option<u64> {
220    let disk_limit_gib = match platform {
221        // AWS gp3 and GCP persistent disks currently top out at 64 TiB.
222        Platform::Aws | Platform::Gcp => 64 * 1024,
223        // Azure managed OS disks currently top out at 4,095 GiB.
224        Platform::Azure => 4_095,
225        Platform::Kubernetes | Platform::Machines | Platform::Local | Platform::Test => {
226            return None;
227        }
228    };
229
230    // Controllers first round the requested bytes up to a whole GiB, then
231    // round the 25% headroom up again. Returning a fractional-GiB bound would
232    // therefore admit `bound + 1 byte` and materialize a disk one GiB over the
233    // provider limit.
234    let max_requested_gib = (disk_limit_gib - 12) * 4 / 5;
235    Some(max_requested_gib * GI)
236}
237
238/// The instance type catalog, generated from the clouds' machine APIs by
239/// `scripts/instance-catalog/generate.py` from `instance-catalog.toml`.
240mod catalog;
241use catalog::CATALOG;
242
243// ---------------------------------------------------------------------------
244// Catalog lookup
245// ---------------------------------------------------------------------------
246
247/// Get all instance types for a given platform.
248pub fn catalog_for_platform(platform: Platform) -> Vec<&'static InstanceTypeSpec> {
249    CATALOG
250        .iter()
251        .filter(|spec| spec.platform == platform)
252        .collect()
253}
254
255/// Find a specific instance type by name and platform.
256pub fn find_instance_type(platform: Platform, name: &str) -> Option<&'static InstanceTypeSpec> {
257    CATALOG
258        .iter()
259        .find(|spec| spec.platform == platform && spec.name == name)
260}
261
262/// Whether a capacity group may move from AWS machine `old` to `new` without setup: both are
263/// catalog machines of one CPU architecture, so the stack's images still run on the new one.
264pub fn is_same_architecture_aws_machine(old: &str, new: &str) -> bool {
265    is_same_architecture_machine(Platform::Aws, old, new)
266}
267
268/// Whether two catalog machines belong to the given cloud and share a CPU architecture.
269pub fn is_same_architecture_machine(platform: Platform, old: &str, new: &str) -> bool {
270    matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure)
271        && find_instance_type(platform, old)
272            .zip(find_instance_type(platform, new))
273            .is_some_and(|(old, new)| old.architecture == new.architecture)
274}
275
276// ---------------------------------------------------------------------------
277// Instance type selection
278// ---------------------------------------------------------------------------
279
280/// Aggregated resource requirements from all containers in a capacity group.
281#[derive(Debug, Clone)]
282pub struct WorkloadRequirements {
283    /// Total CPU needed at desired scale (sum of desired CPU * desired_replicas per container)
284    pub total_cpu_at_desired: f64,
285    /// Total memory needed at desired scale (sum of desired memory * desired_replicas per container)
286    pub total_memory_bytes_at_desired: u64,
287    /// Total CPU needed at maximum scale (sum of desired CPU * max_replicas per container)
288    pub total_cpu_at_max: f64,
289    /// Total memory needed at maximum scale (sum of desired memory * max_replicas per container)
290    pub total_memory_bytes_at_max: u64,
291    /// Largest CPU request among all individual containers (single replica)
292    pub max_cpu_per_container: f64,
293    /// Largest memory request among all individual containers (single replica)
294    pub max_memory_per_container: u64,
295    /// Maximum ephemeral storage any single container requires
296    pub max_ephemeral_storage_bytes: u64,
297    /// GPU requirement (if any container needs GPU)
298    pub gpu: Option<GpuSpec>,
299    /// Required CPU architecture, when source explicitly constrains it.
300    pub architecture: Option<Architecture>,
301    /// If true, only instance types that expose nested virtualization (VT-x/EPT)
302    /// to guest VMs are eligible. Required by workloads that run QEMU/KVM
303    /// inside a container.
304    pub nested_virt: bool,
305}
306
307/// Result of instance type selection.
308#[derive(Debug, Clone)]
309pub struct InstanceSelection {
310    /// Selected instance type name (e.g., "m7g.2xlarge")
311    pub instance_type: &'static str,
312    /// Machine profile derived from the instance type
313    pub profile: MachineProfile,
314    /// Recommended minimum number of machines
315    pub min_machines: u32,
316    /// Recommended maximum number of machines
317    pub max_machines: u32,
318}
319
320/// Ephemeral storage threshold above which storage-optimized instances are selected.
321const STORAGE_OPTIMIZED_THRESHOLD: u64 = 200 * GI;
322
323/// Maximum number of machines per cluster.
324const MAX_MACHINES_PER_CLUSTER: u32 = 10;
325
326/// Preferred vCPU cap for non-GPU/non-storage workloads. A larger indivisible
327/// allocation or bounded fleet can require a bigger machine.
328const MAX_STANDARD_VCPU: u32 = 8;
329
330/// Runtime CPU reserved for system processes on each managed container machine.
331const SYSTEM_RESERVE_CPU: f64 = 0.5;
332
333/// Runtime planning headroom for total desired/max workload.
334const WORKLOAD_HEADROOM_FACTOR: f64 = 1.15;
335
336/// Select the best instance type for a workload on a given platform.
337///
338/// The algorithm:
339/// 1. GPU workloads: Match by GPU type, find smallest instance with enough GPUs.
340/// 2. Storage-heavy workloads (>200Gi ephemeral): Use storage-optimized instances.
341/// 3. All other workloads: Fit the allocation with system reserve and headroom,
342///    preferring at most 8 vCPUs unless the allocation requires more. Use the
343///    workload's preferred family, with general-purpose fallback when needed.
344///
345/// Returns an error if no suitable instance type is found.
346pub fn select_instance_type(
347    platform: Platform,
348    requirements: &WorkloadRequirements,
349) -> Result<InstanceSelection, String> {
350    select_instance_type_where(platform, requirements, &|_| true)
351}
352
353/// A machine that automatic selection may pick, restricted by a caller's filter.
354type MachineFilter<'a> = &'a dyn Fn(&InstanceTypeSpec) -> bool;
355
356/// Like [`select_instance_type`], but only from the series that have room for `machines`
357/// machines. `has_room` answers for one machine type of a series. The ordinary selection runs
358/// first; a pick whose series has no room removes that series and selection runs again, so
359/// every preference of the ordinary selection (local disk before a configurable one, the
360/// smallest machine that fits, catalog order between equal machines) still applies to the
361/// series that remain. When no series has room, the result is the plain selection, so the
362/// caller's quota check reports the refusal. Pass the machines the pool launches with.
363pub fn select_instance_type_with_room(
364    platform: Platform,
365    requirements: &WorkloadRequirements,
366    machines: u32,
367    has_room: &dyn Fn(&InstanceTypeSpec, u32) -> bool,
368) -> Result<InstanceSelection, String> {
369    let mut without_room: Vec<&'static str> = Vec::new();
370    loop {
371        let remaining = |spec: &InstanceTypeSpec| !without_room.contains(&spec.series);
372        let Ok(selection) = select_instance_type_where(platform, requirements, &remaining) else {
373            break;
374        };
375        let Some(spec) = find_instance_type(platform, selection.instance_type) else {
376            break;
377        };
378        if has_room(spec, machines) {
379            return Ok(selection);
380        }
381        without_room.push(spec.series);
382    }
383    select_instance_type(platform, requirements)
384}
385
386/// The series automatic selection may pick from, in catalog (preference) order.
387pub fn auto_select_series(platform: Platform) -> Vec<&'static str> {
388    let mut series: Vec<&'static str> = Vec::new();
389    for spec in CATALOG
390        .iter()
391        .filter(|spec| spec.auto_select && spec.platform == platform)
392    {
393        if !series.contains(&spec.series) {
394            series.push(spec.series);
395        }
396    }
397    series
398}
399
400fn select_instance_type_where(
401    platform: Platform,
402    requirements: &WorkloadRequirements,
403    allowed: MachineFilter,
404) -> Result<InstanceSelection, String> {
405    // An unset architecture accepts either one. Nested virtualization and GPU
406    // models can exist on only one architecture of a platform (AWS nested
407    // virtualization is x86_64 only), so try the platform default first and
408    // then the other architecture.
409    if requirements.architecture.is_none()
410        && (requirements.nested_virt || requirements.gpu.is_some())
411    {
412        if let Some(default) = default_architecture(platform) {
413            let other = match default {
414                Architecture::Arm64 => Architecture::X86_64,
415                Architecture::X86_64 => Architecture::Arm64,
416            };
417            let with_architecture = |architecture| WorkloadRequirements {
418                architecture: Some(architecture),
419                ..requirements.clone()
420            };
421            let selection = select_instance_type_for_architecture(
422                platform,
423                &with_architecture(default),
424                allowed,
425            );
426            if selection.is_ok() {
427                return selection;
428            }
429            // Report both reasons: the default architecture often lacks the
430            // feature entirely, while the other one says what to change.
431            return select_instance_type_for_architecture(
432                platform,
433                &with_architecture(other),
434                allowed,
435            )
436            .map_err(|other_error| {
437                let default_error = selection.err().unwrap_or_default();
438                format!("{default:?}: {default_error}; {other:?}: {other_error}")
439            });
440        }
441    }
442    select_instance_type_for_architecture(platform, requirements, allowed)
443}
444
445fn select_instance_type_for_architecture(
446    platform: Platform,
447    requirements: &WorkloadRequirements,
448    allowed: MachineFilter,
449) -> Result<InstanceSelection, String> {
450    let family = select_family(requirements);
451    let family = if requirements.nested_virt && family == InstanceFamily::Burstable {
452        InstanceFamily::GeneralPurpose
453    } else {
454        family
455    };
456    let selection = select_instance_type_in_family(platform, requirements, family, allowed);
457    if selection.is_err() && family == InstanceFamily::Burstable {
458        return select_instance_type_in_family(
459            platform,
460            requirements,
461            InstanceFamily::GeneralPurpose,
462            allowed,
463        );
464    }
465    selection
466}
467
468fn select_instance_type_in_family(
469    platform: Platform,
470    requirements: &WorkloadRequirements,
471    family: InstanceFamily,
472    allowed: MachineFilter,
473) -> Result<InstanceSelection, String> {
474    let architecture = requirements
475        .architecture
476        .or_else(|| default_architecture(platform))
477        .ok_or_else(|| format!("platform {platform} has no default compute architecture"))?;
478
479    let candidates: Vec<&InstanceTypeSpec> = CATALOG
480        .iter()
481        .filter(|spec| spec.auto_select && spec.platform == platform && spec.family == family)
482        .filter(|spec| allowed(spec))
483        .filter(|spec| {
484            if requirements.nested_virt {
485                spec.is_nested_virt_capable()
486            } else {
487                platform != Platform::Aws || !spec.is_nested_virt_capable()
488            }
489        })
490        .filter(|spec| spec.architecture == architecture)
491        .collect();
492
493    // A storage-heavy workload may have no fixed-local candidate for the
494    // requested architecture/nested-virtualization contract. That is exactly
495    // when we must consider a provider-backed disk on a general-purpose VM;
496    // rejecting here made the fallback below unreachable.
497    if candidates.is_empty() && family != InstanceFamily::StorageOptimized {
498        let family_has_other_architecture = CATALOG.iter().any(|spec| {
499            spec.auto_select
500                && spec.platform == platform
501                && spec.family == family
502                && if requirements.nested_virt {
503                    spec.is_nested_virt_capable()
504                } else {
505                    platform != Platform::Aws || !spec.is_nested_virt_capable()
506                }
507        });
508        if family_has_other_architecture {
509            return Err(format!(
510                "architecture {architecture:?} is unavailable for this workload on platform {platform}"
511            ));
512        }
513        return Err(if requirements.nested_virt {
514            format!(
515                "no nested-virt-capable {family:?} instance types in catalog for platform {platform}"
516            )
517        } else {
518            format!("no {family:?} instance types in catalog for platform {platform}")
519        });
520    }
521
522    // For GPU workloads, filter by GPU type
523    let candidates = if let Some(ref gpu) = requirements.gpu {
524        let filtered: Vec<&InstanceTypeSpec> = candidates
525            .into_iter()
526            .filter(|spec| {
527                spec.gpu.as_ref().map_or(false, |g| {
528                    g.gpu_type == gpu.gpu_type && g.count >= gpu.count
529                })
530            })
531            .collect();
532        if filtered.is_empty() {
533            return Err(format!(
534                "no instance type for GPU type '{}' x{} on platform {platform}",
535                gpu.gpu_type, gpu.count
536            ));
537        }
538        filtered
539    } else {
540        candidates
541    };
542
543    // For storage workloads, filter by ephemeral storage capacity
544    let candidates = if family == InstanceFamily::StorageOptimized {
545        let filtered: Vec<&InstanceTypeSpec> = candidates
546            .into_iter()
547            .filter(|spec| spec.ephemeral_storage_bytes >= requirements.max_ephemeral_storage_bytes)
548            .collect();
549        if filtered.is_empty() {
550            // Fixed-local NVMe is preferred for large requests, but provider
551            // disks on ordinary cloud machines remain configurable. Fall back
552            // when no fixed-local catalog entry can satisfy the request.
553            CATALOG
554                .iter()
555                .filter(|spec| {
556                    spec.auto_select
557                        && spec.platform == platform
558                        && spec.family == InstanceFamily::GeneralPurpose
559                        && allowed(spec)
560                        && spec.has_configurable_ephemeral_storage()
561                        && max_configurable_ephemeral_storage_bytes(platform)
562                            .is_some_and(|max| requirements.max_ephemeral_storage_bytes <= max)
563                })
564                .filter(|spec| {
565                    if requirements.nested_virt {
566                        spec.is_nested_virt_capable()
567                    } else {
568                        platform != Platform::Aws || !spec.is_nested_virt_capable()
569                    }
570                })
571                .filter(|spec| spec.architecture == architecture)
572                .collect()
573        } else {
574            filtered
575        }
576    } else {
577        candidates
578    };
579
580    if candidates.is_empty() {
581        return Err(format!(
582            "architecture {architecture:?} is unavailable for this workload on platform {platform}"
583        ));
584    }
585
586    // More machines cannot split one replica. Every candidate must fit its
587    // largest allocation after host reserve and workload headroom.
588    let candidates: Vec<_> = candidates
589        .into_iter()
590        .filter(|spec| {
591            allocatable_cpu(spec) >= requirements.max_cpu_per_container * WORKLOAD_HEADROOM_FACTOR
592                && allocatable_memory_bytes(spec) as f64
593                    >= requirements.max_memory_per_container as f64 * WORKLOAD_HEADROOM_FACTOR
594        })
595        .collect();
596    let smallest_replica_machine = candidates.iter().map(|spec| spec.vcpu).min()
597        .ok_or_else(|| format!("no {platform} machine can fit one replica with system reserve and workload headroom"))?;
598
599    // Apply the policy for the candidates we will actually select from. A
600    // storage-heavy request can fall back from fixed-local storage machines to
601    // general-purpose machines with provider-backed disks; those machines must
602    // retain the normal horizontal-scaling cap.
603    let effective_family = candidates[0].family;
604    let vcpu_cap = if effective_family == InstanceFamily::GpuCompute
605        || effective_family == InstanceFamily::StorageOptimized
606    {
607        u32::MAX
608    } else {
609        MAX_STANDARD_VCPU.max(smallest_replica_machine)
610    };
611
612    let desired_target_machines = desired_target_machines(requirements);
613    let target_cpu = requirements
614        .max_cpu_per_container
615        .max(requirements.total_cpu_at_desired / desired_target_machines as f64)
616        * WORKLOAD_HEADROOM_FACTOR;
617    let target_memory = (requirements.max_memory_per_container as f64)
618        .max(requirements.total_memory_bytes_at_desired as f64 / desired_target_machines as f64)
619        * WORKLOAD_HEADROOM_FACTOR;
620
621    // Find the smallest instance whose allocatable capacity meets the workload
622    // target after host reserve and workload headroom. Machine count already
623    // accounts for multiple replicas; requiring space for an arbitrary second
624    // copy here would size the same demand twice.
625    let selected = candidates
626        .iter()
627        .filter(|spec| {
628            spec.vcpu <= vcpu_cap
629                && allocatable_cpu(spec) >= target_cpu
630                && allocatable_memory_bytes(spec) as f64 >= target_memory
631        })
632        .min_by_key(|spec| spec.vcpu)
633        .or_else(|| {
634            // If nothing fits within the cap, pick the largest instance under the cap
635            // `max_by_key` keeps the last of equal machines; the earlier series wins ties.
636            candidates
637                .iter()
638                .rev()
639                .filter(|spec| spec.vcpu <= vcpu_cap)
640                .max_by_key(|spec| spec.vcpu)
641        })
642        .or_else(|| {
643            // Last resort: pick the smallest available instance (for GPU/storage)
644            candidates.iter().min_by_key(|spec| spec.vcpu)
645        })
646        .ok_or_else(|| format!("no instance types available for platform {platform}"))?;
647
648    // Calculate machine counts
649    let max_machines = compute_max_machines(requirements, selected);
650    let min_machines = compute_min_machines(requirements, selected, max_machines);
651
652    Ok(InstanceSelection {
653        instance_type: selected.name,
654        profile: selected.to_machine_profile_for_storage(requirements.max_ephemeral_storage_bytes),
655        min_machines,
656        max_machines,
657    })
658}
659
660/// Select instance family based on workload characteristics.
661///
662/// Uses GeneralPurpose for all standard workloads — widely available across
663/// regions and cost-effective. Only specialized workloads (GPU, large ephemeral
664/// storage) get specialized families. Very small workloads get burstable.
665pub fn select_family(requirements: &WorkloadRequirements) -> InstanceFamily {
666    // GPU workloads always get GPU instances
667    if requirements.gpu.is_some() {
668        return InstanceFamily::GpuCompute;
669    }
670
671    // Large ephemeral storage needs NVMe (storage-optimized)
672    if requirements.max_ephemeral_storage_bytes > STORAGE_OPTIMIZED_THRESHOLD {
673        return InstanceFamily::StorageOptimized;
674    }
675
676    // Very small workloads use burstable instances
677    if requirements.total_cpu_at_max < 2.0 {
678        return InstanceFamily::Burstable;
679    }
680
681    // All other workloads use GeneralPurpose — available everywhere, good pricing
682    InstanceFamily::GeneralPurpose
683}
684
685/// Calculate maximum machines needed to fit the workload with headroom.
686fn compute_max_machines(requirements: &WorkloadRequirements, instance: &InstanceTypeSpec) -> u32 {
687    let cpu_with_headroom = requirements.total_cpu_at_max * WORKLOAD_HEADROOM_FACTOR;
688    let cpu_machines = (cpu_with_headroom / allocatable_cpu(instance)).ceil() as u32;
689
690    let mem_with_headroom =
691        requirements.total_memory_bytes_at_max as f64 * WORKLOAD_HEADROOM_FACTOR;
692    let mem_machines =
693        (mem_with_headroom / allocatable_memory_bytes(instance) as f64).ceil() as u32;
694
695    // Take the larger of CPU-based and memory-based, clamped to cluster limit
696    cpu_machines
697        .max(mem_machines)
698        .max(1)
699        .min(MAX_MACHINES_PER_CLUSTER)
700}
701
702/// Calculate minimum machines for HA.
703fn compute_min_machines(
704    requirements: &WorkloadRequirements,
705    instance: &InstanceTypeSpec,
706    max_machines: u32,
707) -> u32 {
708    let cpu_with_headroom = requirements.total_cpu_at_desired * WORKLOAD_HEADROOM_FACTOR;
709    let cpu_machines = (cpu_with_headroom / allocatable_cpu(instance)).ceil() as u32;
710
711    let mem_with_headroom =
712        requirements.total_memory_bytes_at_desired as f64 * WORKLOAD_HEADROOM_FACTOR;
713    let mem_machines =
714        (mem_with_headroom / allocatable_memory_bytes(instance) as f64).ceil() as u32;
715
716    cpu_machines
717        .max(mem_machines)
718        .max(1)
719        .min(2)
720        .min(max_machines)
721}
722
723fn desired_target_machines(requirements: &WorkloadRequirements) -> u32 {
724    if requirements.total_cpu_at_desired >= 2.0
725        || requirements.total_memory_bytes_at_desired >= 4 * GI
726    {
727        2
728    } else {
729        1
730    }
731}
732
733pub(crate) fn allocatable_cpu(instance: &InstanceTypeSpec) -> f64 {
734    (instance.vcpu as f64 - SYSTEM_RESERVE_CPU).max(0.25)
735}
736
737pub(crate) fn allocatable_memory_bytes(instance: &InstanceTypeSpec) -> u64 {
738    instance
739        .memory_bytes
740        .saturating_sub(system_reserve_memory_bytes(instance.memory_bytes))
741        .max(256 * MI)
742}
743
744fn system_reserve_memory_bytes(memory_bytes: u64) -> u64 {
745    if memory_bytes < 4 * GI {
746        256 * MI
747    } else if memory_bytes < 16 * GI {
748        512 * MI
749    } else {
750        GI
751    }
752}
753
754// ---------------------------------------------------------------------------
755// Tests
756// ---------------------------------------------------------------------------
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761    use crate::BinaryTarget;
762
763    // -- Parsing tests --
764
765    #[test]
766    fn test_parse_cpu_plain() {
767        assert_eq!(parse_cpu("1").unwrap(), 1.0);
768        assert_eq!(parse_cpu("0.5").unwrap(), 0.5);
769        assert_eq!(parse_cpu("2.0").unwrap(), 2.0);
770        assert_eq!(parse_cpu("16").unwrap(), 16.0);
771    }
772
773    #[test]
774    fn test_parse_cpu_millicore() {
775        assert_eq!(parse_cpu("500m").unwrap(), 0.5);
776        assert_eq!(parse_cpu("250m").unwrap(), 0.25);
777        assert_eq!(parse_cpu("1000m").unwrap(), 1.0);
778        assert_eq!(parse_cpu("100m").unwrap(), 0.1);
779    }
780
781    #[test]
782    fn test_parse_cpu_invalid() {
783        assert!(parse_cpu("").is_err());
784        assert!(parse_cpu("abc").is_err());
785        assert!(parse_cpu("m").is_err());
786    }
787
788    #[test]
789    fn test_parse_memory_binary_suffixes() {
790        assert_eq!(parse_memory_bytes("1Ki").unwrap(), 1024);
791        assert_eq!(parse_memory_bytes("1Mi").unwrap(), 1024 * 1024);
792        assert_eq!(parse_memory_bytes("1Gi").unwrap(), 1024 * 1024 * 1024);
793        assert_eq!(parse_memory_bytes("4Gi").unwrap(), 4 * 1024 * 1024 * 1024);
794        assert_eq!(parse_memory_bytes("512Mi").unwrap(), 512 * 1024 * 1024);
795        assert_eq!(
796            parse_memory_bytes("1Ti").unwrap(),
797            1024u64 * 1024 * 1024 * 1024
798        );
799    }
800
801    #[test]
802    fn test_parse_memory_decimal_suffixes() {
803        assert_eq!(parse_memory_bytes("1k").unwrap(), 1000);
804        assert_eq!(parse_memory_bytes("1M").unwrap(), 1_000_000);
805        assert_eq!(parse_memory_bytes("1G").unwrap(), 1_000_000_000);
806        assert_eq!(parse_memory_bytes("1T").unwrap(), 1_000_000_000_000);
807    }
808
809    #[test]
810    fn test_parse_memory_plain_bytes() {
811        assert_eq!(parse_memory_bytes("1024").unwrap(), 1024);
812        assert_eq!(parse_memory_bytes("0").unwrap(), 0);
813    }
814
815    #[test]
816    fn test_parse_memory_invalid() {
817        assert!(parse_memory_bytes("").is_err());
818        assert!(parse_memory_bytes("abc").is_err());
819        assert!(parse_memory_bytes("Gi").is_err());
820    }
821
822    #[test]
823    fn test_parse_memory_fractional() {
824        assert_eq!(parse_memory_bytes("0.5Gi").unwrap(), GI / 2);
825        assert_eq!(parse_memory_bytes("1.5Gi").unwrap(), GI + GI / 2);
826    }
827
828    // -- Catalog lookup tests --
829
830    #[test]
831    fn test_catalog_has_entries_for_all_cloud_platforms() {
832        assert!(!catalog_for_platform(Platform::Aws).is_empty());
833        assert!(!catalog_for_platform(Platform::Gcp).is_empty());
834        assert!(!catalog_for_platform(Platform::Azure).is_empty());
835    }
836
837    #[test]
838    fn test_catalog_no_entries_for_non_cloud_platforms() {
839        assert!(catalog_for_platform(Platform::Local).is_empty());
840        assert!(catalog_for_platform(Platform::Kubernetes).is_empty());
841    }
842
843    #[test]
844    fn test_find_known_instance_type() {
845        let spec =
846            find_instance_type(Platform::Aws, "m7g.2xlarge").expect("should find m7g.2xlarge");
847        assert_eq!(spec.vcpu, 8);
848        assert_eq!(spec.memory_bytes, 32 * GI);
849        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
850    }
851
852    #[test]
853    fn test_find_aws_c8i_nested_virt_instance_type() {
854        let spec = find_instance_type(Platform::Aws, "c8i.large").expect("should find c8i.large");
855        assert_eq!(spec.vcpu, 2);
856        assert_eq!(spec.memory_bytes, 4 * GI);
857        assert_eq!(spec.family, InstanceFamily::ComputeOptimized);
858        assert_eq!(spec.architecture, Architecture::X86_64);
859        assert!(spec.is_nested_virt_capable());
860    }
861
862    #[test]
863    fn test_find_unknown_instance_type() {
864        assert!(find_instance_type(Platform::Aws, "nonexistent.xlarge").is_none());
865    }
866
867    #[test]
868    fn test_find_wrong_platform() {
869        assert!(find_instance_type(Platform::Gcp, "m7g.2xlarge").is_none());
870    }
871
872    #[test]
873    fn test_to_machine_profile() {
874        let spec = find_instance_type(Platform::Aws, "m7g.2xlarge").unwrap();
875        let profile = spec.to_machine_profile();
876        assert_eq!(profile.cpu, "8.0");
877        assert_eq!(profile.memory_bytes, 32 * GI);
878        assert_eq!(profile.ephemeral_storage_bytes, 20 * GI);
879        assert!(profile.gpu.is_none());
880    }
881
882    #[test]
883    fn test_to_machine_profile_with_gpu() {
884        let spec = find_instance_type(Platform::Aws, "p4d.24xlarge").unwrap();
885        let profile = spec.to_machine_profile();
886        let gpu = profile.gpu.as_ref().expect("should have GPU");
887        assert_eq!(gpu.gpu_type, "nvidia-a100");
888        assert_eq!(gpu.count, 8);
889    }
890
891    // -- Selection algorithm tests --
892
893    #[test]
894    fn small_cpu_with_large_memory_falls_back_from_burstable() {
895        let requirements = WorkloadRequirements {
896            total_cpu_at_desired: 0.5,
897            total_memory_bytes_at_desired: 8 * GI,
898            total_cpu_at_max: 0.5,
899            total_memory_bytes_at_max: 8 * GI,
900            max_cpu_per_container: 0.5,
901            max_memory_per_container: 8 * GI,
902            max_ephemeral_storage_bytes: 0,
903            gpu: None,
904            architecture: Some(Architecture::X86_64),
905            nested_virt: false,
906        };
907        let selected = select_instance_type(Platform::Gcp, &requirements).unwrap();
908        let machine = find_instance_type(Platform::Gcp, selected.instance_type).unwrap();
909        assert!(
910            allocatable_memory_bytes(machine) as f64 >= 8.0 * GI as f64 * WORKLOAD_HEADROOM_FACTOR
911        );
912    }
913
914    #[test]
915    fn test_select_burstable_for_small_workload() {
916        let req = WorkloadRequirements {
917            total_cpu_at_desired: 1.0,
918            total_memory_bytes_at_desired: 2 * GI,
919            total_cpu_at_max: 1.0,
920            total_memory_bytes_at_max: 2 * GI,
921            max_cpu_per_container: 0.5,
922            max_memory_per_container: 1 * GI,
923            max_ephemeral_storage_bytes: 10 * GI,
924            gpu: None,
925            architecture: None,
926            nested_virt: false,
927        };
928        let sel = select_instance_type(Platform::Aws, &req).unwrap();
929        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
930        assert_eq!(spec.family, InstanceFamily::Burstable);
931    }
932
933    #[test]
934    fn test_selects_smallest_burstable_machine_with_real_headroom() {
935        let req = WorkloadRequirements {
936            total_cpu_at_desired: 1.0,
937            total_memory_bytes_at_desired: 2 * GI,
938            total_cpu_at_max: 1.0,
939            total_memory_bytes_at_max: 2 * GI,
940            max_cpu_per_container: 1.0,
941            max_memory_per_container: 2 * GI,
942            max_ephemeral_storage_bytes: 10 * GI,
943            gpu: None,
944            architecture: None,
945            nested_virt: false,
946        };
947
948        let selection = select_instance_type(Platform::Aws, &req).unwrap();
949
950        assert_eq!(selection.instance_type, "t4g.medium");
951        assert_eq!(selection.min_machines, 1);
952        assert_eq!(selection.max_machines, 1);
953    }
954
955    #[test]
956    fn test_select_general_purpose_for_standard_workload() {
957        // Standard workloads always get GeneralPurpose regardless of CPU:memory ratio
958        let req = WorkloadRequirements {
959            total_cpu_at_desired: 20.0,
960            total_memory_bytes_at_desired: 80 * GI,
961            total_cpu_at_max: 20.0,
962            total_memory_bytes_at_max: 80 * GI,
963            max_cpu_per_container: 2.0,
964            max_memory_per_container: 8 * GI,
965            max_ephemeral_storage_bytes: 10 * GI,
966            gpu: None,
967            architecture: None,
968            nested_virt: false,
969        };
970        let sel = select_instance_type(Platform::Aws, &req).unwrap();
971        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
972        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
973    }
974
975    #[test]
976    fn test_select_general_purpose_even_for_cpu_heavy() {
977        // CPU-heavy workloads still get GeneralPurpose (no more ComputeOptimized auto-select)
978        let req = WorkloadRequirements {
979            total_cpu_at_desired: 20.0,
980            total_memory_bytes_at_desired: 20 * GI,
981            total_cpu_at_max: 20.0,
982            total_memory_bytes_at_max: 20 * GI,
983            max_cpu_per_container: 2.0,
984            max_memory_per_container: 2 * GI,
985            max_ephemeral_storage_bytes: 10 * GI,
986            gpu: None,
987            architecture: None,
988            nested_virt: false,
989        };
990        let sel = select_instance_type(Platform::Aws, &req).unwrap();
991        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
992        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
993    }
994
995    #[test]
996    fn test_select_storage_optimized_for_large_ephemeral() {
997        let req = WorkloadRequirements {
998            total_cpu_at_desired: 8.0,
999            total_memory_bytes_at_desired: 32 * GI,
1000            total_cpu_at_max: 8.0,
1001            total_memory_bytes_at_max: 32 * GI,
1002            max_cpu_per_container: 2.0,
1003            max_memory_per_container: 8 * GI,
1004            max_ephemeral_storage_bytes: 500 * GI,
1005            gpu: None,
1006            architecture: Some(Architecture::X86_64),
1007            nested_virt: false,
1008        };
1009        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1010        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1011        assert_eq!(spec.family, InstanceFamily::StorageOptimized);
1012    }
1013
1014    #[test]
1015    fn test_select_configurable_storage_above_fixed_local_catalog() {
1016        let req = WorkloadRequirements {
1017            total_cpu_at_desired: 8.0,
1018            total_memory_bytes_at_desired: 32 * GI,
1019            total_cpu_at_max: 8.0,
1020            total_memory_bytes_at_max: 32 * GI,
1021            max_cpu_per_container: 2.0,
1022            max_memory_per_container: 8 * GI,
1023            max_ephemeral_storage_bytes: 8_000 * GI,
1024            gpu: None,
1025            architecture: Some(Architecture::X86_64),
1026            nested_virt: false,
1027        };
1028        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1029        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1030        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
1031        assert_eq!(sel.profile.ephemeral_storage_bytes, 8_000 * GI);
1032    }
1033
1034    #[test]
1035    fn test_configurable_storage_fallback_retains_standard_vcpu_cap() {
1036        let req = WorkloadRequirements {
1037            total_cpu_at_desired: 70.0,
1038            total_memory_bytes_at_desired: 140 * GI,
1039            total_cpu_at_max: 70.0,
1040            total_memory_bytes_at_max: 140 * GI,
1041            max_cpu_per_container: 2.0,
1042            max_memory_per_container: 4 * GI,
1043            max_ephemeral_storage_bytes: 8_000 * GI,
1044            gpu: None,
1045            architecture: Some(Architecture::X86_64),
1046            nested_virt: false,
1047        };
1048
1049        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1050        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1051        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
1052        assert!(spec.vcpu <= MAX_STANDARD_VCPU);
1053        assert!(sel.max_machines > 1);
1054    }
1055
1056    #[test]
1057    fn test_nested_virtualization_storage_falls_back_to_configurable_disk() {
1058        for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1059            let req = WorkloadRequirements {
1060                total_cpu_at_desired: 2.0,
1061                total_memory_bytes_at_desired: 8 * GI,
1062                total_cpu_at_max: 2.0,
1063                total_memory_bytes_at_max: 8 * GI,
1064                max_cpu_per_container: 2.0,
1065                max_memory_per_container: 8 * GI,
1066                max_ephemeral_storage_bytes: 500 * GI,
1067                gpu: None,
1068                architecture: Some(Architecture::X86_64),
1069                nested_virt: true,
1070            };
1071
1072            let sel = select_instance_type(platform, &req)
1073                .unwrap_or_else(|error| panic!("{platform} should support fallback: {error}"));
1074            let spec = find_instance_type(platform, sel.instance_type).unwrap();
1075            assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
1076            assert!(spec.is_nested_virt_capable());
1077            assert_eq!(sel.profile.ephemeral_storage_bytes, 500 * GI);
1078        }
1079    }
1080
1081    #[test]
1082    fn unset_architecture_resolves_to_the_one_offering_nested_virtualization() {
1083        let req = WorkloadRequirements {
1084            total_cpu_at_desired: 2.0,
1085            total_memory_bytes_at_desired: 4 * GI,
1086            total_cpu_at_max: 2.0,
1087            total_memory_bytes_at_max: 4 * GI,
1088            max_cpu_per_container: 2.0,
1089            max_memory_per_container: 4 * GI,
1090            max_ephemeral_storage_bytes: 20 * GI,
1091            gpu: None,
1092            architecture: None,
1093            nested_virt: true,
1094        };
1095
1096        for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1097            let selection = select_instance_type(platform, &req)
1098                .unwrap_or_else(|message| panic!("{platform}: {message}"));
1099            let spec = find_instance_type(platform, selection.instance_type)
1100                .expect("selected machine should exist in the catalog");
1101            assert!(spec.is_nested_virt_capable(), "{platform}: {}", spec.name);
1102            assert_eq!(spec.architecture, Architecture::X86_64, "{platform}");
1103            assert_eq!(selection.profile.architecture, Some(Architecture::X86_64));
1104        }
1105
1106        // When neither architecture fits, the error says why for each, so a
1107        // sizing problem is not reported as a missing architecture.
1108        let oversized = WorkloadRequirements {
1109            max_cpu_per_container: 1000.0,
1110            total_cpu_at_desired: 1000.0,
1111            total_cpu_at_max: 1000.0,
1112            ..req.clone()
1113        };
1114        let message = select_instance_type(Platform::Aws, &oversized)
1115            .expect_err("no AWS machine fits 1000 vCPU per replica");
1116        assert!(
1117            message.starts_with("Arm64: architecture Arm64 is unavailable"),
1118            "{message}"
1119        );
1120        assert!(
1121            message.contains("; X86_64: no aws machine can fit one replica"),
1122            "{message}"
1123        );
1124
1125        // An explicit architecture is a constraint, not a preference.
1126        let arm = WorkloadRequirements {
1127            architecture: Some(Architecture::Arm64),
1128            ..req
1129        };
1130        assert!(select_instance_type(Platform::Aws, &arm).is_err());
1131    }
1132
1133    #[test]
1134    fn test_configurable_disk_rejects_capacity_above_provider_limit() {
1135        for (platform, requested) in [
1136            (Platform::Aws, 100 * TI),
1137            (Platform::Gcp, 100 * TI),
1138            (Platform::Azure, 8_000 * GI),
1139        ] {
1140            let req = WorkloadRequirements {
1141                total_cpu_at_desired: 2.0,
1142                total_memory_bytes_at_desired: 8 * GI,
1143                total_cpu_at_max: 2.0,
1144                total_memory_bytes_at_max: 8 * GI,
1145                max_cpu_per_container: 2.0,
1146                max_memory_per_container: 8 * GI,
1147                max_ephemeral_storage_bytes: requested,
1148                gpu: None,
1149                architecture: Some(Architecture::X86_64),
1150                nested_virt: true,
1151            };
1152
1153            assert!(select_instance_type(platform, &req).is_err());
1154        }
1155    }
1156
1157    #[test]
1158    fn test_configurable_disk_limits_account_for_controller_rounding() {
1159        for (platform, disk_limit_gib) in [
1160            (Platform::Aws, 64 * 1024),
1161            (Platform::Gcp, 64 * 1024),
1162            (Platform::Azure, 4_095),
1163        ] {
1164            let max = max_configurable_ephemeral_storage_bytes(platform).unwrap();
1165            let materialized_disk_gib = |requested_bytes: u64| {
1166                let requested_gib = requested_bytes.div_ceil(GI);
1167                (requested_gib * 5).div_ceil(4) + 12
1168            };
1169
1170            assert!(materialized_disk_gib(max) <= disk_limit_gib);
1171            assert!(materialized_disk_gib(max + 1) > disk_limit_gib);
1172        }
1173    }
1174
1175    #[test]
1176    fn test_gpu_local_storage_is_not_treated_as_resizable() {
1177        let spec = find_instance_type(Platform::Aws, "g5.xlarge").unwrap();
1178        assert_eq!(spec.family, InstanceFamily::GpuCompute);
1179        assert!(!spec.has_configurable_ephemeral_storage());
1180    }
1181
1182    #[test]
1183    fn test_select_gpu_instance() {
1184        let req = WorkloadRequirements {
1185            total_cpu_at_desired: 8.0,
1186            total_memory_bytes_at_desired: 32 * GI,
1187            total_cpu_at_max: 8.0,
1188            total_memory_bytes_at_max: 32 * GI,
1189            max_cpu_per_container: 4.0,
1190            max_memory_per_container: 16 * GI,
1191            max_ephemeral_storage_bytes: 10 * GI,
1192            gpu: Some(GpuSpec {
1193                gpu_type: "nvidia-a100".to_string(),
1194                count: 1,
1195            }),
1196            architecture: Some(Architecture::X86_64),
1197            nested_virt: false,
1198        };
1199        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1200        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1201        assert_eq!(spec.family, InstanceFamily::GpuCompute);
1202        assert!(spec.gpu.is_some());
1203    }
1204
1205    #[test]
1206    fn test_select_uses_each_cloud_image_target_architecture() {
1207        let req = WorkloadRequirements {
1208            total_cpu_at_desired: 4.0,
1209            total_memory_bytes_at_desired: 16 * GI,
1210            total_cpu_at_max: 4.0,
1211            total_memory_bytes_at_max: 16 * GI,
1212            max_cpu_per_container: 1.0,
1213            max_memory_per_container: 4 * GI,
1214            max_ephemeral_storage_bytes: 10 * GI,
1215            gpu: None,
1216            architecture: None,
1217            nested_virt: false,
1218        };
1219        for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1220            let sel = select_instance_type(platform, &req)
1221                .unwrap_or_else(|error| panic!("selection failed for {platform}: {error}"));
1222            let spec = find_instance_type(platform, sel.instance_type)
1223                .expect("selected machine should exist in the catalog");
1224            assert_eq!(
1225                Some(spec.architecture),
1226                default_architecture(platform),
1227                "machine architecture must match the image target for {platform}"
1228            );
1229        }
1230    }
1231
1232    #[test]
1233    fn test_machine_count_reasonable() {
1234        // Single container: 1 CPU, 2Gi, maxReplicas=20
1235        let req = WorkloadRequirements {
1236            total_cpu_at_desired: 20.0,
1237            total_memory_bytes_at_desired: 40 * GI,
1238            total_cpu_at_max: 20.0,
1239            total_memory_bytes_at_max: 40 * GI,
1240            max_cpu_per_container: 1.0,
1241            max_memory_per_container: 2 * GI,
1242            max_ephemeral_storage_bytes: 10 * GI,
1243            gpu: None,
1244            architecture: None,
1245            nested_virt: false,
1246        };
1247        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1248        assert!(sel.min_machines >= 1);
1249        assert!(sel.max_machines <= MAX_MACHINES_PER_CLUSTER);
1250        assert!(sel.max_machines >= sel.min_machines);
1251    }
1252
1253    #[test]
1254    fn test_instance_size_capped_at_8_vcpu() {
1255        // Many small replicas prefer more machines over larger instances.
1256        let req = WorkloadRequirements {
1257            total_cpu_at_desired: 70.0,
1258            total_memory_bytes_at_desired: 140 * GI,
1259            total_cpu_at_max: 70.0,
1260            total_memory_bytes_at_max: 140 * GI,
1261            max_cpu_per_container: 2.0,
1262            max_memory_per_container: 4 * GI,
1263            max_ephemeral_storage_bytes: 10 * GI,
1264            gpu: None,
1265            architecture: None,
1266            nested_virt: false,
1267        };
1268        let sel = select_instance_type(Platform::Gcp, &req).unwrap();
1269        let spec = find_instance_type(Platform::Gcp, sel.instance_type).unwrap();
1270        assert!(
1271            spec.vcpu <= MAX_STANDARD_VCPU,
1272            "selected {} with {} vCPUs, expected <= {}",
1273            spec.name,
1274            spec.vcpu,
1275            MAX_STANDARD_VCPU
1276        );
1277        assert_eq!(spec.family, InstanceFamily::GeneralPurpose);
1278        // Should scale horizontally instead
1279        assert!(sel.max_machines > 1);
1280    }
1281
1282    #[test]
1283    fn test_larger_autoscaled_workload_gets_reasonable_instance() {
1284        // Simulates a larger autoscaled workload: 4 containers, each 2 CPU / 4 GiB
1285        // maxReplicas: 10, 10, 10, 5
1286        let req = WorkloadRequirements {
1287            total_cpu_at_desired: 70.0,
1288            total_memory_bytes_at_desired: 140 * GI,
1289            total_cpu_at_max: 70.0,              // 2*10 + 2*10 + 2*10 + 2*5
1290            total_memory_bytes_at_max: 140 * GI, // 4*10 + 4*10 + 4*10 + 4*5
1291            max_cpu_per_container: 2.0,
1292            max_memory_per_container: 4 * GI,
1293            max_ephemeral_storage_bytes: 20 * GI,
1294            gpu: None,
1295            architecture: None,
1296            nested_virt: false,
1297        };
1298        let sel = select_instance_type(Platform::Gcp, &req).unwrap();
1299        // Should pick n2-standard-8 (8 vCPU, 32 GiB) — NOT c3-standard-44
1300        assert_eq!(sel.instance_type, "n2-standard-8");
1301        assert!(sel.max_machines >= 2);
1302    }
1303
1304    /// When `nested_virt` is set on the workload, the selector must
1305    /// restrict to nested-virt-capable families. On AWS that means an m8i
1306    /// (or other 8th-gen Intel) entry, never a Graviton (`*7g`, `t4g`) or
1307    /// burstable. Without this filter the launch template gets created
1308    /// with `CpuOptions.NestedVirtualization=enabled` paired with an
1309    /// instance type AWS rejects at RunInstances.
1310    #[test]
1311    fn test_select_aws_picks_m8i_when_nested_virt_required() {
1312        let req = WorkloadRequirements {
1313            total_cpu_at_desired: 4.0,
1314            total_memory_bytes_at_desired: 8 * GI,
1315            total_cpu_at_max: 4.0,
1316            total_memory_bytes_at_max: 8 * GI,
1317            max_cpu_per_container: 4.0,
1318            max_memory_per_container: 8 * GI,
1319            max_ephemeral_storage_bytes: 10 * GI,
1320            gpu: None,
1321            architecture: Some(Architecture::X86_64),
1322            nested_virt: true,
1323        };
1324        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1325        assert!(
1326            sel.instance_type.starts_with("m8i.")
1327                || sel.instance_type.starts_with("c8i.")
1328                || sel.instance_type.starts_with("r8i."),
1329            "expected an m8i/c8i/r8i instance, got {}",
1330            sel.instance_type
1331        );
1332        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1333        assert!(spec.is_nested_virt_capable());
1334    }
1335
1336    #[test]
1337    fn test_select_gcp_picks_n2_when_nested_virt_required() {
1338        let req = WorkloadRequirements {
1339            total_cpu_at_desired: 4.0,
1340            total_memory_bytes_at_desired: 8 * GI,
1341            total_cpu_at_max: 4.0,
1342            total_memory_bytes_at_max: 8 * GI,
1343            max_cpu_per_container: 4.0,
1344            max_memory_per_container: 8 * GI,
1345            max_ephemeral_storage_bytes: 0,
1346            architecture: Some(Architecture::X86_64),
1347            gpu: None,
1348            nested_virt: true,
1349        };
1350
1351        let selection = select_instance_type(Platform::Gcp, &req).unwrap();
1352        assert_eq!(selection.instance_type, "n2-standard-8");
1353        assert!(find_instance_type(Platform::Gcp, selection.instance_type)
1354            .unwrap()
1355            .is_nested_virt_capable());
1356    }
1357
1358    #[test]
1359    fn test_select_azure_picks_dsv5_when_nested_virt_required() {
1360        let req = WorkloadRequirements {
1361            total_cpu_at_desired: 4.0,
1362            total_memory_bytes_at_desired: 8 * GI,
1363            total_cpu_at_max: 4.0,
1364            total_memory_bytes_at_max: 8 * GI,
1365            max_cpu_per_container: 4.0,
1366            max_memory_per_container: 8 * GI,
1367            max_ephemeral_storage_bytes: 0,
1368            architecture: Some(Architecture::X86_64),
1369            gpu: None,
1370            nested_virt: true,
1371        };
1372
1373        let selection = select_instance_type(Platform::Azure, &req).unwrap();
1374        assert_eq!(selection.instance_type, "Standard_D8s_v5");
1375        assert!(find_instance_type(Platform::Azure, selection.instance_type)
1376            .unwrap()
1377            .is_nested_virt_capable());
1378    }
1379
1380    #[test]
1381    fn test_select_aws_defaults_to_image_target_architecture() {
1382        let req = WorkloadRequirements {
1383            total_cpu_at_desired: 4.0,
1384            total_memory_bytes_at_desired: 8 * GI,
1385            total_cpu_at_max: 4.0,
1386            total_memory_bytes_at_max: 8 * GI,
1387            max_cpu_per_container: 4.0,
1388            max_memory_per_container: 8 * GI,
1389            max_ephemeral_storage_bytes: 10 * GI,
1390            gpu: None,
1391            architecture: None,
1392            nested_virt: false,
1393        };
1394        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1395        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1396        assert_eq!(spec.architecture, Architecture::Arm64);
1397    }
1398
1399    #[test]
1400    fn test_cloud_defaults_match_image_target_architectures() {
1401        for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1402            let target = BinaryTarget::defaults_for_platform(platform)
1403                .into_iter()
1404                .next()
1405                .expect("managed cloud should have a default image target");
1406            let image_architecture = match target.oci_arch() {
1407                "arm64" => Architecture::Arm64,
1408                "amd64" => Architecture::X86_64,
1409                architecture => {
1410                    panic!("unsupported managed-cloud image architecture {architecture}")
1411                }
1412            };
1413
1414            assert_eq!(default_architecture(platform), Some(image_architecture));
1415        }
1416    }
1417
1418    /// ARM remains available when the workload or capacity profile declares it.
1419    #[test]
1420    fn test_select_aws_uses_graviton_for_explicit_arm64() {
1421        let req = WorkloadRequirements {
1422            total_cpu_at_desired: 4.0,
1423            total_memory_bytes_at_desired: 8 * GI,
1424            total_cpu_at_max: 4.0,
1425            total_memory_bytes_at_max: 8 * GI,
1426            max_cpu_per_container: 4.0,
1427            max_memory_per_container: 8 * GI,
1428            max_ephemeral_storage_bytes: 10 * GI,
1429            gpu: None,
1430            architecture: Some(Architecture::Arm64),
1431            nested_virt: false,
1432        };
1433        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1434        let spec = find_instance_type(Platform::Aws, sel.instance_type).unwrap();
1435        assert_eq!(spec.architecture, Architecture::Arm64);
1436    }
1437
1438    #[test]
1439    fn test_select_rejects_explicit_architecture_missing_from_cloud_catalog() {
1440        let req = WorkloadRequirements {
1441            total_cpu_at_desired: 1.0,
1442            total_memory_bytes_at_desired: 2 * GI,
1443            total_cpu_at_max: 1.0,
1444            total_memory_bytes_at_max: 2 * GI,
1445            max_cpu_per_container: 1.0,
1446            max_memory_per_container: 2 * GI,
1447            max_ephemeral_storage_bytes: 10 * GI,
1448            gpu: None,
1449            architecture: Some(Architecture::Arm64),
1450            nested_virt: false,
1451        };
1452
1453        let error = select_instance_type(Platform::Gcp, &req)
1454            .expect_err("GCP catalog has no ARM64 machine");
1455
1456        assert!(error.contains("architecture Arm64 is unavailable"));
1457    }
1458
1459    #[test]
1460    fn test_profile_has_required_fields() {
1461        let req = WorkloadRequirements {
1462            total_cpu_at_desired: 4.0,
1463            total_memory_bytes_at_desired: 16 * GI,
1464            total_cpu_at_max: 4.0,
1465            total_memory_bytes_at_max: 16 * GI,
1466            max_cpu_per_container: 1.0,
1467            max_memory_per_container: 4 * GI,
1468            max_ephemeral_storage_bytes: 10 * GI,
1469            gpu: None,
1470            architecture: None,
1471            nested_virt: false,
1472        };
1473        let sel = select_instance_type(Platform::Aws, &req).unwrap();
1474        assert!(!sel.profile.cpu.is_empty());
1475        assert!(sel.profile.memory_bytes > 0);
1476        assert!(sel.profile.ephemeral_storage_bytes > 0);
1477    }
1478
1479    #[test]
1480    fn test_error_for_unsupported_gpu_type() {
1481        let req = WorkloadRequirements {
1482            total_cpu_at_desired: 8.0,
1483            total_memory_bytes_at_desired: 32 * GI,
1484            total_cpu_at_max: 8.0,
1485            total_memory_bytes_at_max: 32 * GI,
1486            max_cpu_per_container: 4.0,
1487            max_memory_per_container: 16 * GI,
1488            max_ephemeral_storage_bytes: 10 * GI,
1489            gpu: Some(GpuSpec {
1490                gpu_type: "amd-mi300".to_string(),
1491                count: 1,
1492            }),
1493            architecture: None,
1494            nested_virt: false,
1495        };
1496        let result = select_instance_type(Platform::Aws, &req);
1497        assert!(result.is_err());
1498    }
1499
1500    /// Workload shapes for the auto-selection matrix: name, CPU and memory per replica,
1501    /// desired and max replicas, ephemeral storage, GPU type and count.
1502    type SelectionShape = (
1503        &'static str,
1504        f64,
1505        u64,
1506        u32,
1507        u32,
1508        u64,
1509        Option<(&'static str, u32)>,
1510    );
1511
1512    #[rustfmt::skip]
1513    const SELECTION_SHAPES: &[SelectionShape] = &[
1514        ("tiny", 0.25, 512 * MI, 1, 1, 0, None),
1515        ("burstable", 1.0, 2 * GI, 1, 1, 10 * GI, None),
1516        ("burstable-big-memory", 0.5, 8 * GI, 1, 1, 0, None),
1517        ("small", 1.0, 2 * GI, 2, 4, 10 * GI, None),
1518        ("medium", 4.0, 8 * GI, 1, 1, 10 * GI, None),
1519        ("general", 2.0, 8 * GI, 4, 10, 20 * GI, None),
1520        ("many-replicas", 2.0, 4 * GI, 35, 35, 20 * GI, None),
1521        ("large-replica", 12.0, 48 * GI, 1, 2, 20 * GI, None),
1522        ("huge-replica", 60.0, 240 * GI, 1, 1, 20 * GI, None),
1523        ("memory-heavy", 4.0, 60 * GI, 2, 4, 20 * GI, None),
1524        ("storage-300g", 2.0, 8 * GI, 2, 2, 300 * GI, None),
1525        ("storage-1t", 4.0, 16 * GI, 2, 4, 1000 * GI, None),
1526        ("storage-2t", 4.0, 16 * GI, 2, 4, 2000 * GI, None),
1527        ("storage-8t", 2.0, 8 * GI, 2, 2, 8000 * GI, None),
1528        ("storage-100t", 2.0, 8 * GI, 1, 1, 100 * TI, None),
1529        ("gpu-t4", 2.0, 8 * GI, 1, 1, 10 * GI, Some(("nvidia-t4", 1))),
1530        ("gpu-a10g", 2.0, 8 * GI, 1, 1, 10 * GI, Some(("nvidia-a10g", 1))),
1531        ("gpu-a100", 4.0, 16 * GI, 1, 1, 10 * GI, Some(("nvidia-a100", 1))),
1532        ("gpu-a100x8", 16.0, 128 * GI, 1, 1, 10 * GI, Some(("nvidia-a100", 8))),
1533        ("gpu-h100x8", 16.0, 128 * GI, 1, 1, 10 * GI, Some(("nvidia-h100", 8))),
1534    ];
1535
1536    /// One line per case: what `select_instance_type` picks for every platform, architecture,
1537    /// nested-virtualization setting and workload shape above.
1538    fn render_selection_matrix() -> String {
1539        let mut table = String::new();
1540        for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1541            for architecture in [None, Some(Architecture::Arm64), Some(Architecture::X86_64)] {
1542                for nested_virt in [false, true] {
1543                    for &(shape, cpu, memory, desired, max, storage, gpu) in SELECTION_SHAPES {
1544                        let requirements = WorkloadRequirements {
1545                            total_cpu_at_desired: cpu * desired as f64,
1546                            total_memory_bytes_at_desired: memory * desired as u64,
1547                            total_cpu_at_max: cpu * max as f64,
1548                            total_memory_bytes_at_max: memory * max as u64,
1549                            max_cpu_per_container: cpu,
1550                            max_memory_per_container: memory,
1551                            max_ephemeral_storage_bytes: storage,
1552                            gpu: gpu.map(|(gpu_type, count)| GpuSpec {
1553                                gpu_type: gpu_type.to_string(),
1554                                count,
1555                            }),
1556                            architecture,
1557                            nested_virt,
1558                        };
1559                        let pick = match select_instance_type(platform, &requirements) {
1560                            Ok(selection) => format!(
1561                                "{} min={} max={} memory={} storage={}",
1562                                selection.instance_type,
1563                                selection.min_machines,
1564                                selection.max_machines,
1565                                selection.profile.memory_bytes,
1566                                selection.profile.ephemeral_storage_bytes
1567                            ),
1568                            Err(error) => format!("error: {error}"),
1569                        };
1570                        let architecture = architecture
1571                            .map_or("default".to_string(), |architecture| {
1572                                format!("{architecture:?}")
1573                            });
1574                        table.push_str(&format!(
1575                            "{platform} {architecture} nested={nested_virt} {shape} -> {pick}\n"
1576                        ));
1577                    }
1578                }
1579            }
1580        }
1581        table
1582    }
1583
1584    /// Matrix cases whose pick differs from the baseline on purpose, with the pick they get.
1585    /// AWS reports an NVIDIA A10G on g5, so a T4 request has no AWS machine and an A10G
1586    /// request gets g5.
1587    #[rustfmt::skip]
1588    const ACCEPTED_PICK_CHANGES: &[(&str, &str)] = &[
1589        (
1590            "aws default nested=false gpu-t4",
1591            "error: Arm64: architecture Arm64 is unavailable for this workload on platform aws; \
1592             X86_64: no instance type for GPU type 'nvidia-t4' x1 on platform aws",
1593        ),
1594        (
1595            "aws default nested=false gpu-a10g",
1596            "g5.xlarge min=1 max=1 memory=17179869184 storage=268435456000",
1597        ),
1598        (
1599            "aws X86_64 nested=false gpu-t4",
1600            "error: no instance type for GPU type 'nvidia-t4' x1 on platform aws",
1601        ),
1602        (
1603            "aws X86_64 nested=false gpu-a10g",
1604            "g5.xlarge min=1 max=1 memory=17179869184 storage=268435456000",
1605        ),
1606    ];
1607
1608    /// Automatic picks, with the memory and disk they provision, are what existing stacks get
1609    /// on their next deploy, so a catalog change must leave them alone. The baseline holds the
1610    /// picks every case gets; only the cases in `ACCEPTED_PICK_CHANGES` may differ.
1611    #[test]
1612    fn automatic_picks_match_the_baseline_except_accepted_changes() {
1613        let baseline = include_str!("instance_catalog/auto_selection_baseline.txt");
1614        let rendered = render_selection_matrix();
1615        assert_eq!(baseline.lines().count(), rendered.lines().count());
1616        fn split(line: &str) -> (&str, &str) {
1617            line.split_once(" -> ").unwrap_or((line, ""))
1618        }
1619        for (before, now) in baseline.lines().zip(rendered.lines()) {
1620            let ((case, _), (now_case, pick)) = (split(before), split(now));
1621            assert_eq!(case, now_case);
1622            match ACCEPTED_PICK_CHANGES
1623                .iter()
1624                .find(|(accepted, _)| *accepted == case)
1625            {
1626                Some((_, accepted_pick)) => {
1627                    assert_ne!(
1628                        before, now,
1629                        "{case} no longer changes; drop it from the list"
1630                    );
1631                    assert_eq!(pick, *accepted_pick, "{case}");
1632                }
1633                None => assert_eq!(before, now, "automatic pick changed"),
1634            }
1635        }
1636    }
1637
1638    type PinnedMachine = (
1639        Platform,
1640        &'static str,
1641        u32,
1642        u64,
1643        u64,
1644        Option<(&'static str, u32)>,
1645        bool,
1646    );
1647
1648    /// Machines existing stacks may run, with the vCPU, memory, disk, GPU and nested
1649    /// virtualization they are planned with. Each must stay in the catalog with those values.
1650    #[rustfmt::skip]
1651    const PINNED_MACHINES: &[PinnedMachine] = &[
1652        (Platform::Aws, "t4g.micro", 2, GI, 20 * GI, None, false),
1653        (Platform::Aws, "t4g.small", 2, 2 * GI, 20 * GI, None, false),
1654        (Platform::Aws, "t4g.medium", 2, 4 * GI, 20 * GI, None, false),
1655        (Platform::Aws, "t4g.large", 2, 8 * GI, 20 * GI, None, false),
1656        (Platform::Aws, "t3.xlarge", 4, 16 * GI, 20 * GI, None, false),
1657        (Platform::Aws, "t4g.xlarge", 4, 16 * GI, 20 * GI, None, false),
1658        (Platform::Aws, "m7g.medium", 1, 4 * GI, 20 * GI, None, false),
1659        (Platform::Aws, "m7i.large", 2, 8 * GI, 20 * GI, None, false),
1660        (Platform::Aws, "m7g.large", 2, 8 * GI, 20 * GI, None, false),
1661        (Platform::Aws, "m8i.large", 2, 8 * GI, 20 * GI, None, true),
1662        (Platform::Aws, "m7i.xlarge", 4, 16 * GI, 20 * GI, None, false),
1663        (Platform::Aws, "m7g.xlarge", 4, 16 * GI, 20 * GI, None, false),
1664        (Platform::Aws, "m8i.xlarge", 4, 16 * GI, 20 * GI, None, true),
1665        (Platform::Aws, "m7i.2xlarge", 8, 32 * GI, 20 * GI, None, false),
1666        (Platform::Aws, "m7g.2xlarge", 8, 32 * GI, 20 * GI, None, false),
1667        (Platform::Aws, "m8i.2xlarge", 8, 32 * GI, 20 * GI, None, true),
1668        (Platform::Aws, "m7i.4xlarge", 16, 64 * GI, 20 * GI, None, false),
1669        (Platform::Aws, "m7g.4xlarge", 16, 64 * GI, 20 * GI, None, false),
1670        (Platform::Aws, "m8i.4xlarge", 16, 64 * GI, 20 * GI, None, true),
1671        (Platform::Aws, "c7g.medium", 1, 2 * GI, 20 * GI, None, false),
1672        (Platform::Aws, "c8g.medium", 1, 2 * GI, 20 * GI, None, false),
1673        (Platform::Aws, "c7g.large", 2, 4 * GI, 20 * GI, None, false),
1674        (Platform::Aws, "c8g.large", 2, 4 * GI, 20 * GI, None, false),
1675        (Platform::Aws, "c8i.large", 2, 4 * GI, 20 * GI, None, true),
1676        (Platform::Aws, "c7g.xlarge", 4, 8 * GI, 20 * GI, None, false),
1677        (Platform::Aws, "c8g.xlarge", 4, 8 * GI, 20 * GI, None, false),
1678        (Platform::Aws, "c8i.xlarge", 4, 8 * GI, 20 * GI, None, true),
1679        (Platform::Aws, "c7g.2xlarge", 8, 16 * GI, 20 * GI, None, false),
1680        (Platform::Aws, "c8g.2xlarge", 8, 16 * GI, 20 * GI, None, false),
1681        (Platform::Aws, "c8i.2xlarge", 8, 16 * GI, 20 * GI, None, true),
1682        (Platform::Aws, "c7g.4xlarge", 16, 32 * GI, 20 * GI, None, false),
1683        (Platform::Aws, "c8g.4xlarge", 16, 32 * GI, 20 * GI, None, false),
1684        (Platform::Aws, "c8i.4xlarge", 16, 32 * GI, 20 * GI, None, true),
1685        (Platform::Aws, "r7g.medium", 1, 8 * GI, 20 * GI, None, false),
1686        (Platform::Aws, "r7g.large", 2, 16 * GI, 20 * GI, None, false),
1687        (Platform::Aws, "r6a.large", 2, 16 * GI, 20 * GI, None, false),
1688        (Platform::Aws, "r7i.large", 2, 16 * GI, 20 * GI, None, false),
1689        (Platform::Aws, "r7g.xlarge", 4, 32 * GI, 20 * GI, None, false),
1690        (Platform::Aws, "r6a.xlarge", 4, 32 * GI, 20 * GI, None, false),
1691        (Platform::Aws, "r7i.xlarge", 4, 32 * GI, 20 * GI, None, false),
1692        (Platform::Aws, "r7g.2xlarge", 8, 64 * GI, 20 * GI, None, false),
1693        (Platform::Aws, "r6a.2xlarge", 8, 64 * GI, 20 * GI, None, false),
1694        (Platform::Aws, "r7i.2xlarge", 8, 64 * GI, 20 * GI, None, false),
1695        (Platform::Aws, "r7g.4xlarge", 16, 128 * GI, 20 * GI, None, false),
1696        (Platform::Aws, "r6a.4xlarge", 16, 128 * GI, 20 * GI, None, false),
1697        (Platform::Aws, "r7i.4xlarge", 16, 128 * GI, 20 * GI, None, false),
1698        (Platform::Aws, "i4i.xlarge", 4, 32 * GI, 937 * GI, None, false),
1699        (Platform::Aws, "i4i.2xlarge", 8, 64 * GI, 1875 * GI, None, false),
1700        (Platform::Aws, "i4i.4xlarge", 16, 128 * GI, 3750 * GI, None, false),
1701        (Platform::Aws, "i4i.8xlarge", 32, 256 * GI, 7500 * GI, None, false),
1702        (Platform::Aws, "g5.xlarge", 4, 16 * GI, 250 * GI, Some(("nvidia-t4", 1)), false),
1703        (Platform::Aws, "g5.2xlarge", 8, 32 * GI, 450 * GI, Some(("nvidia-t4", 1)), false),
1704        (Platform::Aws, "p4d.24xlarge", 96, 1152 * GI, 8000 * GI, Some(("nvidia-a100", 8)), false),
1705        (Platform::Aws, "p5.48xlarge", 192, 2048 * GI, 8000 * GI, Some(("nvidia-h100", 8)), false),
1706        (Platform::Gcp, "e2-micro", 2, GI, 20 * GI, None, false),
1707        (Platform::Gcp, "e2-small", 2, 2 * GI, 20 * GI, None, false),
1708        (Platform::Gcp, "e2-medium", 2, 4 * GI, 20 * GI, None, false),
1709        (Platform::Gcp, "n2-standard-2", 2, 8 * GI, 20 * GI, None, true),
1710        (Platform::Gcp, "n2-standard-4", 4, 16 * GI, 20 * GI, None, true),
1711        (Platform::Gcp, "n2-standard-8", 8, 32 * GI, 20 * GI, None, true),
1712        (Platform::Gcp, "n2-standard-16", 16, 64 * GI, 20 * GI, None, true),
1713        (Platform::Gcp, "c3-standard-4", 4, 8 * GI, 20 * GI, None, false),
1714        (Platform::Gcp, "c3-standard-8", 8, 16 * GI, 20 * GI, None, false),
1715        (Platform::Gcp, "n2-highmem-2", 2, 16 * GI, 20 * GI, None, false),
1716        (Platform::Gcp, "n2-highmem-4", 4, 32 * GI, 20 * GI, None, false),
1717        (Platform::Gcp, "n2-highmem-8", 8, 64 * GI, 20 * GI, None, false),
1718        (Platform::Gcp, "n2-highmem-16", 16, 128 * GI, 20 * GI, None, false),
1719        (Platform::Gcp, "n2-highmem-32", 32, 256 * GI, 20 * GI, None, false),
1720        (Platform::Gcp, "c3d-standard-8", 8, 32 * GI, 480 * GI, None, false),
1721        (Platform::Gcp, "c3d-standard-16", 16, 64 * GI, 960 * GI, None, false),
1722        (Platform::Gcp, "c3d-standard-30", 30, 120 * GI, 1920 * GI, None, false),
1723        (Platform::Gcp, "n1-standard-4-t4", 4, 15 * GI, 100 * GI, Some(("nvidia-t4", 1)), false),
1724        (Platform::Gcp, "a2-highgpu-1g", 12, 85 * GI, 100 * GI, Some(("nvidia-a100", 1)), false),
1725        (Platform::Gcp, "a2-highgpu-8g", 96, 1360 * GI, 100 * GI, Some(("nvidia-a100", 8)), false),
1726        (Platform::Gcp, "a3-highgpu-8g", 208, 1872 * GI, 100 * GI, Some(("nvidia-h100", 8)), false),
1727        (Platform::Azure, "Standard_B1s", 1, GI, 20 * GI, None, false),
1728        (Platform::Azure, "Standard_B2s", 2, 4 * GI, 20 * GI, None, false),
1729        (Platform::Azure, "Standard_B2ms", 2, 8 * GI, 20 * GI, None, false),
1730        (Platform::Azure, "Standard_B4ms", 4, 16 * GI, 20 * GI, None, false),
1731        (Platform::Azure, "Standard_D2s_v4", 2, 8 * GI, 20 * GI, None, false),
1732        (Platform::Azure, "Standard_D2s_v5", 2, 8 * GI, 20 * GI, None, true),
1733        (Platform::Azure, "Standard_D4s_v5", 4, 16 * GI, 20 * GI, None, true),
1734        (Platform::Azure, "Standard_D8s_v5", 8, 32 * GI, 20 * GI, None, true),
1735        (Platform::Azure, "Standard_D16s_v5", 16, 64 * GI, 20 * GI, None, true),
1736        (Platform::Azure, "Standard_D2s_v6", 2, 8 * GI, 20 * GI, None, true),
1737        (Platform::Azure, "Standard_D4s_v6", 4, 16 * GI, 20 * GI, None, true),
1738        (Platform::Azure, "Standard_D8s_v6", 8, 32 * GI, 20 * GI, None, true),
1739        (Platform::Azure, "Standard_D16s_v6", 16, 64 * GI, 20 * GI, None, true),
1740        (Platform::Azure, "Standard_F2s_v2", 2, 4 * GI, 20 * GI, None, true),
1741        (Platform::Azure, "Standard_F4s_v2", 4, 8 * GI, 20 * GI, None, true),
1742        (Platform::Azure, "Standard_F8s_v2", 8, 16 * GI, 20 * GI, None, true),
1743        (Platform::Azure, "Standard_F16s_v2", 16, 32 * GI, 20 * GI, None, true),
1744        (Platform::Azure, "Standard_E2s_v5", 2, 16 * GI, 20 * GI, None, true),
1745        (Platform::Azure, "Standard_E4s_v5", 4, 32 * GI, 20 * GI, None, true),
1746        (Platform::Azure, "Standard_E8s_v5", 8, 64 * GI, 20 * GI, None, true),
1747        (Platform::Azure, "Standard_E16s_v5", 16, 128 * GI, 20 * GI, None, true),
1748        (Platform::Azure, "Standard_L8s_v3", 8, 64 * GI, 1788 * GI, None, false),
1749        (Platform::Azure, "Standard_L16s_v3", 16, 128 * GI, 3576 * GI, None, false),
1750        (Platform::Azure, "Standard_L32s_v3", 32, 256 * GI, 7154 * GI, None, false),
1751        (Platform::Azure, "Standard_NC4as_T4_v3", 4, 28 * GI, 176 * GI, Some(("nvidia-t4", 1)), false),
1752        (Platform::Azure, "Standard_NC24ads_A100_v4", 24, 220 * GI, 958 * GI, Some(("nvidia-a100", 1)), false),
1753        (Platform::Azure, "Standard_NC96ads_A100_v4", 96, 880 * GI, 3916 * GI, Some(("nvidia-a100", 4)), false),
1754        (Platform::Azure, "Standard_ND96isr_H100_v5", 96, 1900 * GI, 1000 * GI, Some(("nvidia-h100", 8)), false),
1755    ];
1756
1757    /// Pinned machines whose GPU type the AWS API reports differently, with that type.
1758    const GPU_TYPE_CORRECTIONS: &[(&str, &str)] =
1759        &[("g5.xlarge", "nvidia-a10g"), ("g5.2xlarge", "nvidia-a10g")];
1760
1761    #[test]
1762    fn every_pinned_machine_is_still_in_the_catalog_with_its_values() {
1763        for &(platform, name, vcpu, memory_bytes, storage_bytes, gpu, nested_virt) in
1764            PINNED_MACHINES
1765        {
1766            let spec = find_instance_type(platform, name)
1767                .unwrap_or_else(|| panic!("{platform} machine {name} left the catalog"));
1768            let gpu = gpu.map(|(gpu_type, count)| {
1769                let corrected = GPU_TYPE_CORRECTIONS
1770                    .iter()
1771                    .find(|(corrected, _)| *corrected == name);
1772                (corrected.map_or(gpu_type, |(_, gpu_type)| *gpu_type), count)
1773            });
1774            assert_eq!(
1775                (
1776                    spec.vcpu,
1777                    spec.memory_bytes,
1778                    spec.ephemeral_storage_bytes,
1779                    spec.gpu.map(|gpu| (gpu.gpu_type, gpu.count)),
1780                    spec.nested_virt,
1781                ),
1782                (vcpu, memory_bytes, storage_bytes, gpu, nested_virt),
1783                "{platform} {name}"
1784            );
1785        }
1786    }
1787
1788    #[test]
1789    fn automatic_selection_considers_exactly_the_pinned_machines() {
1790        let pinned: std::collections::HashSet<_> = PINNED_MACHINES
1791            .iter()
1792            .map(|&(platform, name, ..)| (platform, name))
1793            .collect();
1794        let auto_select: std::collections::HashSet<_> = CATALOG
1795            .iter()
1796            .filter(|spec| spec.auto_select)
1797            .map(|spec| (spec.platform, spec.name))
1798            .collect();
1799        assert_eq!(auto_select, pinned);
1800    }
1801
1802    fn general_requirements() -> WorkloadRequirements {
1803        WorkloadRequirements {
1804            total_cpu_at_desired: 3.0,
1805            total_memory_bytes_at_desired: 12 * GI,
1806            total_cpu_at_max: 3.0,
1807            total_memory_bytes_at_max: 12 * GI,
1808            max_cpu_per_container: 1.0,
1809            max_memory_per_container: 4 * GI,
1810            max_ephemeral_storage_bytes: 10 * GI,
1811            gpu: None,
1812            architecture: None,
1813            nested_virt: true,
1814        }
1815    }
1816
1817    #[test]
1818    fn azure_auto_selection_prefers_dsv5_then_dsv6_in_catalog_order() {
1819        let series = auto_select_series(Platform::Azure);
1820        let position = |name| series.iter().position(|series| *series == name);
1821        assert!(
1822            position("Dsv5").unwrap() < position("Dsv6").unwrap(),
1823            "{series:?}"
1824        );
1825    }
1826
1827    #[test]
1828    fn with_room_everywhere_the_pick_is_the_plain_pick() {
1829        let requirements = general_requirements();
1830        let plain = select_instance_type(Platform::Azure, &requirements).unwrap();
1831        let with_room =
1832            select_instance_type_with_room(Platform::Azure, &requirements, 2, &|_, _| true)
1833                .unwrap();
1834        assert_eq!(plain.instance_type, with_room.instance_type);
1835        assert!(
1836            with_room.instance_type.ends_with("_v5"),
1837            "{}",
1838            with_room.instance_type
1839        );
1840    }
1841
1842    #[test]
1843    fn a_series_without_room_is_skipped_for_the_next_one() {
1844        let requirements = general_requirements();
1845        let selection =
1846            select_instance_type_with_room(Platform::Azure, &requirements, 2, &|spec, _| {
1847                spec.series != "Dsv5"
1848            })
1849            .unwrap();
1850        assert_eq!(selection.instance_type, "Standard_D4s_v6");
1851    }
1852
1853    #[test]
1854    fn room_is_asked_for_the_requested_machines() {
1855        let requirements = general_requirements();
1856        let asked = std::cell::RefCell::new(Vec::new());
1857        select_instance_type_with_room(Platform::Azure, &requirements, 3, &|spec, machines| {
1858            asked.borrow_mut().push((spec.series, machines));
1859            true
1860        })
1861        .unwrap();
1862        assert!(asked.borrow().iter().all(|(_, machines)| *machines == 3));
1863    }
1864
1865    /// A local disk is preferred to a configurable one whatever the series that has room:
1866    /// the machines of series without room are skipped, not the storage preference.
1867    #[test]
1868    fn local_storage_is_preferred_among_the_series_with_room() {
1869        let requirements = WorkloadRequirements {
1870            max_ephemeral_storage_bytes: 500 * GI,
1871            nested_virt: false,
1872            ..general_requirements()
1873        };
1874        let plain = select_instance_type(Platform::Azure, &requirements).unwrap();
1875        let plain_spec = find_instance_type(Platform::Azure, plain.instance_type).unwrap();
1876        assert!(
1877            !plain_spec.has_configurable_ephemeral_storage(),
1878            "the plain pick has a local disk: {}",
1879            plain.instance_type
1880        );
1881        let with_room =
1882            select_instance_type_with_room(Platform::Azure, &requirements, 1, &|_, _| true)
1883                .unwrap();
1884        assert_eq!(with_room.instance_type, plain.instance_type);
1885        // Series that cannot give a local disk have room too, and still lose to it.
1886        let local_only =
1887            select_instance_type_with_room(Platform::Azure, &requirements, 1, &|spec, _| {
1888                spec.series == plain_spec.series || spec.series.starts_with("Dsv")
1889            })
1890            .unwrap();
1891        assert_eq!(local_only.instance_type, plain.instance_type);
1892    }
1893
1894    #[test]
1895    fn with_no_room_anywhere_the_plain_pick_is_kept_for_the_quota_refusal() {
1896        let requirements = general_requirements();
1897        let plain = select_instance_type(Platform::Azure, &requirements).unwrap();
1898        let none = select_instance_type_with_room(Platform::Azure, &requirements, 2, &|_, _| false)
1899            .unwrap();
1900        assert_eq!(plain.instance_type, none.instance_type);
1901    }
1902
1903    #[test]
1904    fn bare_metal_rows_are_never_picked_automatically_and_nest_only_on_x86() {
1905        let c5 = find_instance_type(Platform::Aws, "c5.metal").expect("c5.metal is listed");
1906        assert!(c5.bare_metal && c5.architecture == Architecture::X86_64 && c5.nested_virt);
1907        let m8g =
1908            find_instance_type(Platform::Aws, "m8g.metal-24xl").expect("m8g.metal-24xl is listed");
1909        assert!(m8g.bare_metal && m8g.architecture == Architecture::Arm64 && !m8g.nested_virt);
1910        for spec in CATALOG {
1911            assert_eq!(spec.bare_metal, spec.name.contains(".metal"), "{}", spec.name);
1912            if spec.bare_metal {
1913                assert!(!spec.auto_select, "{}", spec.name);
1914                assert_eq!(
1915                    spec.nested_virt,
1916                    spec.architecture == Architecture::X86_64,
1917                    "{}",
1918                    spec.name
1919                );
1920            }
1921        }
1922    }
1923
1924    #[test]
1925    fn primary_series_are_the_newest_plain_families_of_each_category_and_processor() {
1926        for name in ["m8i.large", "c8i.large", "r8a.large", "m9g.large", "i7i.large", "g5.xlarge"] {
1927            let spec = find_instance_type(Platform::Aws, name).expect(name);
1928            assert!(spec.primary, "{name} is not primary");
1929        }
1930        // An older generation, and newest-generation families with other options.
1931        for name in ["c5.large", "m7i.large", "c7g.large", "c8in.large", "i8ge.large"] {
1932            let spec = find_instance_type(Platform::Aws, name).expect(name);
1933            assert!(!spec.primary, "{name} is primary");
1934        }
1935        for spec in CATALOG {
1936            if spec.platform != Platform::Aws {
1937                assert!(spec.primary, "{} is not primary", spec.name);
1938            }
1939            let series_primary = CATALOG
1940                .iter()
1941                .filter(|other| other.platform == spec.platform && other.series == spec.series)
1942                .all(|other| other.primary == spec.primary);
1943            assert!(series_primary, "series {} mixes primary rows", spec.series);
1944        }
1945        // The label names the processor; each one keeps a primary series in every category.
1946        let processor = |spec: &InstanceTypeSpec| {
1947            ["Graviton", "AMD", "Intel"].into_iter().find(|word| spec.label.contains(word))
1948        };
1949        for spec in CATALOG.iter().filter(|spec| spec.platform == Platform::Aws) {
1950            assert!(
1951                CATALOG.iter().any(|other| other.platform == Platform::Aws
1952                    && other.family == spec.family
1953                    && processor(other) == processor(spec)
1954                    && other.primary),
1955                "no primary AWS series for {:?} {:?}",
1956                spec.family,
1957                processor(spec)
1958            );
1959        }
1960    }
1961
1962    /// The generator writes each series as one run of rows, smallest first.
1963    #[test]
1964    fn test_catalog_instance_types_sorted_by_vcpu_within_series() {
1965        let mut finished = std::collections::HashSet::new();
1966        for window in CATALOG.windows(2) {
1967            let (previous, next) = (&window[0], &window[1]);
1968            if (previous.platform, previous.series) == (next.platform, next.series) {
1969                assert!(
1970                    previous.vcpu <= next.vcpu,
1971                    "{} ({}) before {} ({})",
1972                    previous.name,
1973                    previous.vcpu,
1974                    next.name,
1975                    next.vcpu
1976                );
1977            } else {
1978                finished.insert((previous.platform, previous.series));
1979                assert!(
1980                    !finished.contains(&(next.platform, next.series)),
1981                    "series {} is split",
1982                    next.series
1983                );
1984            }
1985        }
1986    }
1987}