1use crate::{
8 instance_catalog::{self, Architecture, InstanceFamily, WorkloadRequirements},
9 CapacityGroup, CapacityGroupScalePolicy, ComputeChoiceRange, ComputePoolSelection, Container,
10 Daemon, ErrorData, FailureDomainSelection, GpuSpec, MachineProfile, Platform, ResourceSpec,
11 Stack, StackState,
12};
13use alien_error::{AlienError, Result};
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
20#[serde(rename_all = "camelCase")]
21pub struct ComputePlan {
22 pub pools: Vec<ComputePoolPlan>,
24 #[serde(default, skip_serializing_if = "Vec::is_empty")]
26 pub containers: Vec<ContainerResourcePlan>,
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
32#[serde(rename_all = "camelCase")]
33pub struct ContainerResourcePlan {
34 pub container_id: String,
36 pub choices: crate::ContainerResourceChoices,
38 pub cpu: ResourceSpec,
40 pub memory: ResourceSpec,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub volume_size_gib: Option<u32>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub minimum_volume_size_gib: Option<u32>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub maximum_volume_size_gib: Option<u32>,
51}
52
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
56#[serde(rename_all = "camelCase")]
57pub struct ComputePoolPlan {
58 pub pool_id: String,
60 pub workloads: Vec<String>,
62 pub requirements: MachineProfile,
64 pub scale: CapacityGroupScalePolicy,
66 pub selected: ComputePoolSelection,
68 pub recommended: ComputePoolSelection,
70 pub machines: Vec<ComputeMachineOption>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub data_disk: Option<ComputePoolDataDiskPlan>,
77 #[serde(default, skip_serializing_if = "Vec::is_empty")]
79 pub errors: Vec<String>,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
87#[serde(rename_all = "camelCase")]
88pub struct ComputePoolDataDiskPlan {
89 pub min_gib: u32,
91 pub max_gib: u32,
93 pub default_gib: u32,
95 pub selected_gib: u32,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
102#[serde(rename_all = "camelCase")]
103pub struct ComputeMachineOption {
104 pub machine: String,
106 pub series: String,
108 pub category: InstanceFamily,
110 pub label: String,
112 pub profile: MachineProfile,
114 pub nested_virtualization: bool,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub local_storage: Option<u64>,
120 pub available: bool,
122 pub unavailable_reasons: Vec<MachineUnavailableReason>,
124 pub recommended: bool,
126 pub primary: bool,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
135#[serde(rename_all = "camelCase")]
136pub enum MachineUnavailableReason {
137 Architecture,
139 NestedVirtualization,
141 Cpu,
143 Memory,
145 EphemeralStorage,
148 Gpu,
150}
151
152pub fn default_persistent_failure_domains() -> FailureDomainSelection {
156 FailureDomainSelection {
157 spread: 1,
158 selected_failure_domains: Vec::new(),
159 }
160}
161
162pub fn plan_compute(
164 stack: &Stack,
165 platform: Platform,
166 selected_settings: Option<&crate::ComputeSettings>,
167) -> Result<ComputePlan, ErrorData> {
168 plan_compute_with_state(stack, platform, selected_settings, None)
169}
170
171pub fn plan_compute_with_state(
174 stack: &Stack,
175 platform: Platform,
176 selected_settings: Option<&crate::ComputeSettings>,
177 previous_state: Option<&StackState>,
178) -> Result<ComputePlan, ErrorData> {
179 plan_compute_with_room(stack, platform, selected_settings, previous_state, None)
180}
181
182pub trait MachineRoom {
186 fn has_room(
189 &self,
190 pool_id: &str,
191 spec: &instance_catalog::InstanceTypeSpec,
192 machines: u32,
193 ) -> bool;
194
195 fn commit(&self, pool_id: &str, spec: &instance_catalog::InstanceTypeSpec, machines: u32);
199}
200
201pub fn plan_compute_with_room(
204 stack: &Stack,
205 platform: Platform,
206 selected_settings: Option<&crate::ComputeSettings>,
207 previous_state: Option<&StackState>,
208 room: Option<&dyn MachineRoom>,
209) -> Result<ComputePlan, ErrorData> {
210 let mut resolved_stack = stack.clone();
211 crate::container_resources::resolve_container_resources(
212 &mut resolved_stack,
213 selected_settings,
214 )?;
215 if let Some(previous_state) = previous_state {
216 crate::container_resources::retain_installed_volume_sizes(
217 &mut resolved_stack,
218 selected_settings,
219 previous_state,
220 );
221 }
222 let (minimum, maximum) = match platform {
223 Platform::Gcp => (10, 65536),
224 Platform::Azure => (1, 32767),
225 _ => (1, 65536),
226 };
227 for (id, entry) in &resolved_stack.resources {
228 let Some(storage) = entry
229 .config
230 .downcast_ref::<Container>()
231 .and_then(|container| container.persistent_storage.as_ref())
232 else {
233 continue;
234 };
235 let size = crate::container_resources::parse_volume_size_gib(&storage.size)
236 .map_err(|reason| crate::container_resources::invalid(id, "volumeSizeGib", &reason))?;
237 if size < minimum || size > maximum {
238 return Err(AlienError::new(
239 ErrorData::ContainerResourceSelectionInvalid {
240 resource_id: id.clone(),
241 dimension: "volumeSizeGib".into(),
242 reason: format!(
243 "capacity for {platform} must be between {minimum} and {maximum} GiB"
244 ),
245 },
246 ));
247 }
248 }
249 if let Some(previous_state) = previous_state {
250 for (id, entry) in &resolved_stack.resources {
251 let desired = entry
252 .config
253 .downcast_ref::<Container>()
254 .and_then(|container| container.persistent_storage.as_ref());
255 let previous = previous_state
256 .resources
257 .get(id)
258 .and_then(|resource| resource.config.downcast_ref::<Container>())
259 .and_then(|container| container.persistent_storage.as_ref());
260 if previous.is_some() && desired.is_none() {
261 return Err(crate::container_resources::invalid(
262 id,
263 "volumeSizeGib",
264 "removing installed persistent storage is unsupported",
265 ));
266 }
267 if let (Some(desired), Some(previous)) = (desired, previous) {
268 if desired.mount_path != previous.mount_path {
269 return Err(crate::container_resources::invalid(
270 id,
271 "volumeSizeGib",
272 "changing an installed persistent storage mount path is unsupported",
273 ));
274 }
275 let target = crate::container_resources::parse_volume_size_gib(&desired.size);
276 let installed = crate::container_resources::parse_volume_size_gib(&previous.size);
277 if let (Ok(target), Ok(installed)) = (target, installed) {
278 if target < installed {
279 return Err(AlienError::new(ErrorData::ContainerResourceSelectionInvalid {
280 resource_id: id.clone(), dimension: "volumeSizeGib".into(),
281 reason: format!("existing volumes cannot shrink from {installed} to {target} GiB"),
282 }));
283 }
284 }
285 }
286 }
287 }
288 let stack = &resolved_stack;
289 let mut groups = collect_workload_groups(stack)?;
290 merge_explicit_compute_groups(stack, &mut groups)?;
291
292 let mut pool_ids: Vec<String> = groups.keys().cloned().collect();
293 pool_ids.sort();
294
295 if let Some(room) = room {
298 for pool_id in &pool_ids {
299 let selected = selected_settings.and_then(|settings| settings.pools.get(pool_id));
300 let declared = stack
301 .resources
302 .values()
303 .filter_map(|entry| entry.config.downcast_ref::<crate::ComputeCluster>())
304 .flat_map(|cluster| &cluster.capacity_groups)
305 .find(|group| &group.group_id == pool_id)
306 .and_then(|group| group.instance_type.as_deref());
307 let machine = match selected {
308 Some(selection) => selection.machine(),
309 None => declared,
310 };
311 if let Some(spec) =
312 machine.and_then(|machine| instance_catalog::find_instance_type(platform, machine))
313 {
314 let machines = selected
315 .map(ComputePoolSelection::min_size)
316 .unwrap_or_else(|| groups[pool_id].scale.default_min_size());
317 room.commit(pool_id, spec, machines);
318 }
319 }
320 }
321
322 let mut pools = Vec::new();
323 for pool_id in pool_ids {
324 let mut group = groups.remove(&pool_id).expect("pool id came from map keys");
325 let mut requirements = group.requirements;
326 let selected = selected_settings.and_then(|settings| settings.pools.get(&pool_id));
327 let declared_group = stack
328 .resources
329 .values()
330 .filter_map(|entry| entry.config.downcast_ref::<crate::ComputeCluster>())
331 .flat_map(|cluster| &cluster.capacity_groups)
332 .find(|group| group.group_id == pool_id);
333 let declared_machine = declared_group.and_then(|group| group.instance_type.as_deref());
334 let machine_override = match selected {
335 Some(selection) => selection.machine(),
336 None => declared_machine,
337 };
338 if requirements.architecture.is_none() {
339 requirements.architecture = machine_override
340 .and_then(|machine| instance_catalog::find_instance_type(platform, machine))
341 .map(|spec| spec.architecture)
342 .or_else(|| {
343 previous_state.and_then(|state| {
344 state
345 .resources
346 .values()
347 .filter_map(|resource| {
348 resource.config.downcast_ref::<crate::ComputeCluster>()
349 })
350 .flat_map(|cluster| &cluster.capacity_groups)
351 .find(|group| group.group_id == pool_id)
352 .and_then(|group| group.instance_type.as_deref())
353 .and_then(|machine| {
354 instance_catalog::find_instance_type(platform, machine)
355 })
356 .map(|spec| spec.architecture)
357 })
358 });
359 }
360 let workload_machines = if group.generated {
363 group
364 .scale
365 .default_max_size()
366 .min(GENERATED_POOL_MAX_MACHINES)
367 } else {
368 group.scale.default_max_size()
369 };
370 if group.generated {
371 group.scale = generated_pool_scale_policy(
372 group.scale.default_min_size(),
373 workload_machines + group.rolling_update_machines,
374 selected.map(ComputePoolSelection::max_size),
375 );
376 }
377 let machines = selected
378 .map(ComputePoolSelection::max_size)
379 .unwrap_or(workload_machines)
380 .max(1);
381 let mut sizing = requirements.clone();
382 sizing.max_cpu_per_container = sizing
384 .max_cpu_per_container
385 .max(sizing.total_cpu_at_desired / f64::from(machines));
386 sizing.max_memory_per_container = sizing.max_memory_per_container.max(
387 sizing
388 .total_memory_bytes_at_desired
389 .div_ceil(u64::from(machines)),
390 );
391 let recommended = recommended_selection(
392 platform,
393 &sizing,
394 &group.scale,
395 group.requires_failure_domain,
396 group.generated,
397 machine_override,
398 room.filter(|_| machine_override.is_none())
400 .map(|room| PoolRoom {
401 room,
402 pool_id: &pool_id,
403 machines: selected.map(ComputePoolSelection::min_size),
404 }),
405 )?;
406 let mut selected_choice = selected.cloned().unwrap_or_else(|| recommended.clone());
407 if selected.is_none() {
408 if let Some(declared_machine) = declared_machine {
409 match &mut selected_choice {
410 ComputePoolSelection::Fixed { machine, .. }
411 | ComputePoolSelection::Autoscale { machine, .. } => {
412 *machine = Some(declared_machine.to_string());
413 }
414 }
415 }
416 }
417 match &mut selected_choice {
421 ComputePoolSelection::Fixed { machine, .. }
422 | ComputePoolSelection::Autoscale { machine, .. } => {
423 if machine.is_none() {
424 *machine = recommended.machine().map(ToString::to_string);
425 }
426 }
427 }
428 if selected_choice.failure_domains().is_none() {
429 if let Some(default_failure_domains) = recommended.failure_domains().cloned() {
430 match &mut selected_choice {
431 ComputePoolSelection::Fixed {
432 failure_domains, ..
433 }
434 | ComputePoolSelection::Autoscale {
435 failure_domains, ..
436 } => *failure_domains = Some(default_failure_domains),
437 }
438 }
439 }
440 if let Some(room) = room {
441 if let Some(spec) = selected_choice
442 .machine()
443 .and_then(|machine| instance_catalog::find_instance_type(platform, machine))
444 {
445 room.commit(&pool_id, spec, selected_choice.min_size());
446 }
447 }
448 let mut errors = validate_compute_pool_selection(
449 platform,
450 &pool_id,
451 &selected_choice,
452 &requirements,
453 &group.scale,
454 );
455 if let Some(workload_requirements) = &group.workload_requirements {
458 if let Err(message) =
459 check_pool_capacity(platform, &pool_id, &selected_choice, workload_requirements)
460 {
461 errors.push(message);
462 }
463 }
464 let selected_data_disk_gib = selected.and_then(ComputePoolSelection::data_disk_gib);
465 let data_disk_choices = declared_group.and_then(crate::CapacityGroup::data_disk_choices);
466 let data_disk_result = match declared_group {
467 Some(group) => group.effective_data_disk_gib(selected_data_disk_gib),
468 None => match selected_data_disk_gib {
469 None | Some(0) => Ok(None),
470 Some(size) => Err(format!(
471 "pool '{pool_id}' declares no data disk, so dataDiskGib {size} cannot be chosen"
472 )),
473 },
474 };
475 if let Err(message) = &data_disk_result {
476 errors.push(message.clone());
477 }
478 let data_disk = data_disk_choices.map(|choices| ComputePoolDataDiskPlan {
479 min_gib: choices.min,
480 max_gib: choices.max,
481 default_gib: choices.default,
482 selected_gib: match &data_disk_result {
483 Ok(size) => size.unwrap_or(0),
484 Err(_) => selected_data_disk_gib.unwrap_or(choices.default),
485 },
486 });
487 let machines = machine_options(
488 platform,
489 &requirements,
490 group.workload_requirements.as_ref(),
491 selected_choice.machine(),
492 recommended.machine(),
493 )?;
494
495 pools.push(ComputePoolPlan {
496 pool_id,
497 workloads: group.workloads,
498 requirements: requirements_to_profile(&requirements),
499 scale: group.scale,
500 selected: selected_choice,
501 recommended,
502 machines,
503 data_disk,
504 errors,
505 });
506 }
507
508 let mut containers: Vec<_> = stack
509 .resources
510 .values()
511 .filter_map(|entry| entry.config.downcast_ref::<Container>())
512 .filter(|container| {
513 container.resource_choices.is_some() || container.persistent_storage.is_some()
514 })
515 .map(|container| {
516 let capacity = |storage: &crate::PersistentStorage| {
517 crate::container_resources::parse_volume_size_gib(&storage.size).map_err(|reason| {
518 crate::container_resources::invalid(&container.id, "volumeSizeGib", &reason)
519 })
520 };
521 let volume_size_gib = container
522 .persistent_storage
523 .as_ref()
524 .map(capacity)
525 .transpose()?;
526 let installed = previous_state
527 .and_then(|state| state.resources.get(&container.id))
528 .and_then(|resource| resource.config.downcast_ref::<Container>())
529 .and_then(|container| container.persistent_storage.as_ref())
530 .map(capacity)
531 .transpose()?;
532 Ok(ContainerResourcePlan {
533 container_id: container.id.clone(),
534 choices: container.resource_choices.clone().unwrap_or_default(),
535 cpu: container.cpu.clone(),
536 memory: container.memory.clone(),
537 volume_size_gib,
538 minimum_volume_size_gib: volume_size_gib
539 .map(|_| installed.unwrap_or(if platform == Platform::Gcp { 10 } else { 1 })),
540 maximum_volume_size_gib: volume_size_gib.map(|_| {
541 if platform == Platform::Azure {
542 32767
543 } else {
544 65536
545 }
546 }),
547 })
548 })
549 .collect::<Result<Vec<_>, ErrorData>>()?;
550 containers.sort_by(|a, b| a.container_id.cmp(&b.container_id));
551 Ok(ComputePlan { pools, containers })
552}
553
554#[derive(Debug, Clone)]
555struct PlannedGroup {
556 workloads: Vec<String>,
557 workload_requirements: Option<WorkloadRequirements>,
559 requirements: WorkloadRequirements,
560 scale: CapacityGroupScalePolicy,
561 requires_failure_domain: bool,
562 generated: bool,
565 rolling_update_machines: u32,
568}
569
570pub const GENERATED_POOL_MAX_MACHINES: u32 = 100;
575
576pub fn generated_pool_scale_policy(
588 default_min: u32,
589 default_max: u32,
590 selected_max: Option<u32>,
591) -> CapacityGroupScalePolicy {
592 let offered = GENERATED_POOL_MAX_MACHINES;
593 let ceiling = offered.max(selected_max.unwrap_or(0));
594 let default_min = default_min.min(offered);
595 CapacityGroupScalePolicy::Autoscale {
596 min: ComputeChoiceRange {
597 min: default_min,
598 max: ceiling,
599 default: default_min,
600 },
601 max: ComputeChoiceRange {
602 min: default_min.max(1),
603 max: ceiling,
604 default: default_max.clamp(default_min.max(1), offered),
605 },
606 }
607}
608
609pub fn check_pool_capacity(
613 platform: Platform,
614 pool_id: &str,
615 selection: &ComputePoolSelection,
616 requirements: &WorkloadRequirements,
617) -> std::result::Result<(), String> {
618 let Some(spec) = selection
619 .machine()
620 .and_then(|machine| instance_catalog::find_instance_type(platform, machine))
621 else {
622 return Ok(());
624 };
625 let machines = selection.max_size();
626 let per_machine_cpu = instance_catalog::allocatable_cpu(spec);
627 let per_machine_memory = instance_catalog::allocatable_memory_bytes(spec);
628 if per_machine_cpu + f64::EPSILON < requirements.max_cpu_per_container
629 || per_machine_memory < requirements.max_memory_per_container
630 {
631 return Err(format!(
632 "Pool '{pool_id}' machine '{}' cannot fit one replica after reserving host resources",
633 spec.name,
634 ));
635 }
636 let cpu = f64::from(machines) * per_machine_cpu;
637 let memory = u64::from(machines) * per_machine_memory;
638 if cpu + f64::EPSILON >= requirements.total_cpu_at_desired
639 && memory >= requirements.total_memory_bytes_at_desired
640 {
641 return Ok(());
642 }
643 const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
644 Err(format!(
645 "Pool '{pool_id}' is too small for its workloads: {machines} x {} has {cpu:.2} vCPU and {:.1} GiB, and the workloads request {:.2} vCPU and {:.1} GiB at their desired replica counts",
646 spec.name,
647 memory as f64 / GIB,
648 requirements.total_cpu_at_desired,
649 requirements.total_memory_bytes_at_desired as f64 / GIB,
650 ))
651}
652
653fn collect_workload_groups(stack: &Stack) -> Result<HashMap<String, PlannedGroup>, ErrorData> {
654 let mut groups: HashMap<String, Vec<Workload>> = HashMap::new();
655
656 for entry in stack.resources.values() {
657 if let Some(container) = entry.config.downcast_ref::<Container>() {
658 groups
659 .entry(
660 container
661 .pool
662 .clone()
663 .unwrap_or_else(|| needed_container_pool(container).to_string()),
664 )
665 .or_default()
666 .push(Workload::from_container(container)?);
667 }
668 if let Some(daemon) = entry.config.downcast_ref::<Daemon>() {
669 if daemon.cluster.is_some() {
670 groups
671 .entry(daemon.pool.clone().unwrap_or_else(|| "general".to_string()))
672 .or_default()
673 .push(Workload::from_daemon(daemon)?);
674 }
675 }
676 }
677
678 let mut planned = HashMap::new();
679 for (pool_id, workloads) in groups {
680 let requirements = aggregate_workloads(&workloads);
681 let requires_failure_domain = workloads
682 .iter()
683 .any(|workload| workload.requires_failure_domain);
684 let min_size = default_min_machines(&requirements);
685 let max_size = default_max_machines(&requirements);
686 let rolling_update_machines = u32::from(workloads.iter().any(|w| w.starts_before_stop));
690 planned.insert(
691 pool_id,
692 PlannedGroup {
693 workloads: workloads.into_iter().map(|w| w.id).collect(),
694 workload_requirements: Some(requirements.clone()),
695 scale: CapacityGroupScalePolicy::from_selected_bounds(min_size, max_size),
697 requirements,
698 requires_failure_domain,
699 generated: true,
700 rolling_update_machines,
701 },
702 );
703 }
704 Ok(planned)
705}
706
707fn merge_explicit_compute_groups(
708 stack: &Stack,
709 groups: &mut HashMap<String, PlannedGroup>,
710) -> Result<(), ErrorData> {
711 for entry in stack.resources.values() {
712 let Some(cluster) = entry.config.downcast_ref::<crate::ComputeCluster>() else {
713 continue;
714 };
715 for group in &cluster.capacity_groups {
716 let explicit_requirements = profile_to_requirements(
717 group.profile.as_ref(),
718 group.nested_virtualization.unwrap_or(false),
719 );
720 let scale = group.scale_policy.clone().unwrap_or_else(|| {
721 CapacityGroupScalePolicy::from_selected_bounds(group.min_size, group.max_size)
722 });
723 groups
724 .entry(group.group_id.clone())
725 .and_modify(|planned| {
726 if group.instance_type.is_none() {
727 merge_requirements(&mut planned.requirements, &explicit_requirements);
728 } else {
729 planned.requirements.architecture = planned
736 .requirements
737 .architecture
738 .or(explicit_requirements.architecture);
739 planned.requirements.nested_virt |= explicit_requirements.nested_virt;
740 }
741 planned.scale = merge_scale_policy(&planned.scale, &scale);
742 planned.generated = false;
743 })
744 .or_insert_with(|| PlannedGroup {
745 workloads: Vec::new(),
746 workload_requirements: None,
747 scale,
748 requirements: explicit_requirements,
749 requires_failure_domain: false,
750 generated: false,
751 rolling_update_machines: 0,
752 });
753 }
754 }
755 Ok(())
756}
757
758struct PoolRoom<'a> {
761 room: &'a dyn MachineRoom,
762 pool_id: &'a str,
763 machines: Option<u32>,
764}
765
766fn recommended_selection(
767 platform: Platform,
768 requirements: &WorkloadRequirements,
769 scale: &CapacityGroupScalePolicy,
770 requires_failure_domain: bool,
771 generated: bool,
772 machine_override: Option<&str>,
773 room: Option<PoolRoom>,
774) -> Result<ComputePoolSelection, ErrorData> {
775 let machine = match platform {
776 Platform::Aws | Platform::Gcp | Platform::Azure => Some(
777 match match room {
778 Some(pool_room) => {
779 let launch_machines = pool_room
782 .machines
783 .unwrap_or(match scale {
784 CapacityGroupScalePolicy::Fixed { machines } => machines.default,
785 CapacityGroupScalePolicy::Autoscale { min, .. } => min.default,
786 })
787 .max(1);
788 instance_catalog::select_instance_type_with_room(
789 platform,
790 requirements,
791 launch_machines,
792 &|spec, machines| {
793 pool_room.room.has_room(pool_room.pool_id, spec, machines)
794 },
795 )
796 }
797 None => instance_catalog::select_instance_type(platform, requirements),
798 } {
799 Ok(selection) => selection.instance_type.to_string(),
800 Err(message) => {
801 let fallback = machine_override
805 .and_then(|machine| instance_catalog::find_instance_type(platform, machine))
806 .filter(|spec| {
807 instance_satisfies(
808 spec,
809 requirements,
810 requirements.architecture.unwrap_or(spec.architecture),
811 )
812 });
813 fallback.map(|spec| spec.name.to_string()).ok_or_else(|| {
814 AlienError::new(ErrorData::GenericError {
815 message: format!("Failed to select {platform} machine: {message}"),
816 })
817 })?
818 }
819 },
820 ),
821 Platform::Local | Platform::Kubernetes | Platform::Machines | Platform::Test => None,
822 };
823
824 let failure_domains = (requires_failure_domain
825 && matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure))
826 .then(default_persistent_failure_domains);
827
828 match scale {
829 CapacityGroupScalePolicy::Fixed { machines } => Ok(ComputePoolSelection::Fixed {
830 machines: machines.default.max(1),
831 machine,
832 failure_domains,
833 data_disk_gib: None,
834 }),
835 CapacityGroupScalePolicy::Autoscale { min, max }
837 if generated && min.default == max.default =>
838 {
839 Ok(ComputePoolSelection::Fixed {
840 machines: min.default.max(1),
841 machine,
842 failure_domains,
843 data_disk_gib: None,
844 })
845 }
846 CapacityGroupScalePolicy::Autoscale { min, max } => Ok(ComputePoolSelection::Autoscale {
847 min: min.default,
848 max: max.default.max(min.default),
849 machine,
850 failure_domains,
851 data_disk_gib: None,
852 }),
853 }
854}
855
856pub fn validate_compute_pool_selection(
859 platform: Platform,
860 pool_id: &str,
861 selection: &ComputePoolSelection,
862 requirements: &WorkloadRequirements,
863 scale: &CapacityGroupScalePolicy,
864) -> Vec<String> {
865 let mut errors = Vec::new();
866 if let Err(message) = selection.validate() {
867 errors.push(message);
868 }
869 if let Err(message) = validate_selection_against_scale(selection, scale) {
870 errors.push(format!("Pool '{pool_id}' {message}"));
871 }
872 if matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure) {
873 match selection.machine() {
874 Some(machine) => match instance_catalog::find_instance_type(platform, machine) {
875 Some(spec) => {
876 let architecture = requirements.architecture.unwrap_or(spec.architecture);
877 if !instance_satisfies(spec, requirements, architecture) {
878 errors.push(format!(
879 "{} machine '{}' does not satisfy pool '{}' requirements",
880 platform, machine, pool_id
881 ));
882 }
883 }
884 None => errors.push(format!(
885 "Unknown {} machine '{}' for pool '{}'",
886 platform, machine, pool_id
887 )),
888 },
889 None => errors.push(format!(
890 "Pool '{}' requires a provider machine on {}",
891 pool_id, platform
892 )),
893 }
894 }
895 errors
896}
897
898pub fn capacity_group_requirements(group: &CapacityGroup) -> WorkloadRequirements {
900 profile_to_requirements(
901 group.profile.as_ref(),
902 group.nested_virtualization.unwrap_or(false),
903 )
904}
905
906fn machine_options(
907 platform: Platform,
908 requirements: &WorkloadRequirements,
909 workload_requirements: Option<&WorkloadRequirements>,
910 selected_machine: Option<&str>,
911 recommended_machine: Option<&str>,
912) -> Result<Vec<ComputeMachineOption>, ErrorData> {
913 if !matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure) {
914 return Ok(Vec::new());
915 }
916 let resolved_architecture = requirements
917 .architecture
918 .or_else(|| {
919 selected_machine.and_then(|machine| {
920 instance_catalog::find_instance_type(platform, machine)
921 .map(|spec| spec.architecture)
922 })
923 })
924 .or_else(|| {
925 recommended_machine
926 .and_then(|machine| instance_catalog::find_instance_type(platform, machine))
927 .map(|spec| spec.architecture)
928 })
929 .ok_or_else(|| {
930 AlienError::new(ErrorData::GenericError {
931 message: format!("Selected {platform} machine has no CPU architecture"),
932 })
933 })?;
934
935 Ok(instance_catalog::catalog_for_platform(platform)
936 .into_iter()
937 .map(|spec| {
938 let unavailable_reasons = unavailable_reasons(
939 spec,
940 requirements,
941 resolved_architecture,
942 match workload_requirements {
943 Some(workloads) => Fit::OneReplica(workloads),
944 None => Fit::Hardware,
945 },
946 );
947 ComputeMachineOption {
948 machine: spec.name.to_string(),
949 series: spec.series.to_string(),
950 category: spec.family,
951 label: spec.label.to_string(),
952 profile: spec
953 .to_machine_profile_for_storage(requirements.max_ephemeral_storage_bytes),
954 nested_virtualization: spec.is_nested_virt_capable(),
955 local_storage: (spec.local_disk_bytes > 0).then_some(spec.local_disk_bytes),
956 available: unavailable_reasons.is_empty(),
957 unavailable_reasons,
958 recommended: Some(spec.name) == recommended_machine
959 || Some(spec.name) == selected_machine,
960 primary: spec.primary,
961 }
962 })
963 .collect())
964}
965
966fn instance_satisfies(
967 spec: &instance_catalog::InstanceTypeSpec,
968 requirements: &WorkloadRequirements,
969 resolved_architecture: Architecture,
970) -> bool {
971 unavailable_reasons(spec, requirements, resolved_architecture, Fit::Hardware).is_empty()
972}
973
974#[derive(Clone, Copy)]
976enum Fit<'a> {
977 Hardware,
980 OneReplica(&'a WorkloadRequirements),
984}
985
986fn unavailable_reasons(
989 spec: &instance_catalog::InstanceTypeSpec,
990 requirements: &WorkloadRequirements,
991 resolved_architecture: Architecture,
992 fit: Fit<'_>,
993) -> Vec<MachineUnavailableReason> {
994 let mut reasons = Vec::new();
995 if spec.architecture != resolved_architecture {
996 reasons.push(MachineUnavailableReason::Architecture);
997 }
998 if requirements.nested_virt && !spec.is_nested_virt_capable() {
999 reasons.push(MachineUnavailableReason::NestedVirtualization);
1000 }
1001 let mut cpu_fits = spec.vcpu >= requirements.max_cpu_per_container.ceil() as u32;
1002 let mut memory_fits = spec.memory_bytes >= requirements.max_memory_per_container;
1003 if let Fit::OneReplica(workloads) = fit {
1004 cpu_fits &= instance_catalog::allocatable_cpu(spec) + f64::EPSILON
1005 >= workloads.max_cpu_per_container;
1006 memory_fits &=
1007 instance_catalog::allocatable_memory_bytes(spec) >= workloads.max_memory_per_container;
1008 }
1009 if !cpu_fits {
1010 reasons.push(MachineUnavailableReason::Cpu);
1011 }
1012 if !memory_fits {
1013 reasons.push(MachineUnavailableReason::Memory);
1014 }
1015 let storage_fits = if spec.has_configurable_ephemeral_storage() {
1016 crate::instance_catalog::max_configurable_ephemeral_storage_bytes(spec.platform)
1017 .is_some_and(|max| requirements.max_ephemeral_storage_bytes <= max)
1018 } else {
1019 spec.ephemeral_storage_bytes >= requirements.max_ephemeral_storage_bytes
1020 };
1021 if !storage_fits {
1022 reasons.push(MachineUnavailableReason::EphemeralStorage);
1023 }
1024 let gpu_fits = match (&requirements.gpu, spec.gpu) {
1025 (Some(required), Some(actual)) => {
1026 (required.gpu_type == "any" || required.gpu_type == actual.gpu_type)
1027 && actual.count >= required.count
1028 }
1029 (Some(_), None) => false,
1030 (None, _) => true,
1031 };
1032 if !gpu_fits {
1033 reasons.push(MachineUnavailableReason::Gpu);
1034 }
1035 reasons
1036}
1037
1038#[derive(Debug, Clone)]
1039struct Workload {
1040 id: String,
1041 cpu: f64,
1042 memory_bytes: u64,
1043 desired_replicas: f64,
1044 max_replicas: f64,
1045 ephemeral_storage_bytes: u64,
1046 gpu: Option<GpuSpec>,
1047 requires_failure_domain: bool,
1048 starts_before_stop: bool,
1050}
1051
1052impl Workload {
1053 fn from_container(container: &Container) -> Result<Self, ErrorData> {
1054 let cpu = parse_cpu(&container.id, &container.cpu)?;
1055 let memory_bytes = parse_memory(&container.id, &container.memory)?;
1056 let desired_replicas = container
1057 .autoscaling
1058 .as_ref()
1059 .map(|a| a.desired)
1060 .or(container.replicas)
1061 .unwrap_or(1) as f64;
1062 let max_replicas = container
1063 .autoscaling
1064 .as_ref()
1065 .map(|a| a.max)
1066 .or(container.replicas)
1067 .unwrap_or(1) as f64;
1068 let ephemeral_storage_bytes = container
1069 .ephemeral_storage
1070 .as_deref()
1071 .map(instance_catalog::parse_memory_bytes)
1072 .transpose()
1073 .map_err(|message| {
1074 AlienError::new(ErrorData::GenericError {
1075 message: format!(
1076 "Failed to parse ephemeral storage for '{}': {message}",
1077 container.id
1078 ),
1079 })
1080 })?
1081 .unwrap_or(0);
1082
1083 Ok(Self {
1084 id: container.id.clone(),
1085 cpu,
1086 memory_bytes,
1087 desired_replicas,
1088 max_replicas,
1089 ephemeral_storage_bytes,
1090 gpu: container.gpu.as_ref().map(|gpu| GpuSpec {
1091 gpu_type: gpu.gpu_type.clone(),
1092 count: gpu.count,
1093 }),
1094 requires_failure_domain: container.stateful && container.persistent_storage.is_some(),
1095 starts_before_stop: !container.stateful,
1096 })
1097 }
1098
1099 fn from_daemon(daemon: &Daemon) -> Result<Self, ErrorData> {
1100 Ok(Self {
1101 id: daemon.id.clone(),
1102 cpu: parse_cpu(&daemon.id, &daemon.cpu)?,
1103 memory_bytes: parse_memory(&daemon.id, &daemon.memory)?,
1104 desired_replicas: 1.0,
1105 max_replicas: 1.0,
1106 ephemeral_storage_bytes: 0,
1107 gpu: None,
1108 requires_failure_domain: false,
1109 starts_before_stop: false,
1110 })
1111 }
1112}
1113
1114fn parse_cpu(resource_id: &str, spec: &ResourceSpec) -> Result<f64, ErrorData> {
1115 instance_catalog::parse_cpu(&spec.desired).map_err(|message| {
1116 AlienError::new(ErrorData::GenericError {
1117 message: format!(
1118 "Failed to parse CPU requirement '{}' for '{}': {message}",
1119 spec.desired, resource_id
1120 ),
1121 })
1122 })
1123}
1124
1125fn parse_memory(resource_id: &str, spec: &ResourceSpec) -> Result<u64, ErrorData> {
1126 instance_catalog::parse_memory_bytes(&spec.desired).map_err(|message| {
1127 AlienError::new(ErrorData::GenericError {
1128 message: format!(
1129 "Failed to parse memory requirement '{}' for '{}': {message}",
1130 spec.desired, resource_id
1131 ),
1132 })
1133 })
1134}
1135
1136fn aggregate_workloads(workloads: &[Workload]) -> WorkloadRequirements {
1137 let mut requirements = default_requirements();
1138 requirements.total_cpu_at_desired = 0.0;
1139 requirements.total_memory_bytes_at_desired = 0;
1140 requirements.total_cpu_at_max = 0.0;
1141 requirements.total_memory_bytes_at_max = 0;
1142 requirements.max_cpu_per_container = 0.0;
1143 requirements.max_memory_per_container = 0;
1144 requirements.max_ephemeral_storage_bytes = 0;
1145 requirements.gpu = None;
1146
1147 for workload in workloads {
1148 requirements.total_cpu_at_desired += workload.cpu * workload.desired_replicas;
1149 requirements.total_cpu_at_max += workload.cpu * workload.max_replicas;
1150 requirements.total_memory_bytes_at_desired +=
1151 (workload.memory_bytes as f64 * workload.desired_replicas) as u64;
1152 requirements.total_memory_bytes_at_max +=
1153 (workload.memory_bytes as f64 * workload.max_replicas) as u64;
1154 requirements.max_cpu_per_container = requirements.max_cpu_per_container.max(workload.cpu);
1155 requirements.max_memory_per_container = requirements
1156 .max_memory_per_container
1157 .max(workload.memory_bytes);
1158 requirements.max_ephemeral_storage_bytes = requirements
1159 .max_ephemeral_storage_bytes
1160 .max(workload.ephemeral_storage_bytes);
1161 if requirements.gpu.is_none() {
1162 requirements.gpu = workload.gpu.clone();
1163 }
1164 }
1165 requirements
1166}
1167
1168fn default_requirements() -> WorkloadRequirements {
1169 WorkloadRequirements {
1170 total_cpu_at_desired: 1.0,
1171 total_memory_bytes_at_desired: 2 * 1024 * 1024 * 1024,
1172 total_cpu_at_max: 1.0,
1173 total_memory_bytes_at_max: 2 * 1024 * 1024 * 1024,
1174 max_cpu_per_container: 1.0,
1175 max_memory_per_container: 2 * 1024 * 1024 * 1024,
1176 max_ephemeral_storage_bytes: 0,
1177 gpu: None,
1178 architecture: None,
1179 nested_virt: false,
1180 }
1181}
1182
1183fn profile_to_requirements(
1184 profile: Option<&MachineProfile>,
1185 nested_virt: bool,
1186) -> WorkloadRequirements {
1187 let Some(profile) = profile else {
1188 return WorkloadRequirements {
1189 nested_virt,
1190 ..default_requirements()
1191 };
1192 };
1193 let cpu = instance_catalog::parse_cpu(&profile.cpu).unwrap_or(1.0);
1194 WorkloadRequirements {
1195 total_cpu_at_desired: cpu,
1196 total_memory_bytes_at_desired: profile.memory_bytes,
1197 total_cpu_at_max: cpu,
1198 total_memory_bytes_at_max: profile.memory_bytes,
1199 max_cpu_per_container: cpu,
1200 max_memory_per_container: profile.memory_bytes,
1201 max_ephemeral_storage_bytes: profile.ephemeral_storage_bytes,
1202 gpu: profile.gpu.clone(),
1203 architecture: profile.architecture,
1204 nested_virt,
1205 }
1206}
1207
1208fn merge_requirements(existing: &mut WorkloadRequirements, declared: &WorkloadRequirements) {
1209 existing.total_cpu_at_desired = existing
1210 .total_cpu_at_desired
1211 .max(declared.total_cpu_at_desired);
1212 existing.total_memory_bytes_at_desired = existing
1213 .total_memory_bytes_at_desired
1214 .max(declared.total_memory_bytes_at_desired);
1215 existing.total_cpu_at_max = existing.total_cpu_at_max.max(declared.total_cpu_at_max);
1216 existing.total_memory_bytes_at_max = existing
1217 .total_memory_bytes_at_max
1218 .max(declared.total_memory_bytes_at_max);
1219 existing.max_cpu_per_container = existing
1220 .max_cpu_per_container
1221 .max(declared.max_cpu_per_container);
1222 existing.max_memory_per_container = existing
1223 .max_memory_per_container
1224 .max(declared.max_memory_per_container);
1225 existing.max_ephemeral_storage_bytes = existing
1226 .max_ephemeral_storage_bytes
1227 .max(declared.max_ephemeral_storage_bytes);
1228 if existing.gpu.is_none() {
1229 existing.gpu = declared.gpu.clone();
1230 }
1231 existing.nested_virt |= declared.nested_virt;
1232 if existing.architecture.is_none() {
1233 existing.architecture = declared.architecture;
1234 }
1235}
1236
1237fn requirements_to_profile(requirements: &WorkloadRequirements) -> MachineProfile {
1238 MachineProfile {
1239 cpu: requirements.max_cpu_per_container.to_string(),
1240 memory_bytes: requirements.max_memory_per_container,
1241 ephemeral_storage_bytes: requirements.max_ephemeral_storage_bytes,
1242 architecture: requirements.architecture,
1243 gpu: requirements.gpu.clone(),
1244 data_disk: None,
1245 }
1246}
1247
1248fn merge_scale_policy(
1249 existing: &CapacityGroupScalePolicy,
1250 declared: &CapacityGroupScalePolicy,
1251) -> CapacityGroupScalePolicy {
1252 match (existing, declared) {
1253 (
1254 CapacityGroupScalePolicy::Fixed {
1255 machines: existing_machines,
1256 },
1257 CapacityGroupScalePolicy::Fixed {
1258 machines: declared_machines,
1259 },
1260 ) => CapacityGroupScalePolicy::Fixed {
1261 machines: merge_choice_range(existing_machines, declared_machines),
1262 },
1263 (_, declared) => declared.clone(),
1264 }
1265}
1266
1267fn merge_choice_range(
1268 existing: &ComputeChoiceRange,
1269 declared: &ComputeChoiceRange,
1270) -> ComputeChoiceRange {
1271 ComputeChoiceRange {
1272 min: existing.min.max(declared.min),
1273 max: existing.max.max(declared.max),
1274 default: declared.default,
1275 }
1276}
1277
1278fn validate_selection_against_scale(
1279 selection: &ComputePoolSelection,
1280 scale: &CapacityGroupScalePolicy,
1281) -> std::result::Result<(), String> {
1282 match (selection, scale) {
1285 (
1286 ComputePoolSelection::Fixed { machines, .. },
1287 CapacityGroupScalePolicy::Fixed { machines: allowed },
1288 ) => check_machine_count("fixed machine count", *machines, allowed.min, allowed.max),
1289 (
1290 ComputePoolSelection::Autoscale { min, max, .. },
1291 CapacityGroupScalePolicy::Autoscale {
1292 min: allowed_min,
1293 max: allowed_max,
1294 },
1295 ) => {
1296 check_machine_count("autoscale minimum", *min, allowed_min.min, allowed_min.max)?;
1297 check_machine_count("autoscale maximum", *max, allowed_max.min, allowed_max.max)
1298 }
1299 (
1300 ComputePoolSelection::Fixed { machines, .. },
1301 CapacityGroupScalePolicy::Autoscale {
1302 min: allowed_min,
1303 max: allowed_max,
1304 },
1305 ) => {
1306 let lowest = allowed_min.min.max(allowed_max.min);
1307 let highest = allowed_min.max.min(allowed_max.max);
1308 if lowest > highest {
1309 return Err(format!(
1310 "must use autoscale mode (minimum {}-{}, maximum {}-{})",
1311 allowed_min.min, allowed_min.max, allowed_max.min, allowed_max.max
1312 ));
1313 }
1314 check_machine_count("fixed machine count", *machines, lowest, highest)
1315 }
1316 (
1317 ComputePoolSelection::Autoscale { min, max, .. },
1318 CapacityGroupScalePolicy::Fixed { machines: allowed },
1319 ) => {
1320 if min != max {
1321 return Err(format!(
1322 "must use fixed mode with {}-{} machines; autoscale {min}-{max} is not allowed",
1323 allowed.min, allowed.max
1324 ));
1325 }
1326 check_machine_count("machine count", *min, allowed.min, allowed.max)
1327 }
1328 }
1329}
1330
1331fn check_machine_count(
1332 label: &str,
1333 value: u32,
1334 lowest: u32,
1335 highest: u32,
1336) -> std::result::Result<(), String> {
1337 if (lowest..=highest).contains(&value) {
1338 Ok(())
1339 } else {
1340 Err(format!(
1341 "{label} {value} is outside the allowed range {lowest}-{highest}"
1342 ))
1343 }
1344}
1345
1346fn needed_container_pool(container: &Container) -> &'static str {
1347 if container.stateful && container.persistent_storage.is_some() {
1348 return "stateful";
1349 }
1350 if container.gpu.is_some() {
1351 return "gpu";
1352 }
1353 if let Some(storage) = &container.ephemeral_storage {
1354 if instance_catalog::parse_memory_bytes(storage).unwrap_or(0) > 200 * 1024 * 1024 * 1024 {
1355 return "storage";
1356 }
1357 }
1358 "general"
1359}
1360
1361fn default_min_machines(requirements: &WorkloadRequirements) -> u32 {
1362 if requirements.total_cpu_at_desired > 0.0 || requirements.total_memory_bytes_at_desired > 0 {
1363 1
1364 } else {
1365 0
1366 }
1367}
1368
1369fn default_max_machines(requirements: &WorkloadRequirements) -> u32 {
1370 let min = default_min_machines(requirements);
1371 let by_cpu =
1372 (requirements.total_cpu_at_max / requirements.max_cpu_per_container.max(1.0)).ceil() as u32;
1373 let by_mem = requirements
1374 .total_memory_bytes_at_max
1375 .div_ceil(requirements.max_memory_per_container.max(1)) as u32;
1376 min.max(by_cpu).max(by_mem).max(1)
1377}
1378
1379#[cfg(test)]
1380mod tests {
1381 use super::*;
1382 use crate::{
1383 instance_catalog::Architecture, CapacityGroup, CapacityGroupScalePolicy,
1384 ComputeChoiceRange, ComputeCluster, ComputeSettings, ContainerCode, DaemonCode, Resource,
1385 ResourceEntry, ResourceLifecycle, Stack, Storage, Worker, WorkerCode,
1386 };
1387
1388 #[test]
1389 fn deployment_resources_drive_machine_planning_on_every_cloud() {
1390 let mut stack = stack_with_container();
1391 let container = stack
1392 .resources
1393 .get_mut("api")
1394 .unwrap()
1395 .config
1396 .downcast_mut::<Container>()
1397 .unwrap();
1398 container.resource_choices = Some(crate::ContainerResourceChoices {
1399 cpu: Some(crate::ResourceChoiceRange {
1400 min: "0.5".into(),
1401 max: "8".into(),
1402 default: "2".into(),
1403 }),
1404 memory: Some(crate::ResourceChoiceRange {
1405 min: "512Mi".into(),
1406 max: "16Gi".into(),
1407 default: "4Gi".into(),
1408 }),
1409 });
1410 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1411 "pools": { "general": { "mode": "fixed", "machines": 1 } },
1412 "containers": { "api": { "cpu": 8, "memory": "16Gi" } }
1413 }))
1414 .unwrap();
1415 for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1416 let default_plan = plan_compute(&stack, platform, None).unwrap();
1417 let selected_plan = plan_compute(&stack, platform, Some(&settings)).unwrap();
1418 let pool = &selected_plan.pools[0];
1419 assert!(pool.errors.is_empty(), "{platform}: {:?}", pool.errors);
1420 assert_eq!(pool.requirements.cpu, "8");
1421 assert_eq!(pool.requirements.memory_bytes, 16 * 1024 * 1024 * 1024);
1422 assert_ne!(
1423 pool.selected.machine(),
1424 default_plan.pools[0].selected.machine()
1425 );
1426 assert_eq!(selected_plan.containers[0].cpu.min, "8");
1427 assert_eq!(selected_plan.containers[0].memory.desired, "16Gi");
1428 assert_eq!(pool.selected.min_size(), 1);
1429 assert_eq!(pool.selected.max_size(), 1);
1430 }
1431 assert_eq!(
1432 settings.pools["general"].machine(),
1433 None,
1434 "resolving a plan must preserve automatic machine intent"
1435 );
1436 let original = stack.resources["api"]
1437 .config
1438 .downcast_ref::<Container>()
1439 .unwrap();
1440 assert_eq!(
1441 original.cpu.desired, "2",
1442 "planning must not mutate release defaults"
1443 );
1444 }
1445
1446 #[test]
1447 fn explicit_machine_can_fit_a_low_cpu_high_memory_workload() {
1448 let mut stack = stack_with_container();
1449 let container = stack
1450 .resources
1451 .get_mut("api")
1452 .unwrap()
1453 .config
1454 .downcast_mut::<Container>()
1455 .unwrap();
1456 container.cpu = ResourceSpec {
1457 min: "0.5".into(),
1458 desired: "0.5".into(),
1459 };
1460 container.memory = ResourceSpec {
1461 min: "8Gi".into(),
1462 desired: "8Gi".into(),
1463 };
1464 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1465 "pools": {"general":{"mode":"fixed","machines":1,"machine":"n2-standard-4"}}
1466 }))
1467 .unwrap();
1468 let plan = plan_compute(&stack, Platform::Gcp, Some(&settings)).unwrap();
1469 assert!(
1470 plan.pools[0].errors.is_empty(),
1471 "{:?}",
1472 plan.pools[0].errors
1473 );
1474 assert_eq!(plan.pools[0].selected.machine(), Some("n2-standard-4"));
1475 }
1476
1477 #[test]
1478 fn pin_must_leave_host_capacity_for_one_replica() {
1479 let mut stack = stack_with_container();
1480 stack
1481 .resources
1482 .get_mut("api")
1483 .unwrap()
1484 .config
1485 .downcast_mut::<Container>()
1486 .unwrap()
1487 .cpu = ResourceSpec {
1488 min: "4".into(),
1489 desired: "4".into(),
1490 };
1491 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1492 "pools":{"general":{"mode":"fixed","machines":1,"machine":"t3.xlarge"}}
1493 }))
1494 .unwrap();
1495 let plan = plan_compute(&stack, Platform::Aws, Some(&settings)).unwrap();
1496 assert!(
1497 plan.pools[0]
1498 .errors
1499 .iter()
1500 .any(|error| error.contains("host resources")),
1501 "{:?}",
1502 plan.pools[0].errors
1503 );
1504 }
1505
1506 #[test]
1507 fn valid_pin_does_not_require_automatic_recommendation_headroom() {
1508 let machine = instance_catalog::catalog_for_platform(Platform::Gcp)
1509 .into_iter()
1510 .max_by_key(|machine| machine.memory_bytes)
1511 .unwrap();
1512 let mut stack = stack_with_container();
1513 let container = stack
1514 .resources
1515 .get_mut("api")
1516 .unwrap()
1517 .config
1518 .downcast_mut::<Container>()
1519 .unwrap();
1520 container.cpu = ResourceSpec {
1521 min: "0.5".into(),
1522 desired: "0.5".into(),
1523 };
1524 let memory = instance_catalog::allocatable_memory_bytes(machine).to_string();
1525 container.memory = ResourceSpec {
1526 min: memory.clone(),
1527 desired: memory,
1528 };
1529 assert!(plan_compute(&stack, Platform::Gcp, None).is_err());
1530 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1531 "pools":{"general":{"mode":"fixed","machines":1,"machine":machine.name}}
1532 }))
1533 .unwrap();
1534 let plan = plan_compute(&stack, Platform::Gcp, Some(&settings)).unwrap();
1535 assert!(
1536 plan.pools[0].errors.is_empty(),
1537 "{:?}",
1538 plan.pools[0].errors
1539 );
1540 assert_eq!(plan.pools[0].selected.machine(), Some(machine.name));
1541 }
1542
1543 #[test]
1544 fn invalid_deployment_resources_fail_before_capacity_planning() {
1545 let mut stack = stack_with_container();
1546 stack
1547 .resources
1548 .get_mut("api")
1549 .unwrap()
1550 .config
1551 .downcast_mut::<Container>()
1552 .unwrap()
1553 .resource_choices = Some(crate::ContainerResourceChoices {
1554 cpu: Some(crate::ResourceChoiceRange {
1555 min: "0.5".into(),
1556 max: "4".into(),
1557 default: "2".into(),
1558 }),
1559 memory: Some(crate::ResourceChoiceRange {
1560 min: "512Mi".into(),
1561 max: "8Gi".into(),
1562 default: "4Gi".into(),
1563 }),
1564 });
1565 for selection in [
1566 serde_json::json!({"api":{"cpu": 0}}),
1567 serde_json::json!({"api":{"cpu": 5}}),
1568 serde_json::json!({"api":{"memory": "16Gi"}}),
1569 serde_json::json!({"api":{"memory": "NaNGi"}}),
1570 serde_json::json!({"api":{"memory": "-1Gi"}}),
1571 serde_json::json!({"missing":{"cpu": 1}}),
1572 ] {
1573 let settings: ComputeSettings =
1574 serde_json::from_value(serde_json::json!({"containers": selection})).unwrap();
1575 let error = plan_compute(&stack, Platform::Aws, Some(&settings)).unwrap_err();
1576 assert_eq!(error.code, "CONTAINER_RESOURCE_SELECTION_INVALID");
1577 }
1578 }
1579
1580 #[test]
1581 fn deployment_volume_selection_is_applied_without_changing_release_defaults() {
1582 let mut release = stack_with_container();
1583 release
1584 .resources
1585 .get_mut("api")
1586 .unwrap()
1587 .config
1588 .downcast_mut::<Container>()
1589 .unwrap()
1590 .persistent_storage = Some(crate::PersistentStorage {
1591 size: "20Gi".into(),
1592 mount_path: "/data".into(),
1593 backups: crate::VolumeBackups::default(),
1594 encryption_key: None,
1595 });
1596 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1597 "containers": {"api": {"volumeSizeGib": 40}}
1598 }))
1599 .unwrap();
1600 let mut deployment = release.clone();
1601 crate::container_resources::resolve_container_resources(&mut deployment, Some(&settings))
1602 .unwrap();
1603 let volume = |stack: &Stack| {
1604 stack.resources["api"]
1605 .config
1606 .downcast_ref::<Container>()
1607 .unwrap()
1608 .persistent_storage
1609 .as_ref()
1610 .unwrap()
1611 .size
1612 .clone()
1613 };
1614 assert_eq!(volume(&deployment), "40Gi");
1615 assert_eq!(volume(&release), "20Gi");
1616 let mut equivalent = release.clone();
1617 equivalent
1618 .resources
1619 .get_mut("api")
1620 .unwrap()
1621 .config
1622 .downcast_mut::<Container>()
1623 .unwrap()
1624 .persistent_storage
1625 .as_mut()
1626 .unwrap()
1627 .size = "1Ti".into();
1628 let same_capacity: ComputeSettings = serde_json::from_value(serde_json::json!({
1629 "containers": {"api": {"volumeSizeGib": 1024}}
1630 }))
1631 .unwrap();
1632 crate::container_resources::resolve_container_resources(
1633 &mut equivalent,
1634 Some(&same_capacity),
1635 )
1636 .unwrap();
1637 assert_eq!(
1638 volume(&equivalent),
1639 "1Ti",
1640 "equivalent selections preserve PVC quantities"
1641 );
1642 crate::container_resources::resolve_container_resources(&mut deployment, Some(&settings))
1643 .unwrap();
1644 assert_eq!(volume(&deployment), "40Gi");
1645 let smaller_initial: ComputeSettings = serde_json::from_value(serde_json::json!({
1646 "containers": {"api": {"volumeSizeGib": 10}}
1647 }))
1648 .unwrap();
1649 crate::container_resources::resolve_container_resources(
1650 &mut release.clone(),
1651 Some(&smaller_initial),
1652 )
1653 .unwrap();
1654 let mut installed = StackState::new(Platform::Aws);
1655 installed.resources.insert(
1656 "api".into(),
1657 crate::StackResourceState::new_pending(
1658 "Container".into(),
1659 deployment.resources["api"].config.clone(),
1660 None,
1661 vec![],
1662 ),
1663 );
1664 let shrinking: ComputeSettings = serde_json::from_value(serde_json::json!({
1665 "containers": {"api": {"volumeSizeGib": 30}}
1666 }))
1667 .unwrap();
1668 let error =
1669 plan_compute_with_state(&release, Platform::Aws, Some(&shrinking), Some(&installed))
1670 .unwrap_err();
1671 assert_eq!(error.code, "CONTAINER_RESOURCE_SELECTION_INVALID");
1672 assert!(error.to_string().contains("cannot shrink from 40 to 30"));
1673 let imported: ComputeSettings = serde_json::from_value(serde_json::json!({
1674 "containers": {"api": {"volumeSizeGib": "40"}}
1675 }))
1676 .unwrap();
1677 assert_eq!(imported.containers["api"].volume_size_gib, Some(40));
1678 for value in [
1679 serde_json::json!(-1),
1680 serde_json::json!(1.5),
1681 serde_json::json!("4294967296"),
1682 ] {
1683 assert!(
1684 serde_json::from_value::<ComputeSettings>(serde_json::json!({
1685 "containers": {"api": {"volumeSizeGib": value}}
1686 }))
1687 .is_err()
1688 );
1689 }
1690 for (platform, size) in [(Platform::Gcp, 9), (Platform::Azure, 32768)] {
1691 let invalid: ComputeSettings = serde_json::from_value(serde_json::json!({
1692 "containers": {"api": {"volumeSizeGib": size}}
1693 }))
1694 .unwrap();
1695 let error = plan_compute(&release, platform, Some(&invalid)).unwrap_err();
1696 assert_eq!(error.code, "CONTAINER_RESOURCE_SELECTION_INVALID");
1697 assert!(error.to_string().contains("must be between"));
1698 }
1699 for size in [0, 65537] {
1700 let invalid: ComputeSettings = serde_json::from_value(serde_json::json!({
1701 "containers": {"api": {"volumeSizeGib": size}}
1702 }))
1703 .unwrap();
1704 assert_eq!(
1705 crate::container_resources::resolve_container_resources(
1706 &mut release.clone(),
1707 Some(&invalid)
1708 )
1709 .unwrap_err()
1710 .code,
1711 "CONTAINER_RESOURCE_SELECTION_INVALID"
1712 );
1713 }
1714 assert_eq!(
1715 crate::container_resources::resolve_container_resources(
1716 &mut stack_with_container(),
1717 Some(&settings)
1718 )
1719 .unwrap_err()
1720 .code,
1721 "CONTAINER_RESOURCE_SELECTION_INVALID"
1722 );
1723 }
1724
1725 fn stack_with_volume(size: &str) -> Stack {
1726 let mut stack = stack_with_container();
1727 stack
1728 .resources
1729 .get_mut("api")
1730 .unwrap()
1731 .config
1732 .downcast_mut::<Container>()
1733 .unwrap()
1734 .persistent_storage = Some(crate::PersistentStorage {
1735 size: size.into(),
1736 mount_path: "/data".into(),
1737 backups: crate::VolumeBackups::default(),
1738 encryption_key: None,
1739 });
1740 stack
1741 }
1742
1743 fn installed_with_volume(platform: Platform, size: &str) -> StackState {
1744 let mut installed = StackState::new(platform);
1745 installed.resources.insert(
1746 "api".into(),
1747 crate::StackResourceState::new_pending(
1748 "Container".into(),
1749 stack_with_volume(size).resources["api"].config.clone(),
1750 None,
1751 vec![],
1752 ),
1753 );
1754 installed
1755 }
1756
1757 fn api_volume(plan: &ComputePlan) -> (Option<u32>, Option<u32>) {
1758 let api = plan
1759 .containers
1760 .iter()
1761 .find(|container| container.container_id == "api")
1762 .expect("api is planned");
1763 (api.volume_size_gib, api.minimum_volume_size_gib)
1764 }
1765
1766 #[test]
1770 fn a_lower_release_default_keeps_installed_volumes_without_a_selection() {
1771 for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
1772 let installed = installed_with_volume(platform, "30Gi");
1773 let plan = plan_compute_with_state(
1774 &stack_with_volume("20Gi"),
1775 platform,
1776 None,
1777 Some(&installed),
1778 )
1779 .expect("a lower release default keeps the installed volume");
1780 assert_eq!(api_volume(&plan), (Some(30), Some(30)), "{platform}");
1781
1782 let plan = plan_compute_with_state(
1783 &stack_with_volume("40Gi"),
1784 platform,
1785 None,
1786 Some(&installed),
1787 )
1788 .expect("a larger release default grows the volume");
1789 assert_eq!(api_volume(&plan), (Some(40), Some(30)), "{platform}");
1790
1791 let shrinking: ComputeSettings = serde_json::from_value(serde_json::json!({
1793 "containers": {"api": {"volumeSizeGib": 25}}
1794 }))
1795 .unwrap();
1796 let error = plan_compute_with_state(
1797 &stack_with_volume("20Gi"),
1798 platform,
1799 Some(&shrinking),
1800 Some(&installed),
1801 )
1802 .unwrap_err();
1803 assert!(
1804 error.to_string().contains("cannot shrink from 30 to 25"),
1805 "{error}"
1806 );
1807 }
1808 }
1809
1810 #[test]
1814 fn setup_source_volume_sizes_below_installed_keep_the_installed_size() {
1815 let mut installed = installed_with_volume(Platform::Aws, "30Gi");
1816 let mut worker = stack_with_volume("10Gi").resources["api"].config.clone();
1817 worker
1818 .downcast_mut::<Container>()
1819 .unwrap()
1820 .persistent_storage = None;
1821 installed.resources.insert(
1822 "worker".into(),
1823 crate::StackResourceState::new_pending("Container".into(), worker, None, vec![]),
1824 );
1825 let mut settings: ComputeSettings = serde_json::from_value(serde_json::json!({
1826 "containers": {
1827 "api": {"volumeSizeGib": 25, "cpu": 2},
1828 "worker": {"volumeSizeGib": 5},
1829 "new": {"volumeSizeGib": 8}
1830 }
1831 }))
1832 .unwrap();
1833
1834 let kept = crate::container_resources::keep_volume_sizes_over_setup_source(
1835 &mut settings,
1836 Some(&installed),
1837 None,
1838 );
1839
1840 assert_eq!(
1841 kept,
1842 vec![crate::container_resources::KeptVolumeSize {
1843 container_id: "api".into(),
1844 requested_gib: 25,
1845 kept_gib: 30,
1846 }]
1847 );
1848 assert_eq!(settings.containers["api"].volume_size_gib, Some(30));
1849 assert_eq!(
1850 settings.containers["api"].cpu,
1851 Some(serde_json::Number::from(2))
1852 );
1853 assert_eq!(settings.containers["worker"].volume_size_gib, Some(5));
1854 assert_eq!(settings.containers["new"].volume_size_gib, Some(8));
1855 let plan = plan_compute_with_state(
1856 &stack_with_volume("20Gi"),
1857 Platform::Aws,
1858 Some(&ComputeSettings {
1859 containers: [("api".to_string(), settings.containers["api"].clone())].into(),
1860 ..Default::default()
1861 }),
1862 Some(&installed_with_volume(Platform::Aws, "30Gi")),
1863 )
1864 .expect("the kept size plans");
1865 assert_eq!(api_volume(&plan), (Some(30), Some(30)));
1866
1867 let mut growing: ComputeSettings = serde_json::from_value(serde_json::json!({
1868 "containers": {"api": {"volumeSizeGib": 35}}
1869 }))
1870 .unwrap();
1871 assert!(
1872 crate::container_resources::keep_volume_sizes_over_setup_source(
1873 &mut growing,
1874 Some(&installed),
1875 None,
1876 )
1877 .is_empty()
1878 );
1879 assert_eq!(growing.containers["api"].volume_size_gib, Some(35));
1880
1881 let chosen: ComputeSettings = serde_json::from_value(serde_json::json!({
1883 "containers": {"api": {"volumeSizeGib": 40}}
1884 }))
1885 .unwrap();
1886 let mut stale: ComputeSettings = serde_json::from_value(serde_json::json!({
1887 "containers": {"api": {"volumeSizeGib": 25}}
1888 }))
1889 .unwrap();
1890 let kept = crate::container_resources::keep_volume_sizes_over_setup_source(
1891 &mut stale,
1892 Some(&installed),
1893 Some(&chosen),
1894 );
1895 assert_eq!(kept[0].kept_gib, 40);
1896 assert_eq!(stale.containers["api"].volume_size_gib, Some(40));
1897
1898 let mut correction: ComputeSettings = serde_json::from_value(serde_json::json!({
1901 "containers": {"api": {"volumeSizeGib": 20}}
1902 }))
1903 .unwrap();
1904 for nothing_installed in [None, Some(&StackState::new(Platform::Aws))] {
1905 assert!(
1906 crate::container_resources::keep_volume_sizes_over_setup_source(
1907 &mut correction,
1908 nothing_installed,
1909 Some(&chosen),
1910 )
1911 .is_empty()
1912 );
1913 assert_eq!(correction.containers["api"].volume_size_gib, Some(20));
1914 }
1915 }
1916
1917 #[test]
1918 fn installed_storage_cannot_be_removed_or_remounted_on_any_provider() {
1919 for platform in [
1920 Platform::Aws,
1921 Platform::Gcp,
1922 Platform::Azure,
1923 Platform::Kubernetes,
1924 ] {
1925 let mut release = stack_with_container();
1926 release
1927 .resources
1928 .get_mut("api")
1929 .unwrap()
1930 .config
1931 .downcast_mut::<Container>()
1932 .unwrap()
1933 .persistent_storage = Some(crate::PersistentStorage {
1934 size: "20Gi".into(),
1935 mount_path: "/data".into(),
1936 backups: crate::VolumeBackups::default(),
1937 encryption_key: None,
1938 });
1939 let mut installed = StackState::new(platform);
1940 installed.resources.insert(
1941 "api".into(),
1942 crate::StackResourceState::new_pending(
1943 "Container".into(),
1944 release.resources["api"].config.clone(),
1945 None,
1946 vec![],
1947 ),
1948 );
1949 for remove in [false, true] {
1950 let mut desired = release.clone();
1951 let storage = &mut desired
1952 .resources
1953 .get_mut("api")
1954 .unwrap()
1955 .config
1956 .downcast_mut::<Container>()
1957 .unwrap()
1958 .persistent_storage;
1959 if remove {
1960 *storage = None;
1961 } else {
1962 storage.as_mut().unwrap().mount_path = "/other".into();
1963 }
1964 let error = plan_compute_with_state(&desired, platform, None, Some(&installed))
1965 .unwrap_err();
1966 assert_eq!(error.code, "CONTAINER_RESOURCE_SELECTION_INVALID");
1967 assert!(
1968 error.to_string().contains(if remove {
1969 "removing installed"
1970 } else {
1971 "mount path"
1972 }),
1973 "{error}"
1974 );
1975 }
1976 }
1977 }
1978
1979 #[test]
1980 fn release_volume_defaults_obey_provider_bounds_without_a_selection() {
1981 for (platform, size) in [(Platform::Gcp, "5Gi"), (Platform::Azure, "40000Gi")] {
1982 let mut stack = stack_with_container();
1983 stack
1984 .resources
1985 .get_mut("api")
1986 .unwrap()
1987 .config
1988 .downcast_mut::<Container>()
1989 .unwrap()
1990 .persistent_storage = Some(crate::PersistentStorage {
1991 size: size.into(),
1992 mount_path: "/data".into(),
1993 backups: crate::VolumeBackups::default(),
1994 encryption_key: None,
1995 });
1996 let error = plan_compute(&stack, platform, None).unwrap_err();
1997 assert_eq!(error.code, "CONTAINER_RESOURCE_SELECTION_INVALID");
1998 assert!(error.to_string().contains("must be between"));
1999 }
2000 }
2001
2002 #[test]
2003 fn volume_capacity_parsing_rejects_overflow_and_preserves_legacy_units() {
2004 use crate::container_resources::parse_volume_size_gib;
2005 for (value, size) in [
2006 ("20Gi", 20),
2007 ("20GiB", 20),
2008 ("20GB", 20),
2009 ("1Ti", 1024),
2010 ("1TB", 1000),
2011 ("1.5Ti", 1536),
2012 ("1536Mi", 2),
2013 ("0.5Gi", 1),
2014 ("1073741824", 1),
2015 ] {
2016 assert_eq!(parse_volume_size_gib(value).unwrap(), size);
2017 }
2018 for value in ["0Gi", "-1Gi", "NaNGi", "4294967295Ti", "65537Gi"] {
2019 assert!(parse_volume_size_gib(value).is_err(), "{value}");
2020 }
2021 }
2022
2023 fn stack_with_container() -> Stack {
2024 let container = Container::new("api".to_string())
2025 .code(ContainerCode::Image {
2026 image: "api:latest".to_string(),
2027 })
2028 .cpu(ResourceSpec {
2029 min: "1".to_string(),
2030 desired: "2".to_string(),
2031 })
2032 .memory(ResourceSpec {
2033 min: "2Gi".to_string(),
2034 desired: "4Gi".to_string(),
2035 })
2036 .permissions("api".to_string())
2037 .build();
2038 Stack {
2039 id: "test".to_string(),
2040 resources: [(
2041 "api".to_string(),
2042 ResourceEntry {
2043 config: Resource::new(container),
2044 lifecycle: ResourceLifecycle::Live,
2045 dependencies: Vec::new(),
2046 display_name: None,
2047 description: None,
2048 remote_access: false,
2049 enabled_when: None,
2050 },
2051 )]
2052 .into_iter()
2053 .collect(),
2054 permissions: crate::permissions::PermissionsConfig::default(),
2055 supported_platforms: None,
2056 inputs: vec![],
2057 dynamic_container_repositories: Vec::new(),
2058 dynamic_container_image_resources: Vec::new(),
2059 extensions: Vec::new(),
2060 operations: None,
2061 built_architectures: Default::default(),
2062 }
2063 }
2064
2065 #[test]
2066 fn serverless_workers_and_storage_do_not_allocate_machine_pools() {
2067 let mut stack = stack_with_container();
2068 stack.resources.clear();
2069 for (id, resource) in [
2070 (
2071 "api",
2072 Resource::new(
2073 Worker::new("api".to_string())
2074 .code(WorkerCode::Image {
2075 image: "example/worker:v1".to_string(),
2076 })
2077 .permissions("execution".to_string())
2078 .build(),
2079 ),
2080 ),
2081 (
2082 "data",
2083 Resource::new(Storage::new("data".to_string()).build()),
2084 ),
2085 ] {
2086 stack.resources.insert(
2087 id.to_string(),
2088 ResourceEntry {
2089 config: resource,
2090 lifecycle: ResourceLifecycle::Frozen,
2091 dependencies: Vec::new(),
2092 display_name: None,
2093 description: None,
2094 remote_access: false,
2095 enabled_when: None,
2096 },
2097 );
2098 }
2099
2100 for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
2101 let plan = plan_compute(&stack, platform, None).expect("plan should build");
2102 assert!(plan.pools.is_empty(), "serverless plan allocated {plan:?}");
2103 }
2104 }
2105
2106 #[test]
2107 fn empty_stack_does_not_allocate_machine_pools() {
2108 let mut stack = stack_with_container();
2109 stack.resources.clear();
2110 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2111 assert!(plan.pools.is_empty());
2112 }
2113
2114 #[test]
2115 fn explicit_cluster_without_workloads_only_plans_declared_pools() {
2116 let mut stack = stack_with_container();
2117 stack.resources.clear();
2118 let cluster = ComputeCluster::new("compute".to_string())
2119 .capacity_group(CapacityGroup {
2120 group_id: "batch".to_string(),
2121 instance_type: Some("t4g.medium".to_string()),
2122 profile: None,
2123 min_size: 1,
2124 max_size: 1,
2125 scale_policy: None,
2126 nested_virtualization: None,
2127 data_disk_gib_range: None,
2128 })
2129 .build();
2130 stack.resources.insert(
2131 "compute".to_string(),
2132 ResourceEntry {
2133 config: Resource::new(cluster),
2134 lifecycle: ResourceLifecycle::Frozen,
2135 dependencies: Vec::new(),
2136 display_name: None,
2137 description: None,
2138 remote_access: false,
2139 enabled_when: None,
2140 },
2141 );
2142
2143 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2144 assert_eq!(plan.pools.len(), 1);
2145 assert_eq!(plan.pools[0].pool_id, "batch");
2146 assert!(plan.pools[0].errors.is_empty());
2147 }
2148
2149 #[test]
2150 fn cloud_plan_recommends_provider_machine_without_mutating_selection() {
2151 let stack = stack_with_container();
2152
2153 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2154
2155 let pool = plan.pools.first().expect("general pool should exist");
2156 assert_eq!(pool.pool_id, "general");
2157 assert_eq!(pool.workloads, vec!["api"]);
2158 assert!(pool.selected.machine().is_some());
2159 assert!(pool.machines.iter().any(|machine| machine.recommended));
2160 }
2161
2162 #[test]
2163 fn cloud_plan_only_offers_machines_matching_the_default_image_target() {
2164 let stack = stack_with_container();
2165
2166 for platform in [Platform::Aws, Platform::Gcp, Platform::Azure] {
2167 let plan = plan_compute(&stack, platform, None).expect("plan should build");
2168 let pool = plan.pools.first().expect("general pool should exist");
2169 let expected = instance_catalog::default_architecture(platform)
2170 .expect("managed cloud should have a default architecture");
2171
2172 assert!(pool.machines.iter().any(|machine| machine.available));
2173 for machine in &pool.machines {
2174 let spec = instance_catalog::find_instance_type(platform, &machine.machine)
2175 .expect("every option is a catalog machine");
2176 if machine.available {
2177 assert_eq!(spec.architecture, expected, "{}", machine.machine);
2178 }
2179 assert_eq!(
2180 machine
2181 .unavailable_reasons
2182 .contains(&MachineUnavailableReason::Architecture),
2183 spec.architecture != expected,
2184 "{}",
2185 machine.machine
2186 );
2187 }
2188 }
2189 }
2190
2191 #[test]
2192 fn selected_machine_is_preserved_as_static_deployment_choice() {
2193 let stack = stack_with_container();
2194 let settings = ComputeSettings {
2195 containers: Default::default(),
2196 pools: [(
2197 "general".to_string(),
2198 ComputePoolSelection::Fixed {
2199 machines: 1,
2200 machine: Some("m7g.xlarge".to_string()),
2201 failure_domains: None,
2202 data_disk_gib: None,
2203 },
2204 )]
2205 .into_iter()
2206 .collect(),
2207 };
2208
2209 let plan = plan_compute(&stack, Platform::Aws, Some(&settings)).expect("plan should build");
2210
2211 let pool = plan.pools.first().expect("general pool should exist");
2212 assert_eq!(pool.selected.machine(), Some("m7g.xlarge"));
2213 assert!(pool.errors.is_empty());
2214 }
2215
2216 #[test]
2217 fn configurable_cloud_disk_satisfies_storage_above_fixed_local_catalog() {
2218 let mut stack = stack_with_container();
2219 let container = stack
2220 .resources
2221 .get_mut("api")
2222 .and_then(|entry| entry.config.downcast_mut::<Container>())
2223 .expect("test stack should contain a container");
2224 container.ephemeral_storage = Some("8000Gi".to_string());
2225 let settings = ComputeSettings {
2226 containers: Default::default(),
2227 pools: [(
2228 "storage".to_string(),
2229 ComputePoolSelection::Fixed {
2230 machines: 1,
2231 machine: Some("m8i.2xlarge".to_string()),
2232 failure_domains: None,
2233 data_disk_gib: None,
2234 },
2235 )]
2236 .into_iter()
2237 .collect(),
2238 };
2239
2240 let plan = plan_compute(&stack, Platform::Aws, Some(&settings)).expect("plan should build");
2241 let pool = plan.pools.first().expect("general pool should exist");
2242 assert!(pool.errors.is_empty());
2243 let selected = pool
2244 .machines
2245 .iter()
2246 .find(|option| option.machine == "m8i.2xlarge")
2247 .expect("selected machine should remain an option");
2248 assert_eq!(
2249 selected.profile.ephemeral_storage_bytes,
2250 8_000 * 1024 * 1024 * 1024
2251 );
2252 }
2253
2254 #[test]
2255 fn selected_machine_defines_architecture_when_workloads_do_not() {
2256 let stack = stack_with_container();
2257 let settings = ComputeSettings {
2258 containers: Default::default(),
2259 pools: [(
2260 "general".to_string(),
2261 ComputePoolSelection::Fixed {
2262 machines: 1,
2263 machine: Some("m7i.xlarge".to_string()),
2264 failure_domains: None,
2265 data_disk_gib: None,
2266 },
2267 )]
2268 .into_iter()
2269 .collect(),
2270 };
2271
2272 let plan = plan_compute(&stack, Platform::Aws, Some(&settings)).expect("plan should build");
2273
2274 let pool = plan.pools.first().expect("general pool should exist");
2275 assert!(pool.errors.is_empty());
2276 assert!(pool.machines.iter().any(|machine| machine.available));
2277 assert!(pool
2278 .machines
2279 .iter()
2280 .filter(|machine| machine.available)
2281 .all(|machine| machine.profile.architecture == Some(Architecture::X86_64)));
2282 }
2283
2284 #[test]
2285 fn graviton4_compute_machine_can_be_selected() {
2286 let stack = stack_with_container();
2287 let settings = ComputeSettings {
2288 containers: Default::default(),
2289 pools: [(
2290 "general".to_string(),
2291 ComputePoolSelection::Fixed {
2292 machines: 1,
2293 machine: Some("c8g.2xlarge".to_string()),
2294 failure_domains: None,
2295 data_disk_gib: None,
2296 },
2297 )]
2298 .into_iter()
2299 .collect(),
2300 };
2301
2302 let plan = plan_compute(&stack, Platform::Aws, Some(&settings)).expect("plan should build");
2303
2304 let pool = plan.pools.first().expect("general pool should exist");
2305 assert!(pool.errors.is_empty(), "{:?}", pool.errors);
2306 let selected = pool
2307 .machines
2308 .iter()
2309 .find(|option| option.machine == "c8g.2xlarge")
2310 .expect("selected machine should be offered");
2311 assert!(selected.recommended);
2312 assert_eq!(selected.profile.architecture, Some(Architecture::Arm64));
2313 }
2314
2315 #[test]
2316 fn explicit_capacity_group_requirements_are_merged_with_workloads() {
2317 let mut stack = stack_with_container();
2318 let cluster = ComputeCluster::new("compute".to_string())
2319 .capacity_group(CapacityGroup {
2320 group_id: "general".to_string(),
2321 instance_type: None,
2322 profile: Some(MachineProfile {
2323 cpu: "4".to_string(),
2324 memory_bytes: 16 * 1024 * 1024 * 1024,
2325 ephemeral_storage_bytes: 20 * 1024 * 1024 * 1024,
2326 architecture: Some(Architecture::X86_64),
2327 gpu: None,
2328 data_disk: None,
2329 }),
2330 min_size: 2,
2331 max_size: 5,
2332 scale_policy: None,
2333 nested_virtualization: Some(true),
2334 data_disk_gib_range: None,
2335 })
2336 .build();
2337 stack.resources.insert(
2338 "compute".to_string(),
2339 ResourceEntry {
2340 config: Resource::new(cluster),
2341 lifecycle: ResourceLifecycle::Frozen,
2342 dependencies: Vec::new(),
2343 display_name: None,
2344 description: None,
2345 remote_access: false,
2346 enabled_when: None,
2347 },
2348 );
2349
2350 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2351
2352 let pool = plan.pools.first().expect("general pool should exist");
2353 let machine = pool
2354 .selected
2355 .machine()
2356 .expect("AWS selection should include a machine");
2357 let spec = instance_catalog::find_instance_type(Platform::Aws, machine)
2358 .expect("selected machine should exist in the catalog");
2359 assert!(spec.is_nested_virt_capable());
2360 assert_eq!(pool.selected.min_size(), 2);
2361 assert_eq!(pool.selected.max_size(), 5);
2362 assert!(pool.errors.is_empty());
2363 }
2364
2365 #[test]
2371 fn available_machines_fit_one_replica_after_the_host_reserve() {
2372 let mut stack = stack_with_container();
2373 stack
2374 .resources
2375 .get_mut("api")
2376 .unwrap()
2377 .config
2378 .downcast_mut::<Container>()
2379 .unwrap()
2380 .cpu = ResourceSpec {
2381 min: "4".into(),
2382 desired: "4".into(),
2383 };
2384 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2385 let available: Vec<_> = plan.pools[0]
2386 .machines
2387 .iter()
2388 .filter(|option| option.available)
2389 .map(|option| option.machine.clone())
2390 .collect();
2391 assert!(!available.is_empty());
2392 assert!(!available.contains(&"t3.xlarge".to_string()));
2393 for machine in available {
2394 let settings: ComputeSettings = serde_json::from_value(serde_json::json!({
2395 "pools":{"general":{"mode":"fixed","machines":1,"machine":machine}}
2396 }))
2397 .unwrap();
2398 let pinned = plan_compute(&stack, Platform::Aws, Some(&settings)).unwrap();
2399 assert!(
2400 pinned.pools[0].errors.is_empty(),
2401 "{machine} is listed as available: {:?}",
2402 pinned.pools[0].errors
2403 );
2404 }
2405 }
2406
2407 #[test]
2410 fn a_pool_without_workloads_keeps_its_own_machine_available() {
2411 let spec = instance_catalog::find_instance_type(Platform::Aws, "m7g.large").unwrap();
2412 let mut stack = stack_with_container();
2413 stack.resources.remove("api");
2414 stack.resources.insert(
2415 "compute".to_string(),
2416 ResourceEntry {
2417 config: Resource::new(
2418 ComputeCluster::new("compute".to_string())
2419 .capacity_group(CapacityGroup {
2420 group_id: "general".to_string(),
2421 instance_type: Some("m7g.large".to_string()),
2422 profile: Some(spec.to_machine_profile()),
2423 min_size: 1,
2424 max_size: 1,
2425 scale_policy: None,
2426 nested_virtualization: None,
2427 data_disk_gib_range: None,
2428 })
2429 .build(),
2430 ),
2431 lifecycle: ResourceLifecycle::Frozen,
2432 dependencies: Vec::new(),
2433 display_name: None,
2434 description: None,
2435 remote_access: false,
2436 enabled_when: None,
2437 },
2438 );
2439 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2440 let option = plan.pools[0]
2441 .machines
2442 .iter()
2443 .find(|option| option.machine == "m7g.large")
2444 .expect("m7g.large should be listed");
2445 assert!(option.available, "{:?}", option.unavailable_reasons);
2446 }
2447
2448 #[test]
2449 fn nested_pool_runs_on_a_chosen_bare_metal_machine() {
2450 let mut stack = stack_with_container();
2451 let cluster = ComputeCluster::new("compute".to_string())
2452 .capacity_group(CapacityGroup {
2453 group_id: "general".to_string(),
2454 instance_type: Some("c8id.metal-48xl".to_string()),
2455 profile: Some(MachineProfile {
2456 cpu: "4".to_string(),
2457 memory_bytes: 16 * 1024 * 1024 * 1024,
2458 ephemeral_storage_bytes: 20 * 1024 * 1024 * 1024,
2459 architecture: None,
2460 gpu: None,
2461 data_disk: None,
2462 }),
2463 min_size: 1,
2464 max_size: 1,
2465 scale_policy: None,
2466 nested_virtualization: Some(true),
2467 data_disk_gib_range: None,
2468 })
2469 .build();
2470 stack.resources.insert(
2471 "compute".to_string(),
2472 ResourceEntry {
2473 config: Resource::new(cluster),
2474 lifecycle: ResourceLifecycle::Frozen,
2475 dependencies: Vec::new(),
2476 display_name: None,
2477 description: None,
2478 remote_access: false,
2479 enabled_when: None,
2480 },
2481 );
2482
2483 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2484
2485 let pool = plan.pools.first().expect("general pool should exist");
2486 assert!(pool.errors.is_empty(), "{:?}", pool.errors);
2487 assert_eq!(pool.selected.machine(), Some("c8id.metal-48xl"));
2488 let option = pool
2489 .machines
2490 .iter()
2491 .find(|option| option.machine == "c8id.metal-48xl")
2492 .expect("bare metal is listed");
2493 assert!(option.available, "{:?}", option.unavailable_reasons);
2494 assert!(option.nested_virtualization);
2495 let recommended = pool.recommended.machine().expect("a machine is recommended");
2496 assert!(
2497 !instance_catalog::find_instance_type(Platform::Aws, recommended)
2498 .expect("recommended machine is in the catalog")
2499 .bare_metal,
2500 "{recommended} is bare metal"
2501 );
2502 }
2503
2504 #[test]
2505 fn nested_pool_without_architecture_plans_an_aws_machine() {
2506 let mut stack = stack_with_container();
2507 let cluster = ComputeCluster::new("compute".to_string())
2508 .capacity_group(CapacityGroup {
2509 group_id: "general".to_string(),
2510 instance_type: None,
2511 profile: Some(MachineProfile {
2512 cpu: "4".to_string(),
2513 memory_bytes: 16 * 1024 * 1024 * 1024,
2514 ephemeral_storage_bytes: 20 * 1024 * 1024 * 1024,
2515 architecture: None,
2516 gpu: None,
2517 data_disk: None,
2518 }),
2519 min_size: 1,
2520 max_size: 1,
2521 scale_policy: None,
2522 nested_virtualization: Some(true),
2523 data_disk_gib_range: None,
2524 })
2525 .build();
2526 stack.resources.insert(
2527 "compute".to_string(),
2528 ResourceEntry {
2529 config: Resource::new(cluster),
2530 lifecycle: ResourceLifecycle::Frozen,
2531 dependencies: Vec::new(),
2532 display_name: None,
2533 description: None,
2534 remote_access: false,
2535 enabled_when: None,
2536 },
2537 );
2538
2539 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2540
2541 let pool = plan.pools.first().expect("general pool should exist");
2542 assert!(pool.errors.is_empty(), "{:?}", pool.errors);
2543 let machine = pool
2544 .selected
2545 .machine()
2546 .expect("AWS selection should include a machine");
2547 let spec = instance_catalog::find_instance_type(Platform::Aws, machine)
2548 .expect("selected machine should exist in the catalog");
2549 assert!(
2550 spec.is_nested_virt_capable(),
2551 "{machine} is not nested-capable"
2552 );
2553 assert_eq!(spec.architecture, Architecture::X86_64);
2554
2555 let catalog = instance_catalog::catalog_for_platform(Platform::Aws);
2557 assert_eq!(
2558 pool.machines
2559 .iter()
2560 .map(|option| option.machine.as_str())
2561 .collect::<Vec<_>>(),
2562 catalog.iter().map(|spec| spec.name).collect::<Vec<_>>()
2563 );
2564 for (option, spec) in pool.machines.iter().zip(&catalog) {
2566 let fits = spec.is_nested_virt_capable()
2567 && spec.architecture == Architecture::X86_64
2568 && spec.vcpu >= 4
2569 && spec.memory_bytes >= 16 * GIB
2570 && (spec.has_configurable_ephemeral_storage()
2571 || spec.ephemeral_storage_bytes >= 20 * GIB);
2572 assert_eq!(option.available, fits, "{}", option.machine);
2573 assert_eq!(
2574 option.available,
2575 option.unavailable_reasons.is_empty(),
2576 "{}",
2577 option.machine
2578 );
2579 }
2580
2581 let option = |name: &str| {
2582 pool.machines
2583 .iter()
2584 .find(|option| option.machine == name)
2585 .unwrap_or_else(|| panic!("{name} should be listed"))
2586 };
2587 let reasons = |name: &str| option(name).unavailable_reasons.clone();
2588 assert_eq!(reasons("m8i.xlarge"), vec![]);
2589 assert_eq!(
2590 reasons("m8i.large"),
2591 vec![
2592 MachineUnavailableReason::Cpu,
2593 MachineUnavailableReason::Memory
2594 ]
2595 );
2596 assert_eq!(
2597 reasons("c8i.xlarge"),
2598 vec![MachineUnavailableReason::Memory]
2599 );
2600 assert_eq!(
2601 reasons("m7g.xlarge"),
2602 vec![
2603 MachineUnavailableReason::Architecture,
2604 MachineUnavailableReason::NestedVirtualization
2605 ]
2606 );
2607 assert_eq!(
2608 reasons("t3.xlarge"),
2609 vec![MachineUnavailableReason::NestedVirtualization]
2610 );
2611 assert_eq!(
2612 reasons("t4g.micro"),
2613 vec![
2614 MachineUnavailableReason::Architecture,
2615 MachineUnavailableReason::NestedVirtualization,
2616 MachineUnavailableReason::Cpu,
2617 MachineUnavailableReason::Memory
2618 ]
2619 );
2620
2621 let large = option("m8i.24xlarge");
2622 assert!(large.available);
2623 assert_eq!(large.series, "m8i");
2624 assert_eq!(large.category, InstanceFamily::GeneralPurpose);
2625 assert_eq!(large.label, "General purpose · Intel · 8th gen");
2626 assert!(large.nested_virtualization);
2627 assert_eq!(large.local_storage, None);
2628 let local = option("i7i.xlarge");
2629 assert!(local.available);
2630 assert_eq!(local.category, InstanceFamily::StorageOptimized);
2631 assert_eq!(local.local_storage, Some(893_592 * 1024 * 1024));
2633
2634 let wire = serde_json::to_value(large).expect("option should serialize");
2635 assert_eq!(wire["category"], "generalPurpose");
2636 assert_eq!(wire["nestedVirtualization"], true);
2637 assert_eq!(wire["unavailableReasons"], serde_json::json!([]));
2638 assert!(wire.get("localStorage").is_none());
2639 let wire = serde_json::to_value(option("m7g.xlarge")).expect("option should serialize");
2640 assert_eq!(wire["available"], false);
2641 assert_eq!(
2642 wire["unavailableReasons"],
2643 serde_json::json!(["architecture", "nestedVirtualization"])
2644 );
2645 assert_eq!(
2646 serde_json::to_value(local).expect("option should serialize")["localStorage"],
2647 893_592u64 * 1024 * 1024
2648 );
2649 }
2650
2651 const GIB: u64 = 1024 * 1024 * 1024;
2652
2653 fn stack_with_data_disk_pool(
2656 data_disk_gib: Option<u64>,
2657 range: Option<ComputeChoiceRange>,
2658 ) -> Stack {
2659 let mut stack = stack_with_container();
2660 let cluster = ComputeCluster::new("compute".to_string())
2661 .capacity_group(CapacityGroup {
2662 group_id: "general".to_string(),
2663 instance_type: None,
2664 profile: Some(MachineProfile {
2665 cpu: "2".to_string(),
2666 memory_bytes: 8 * GIB,
2667 ephemeral_storage_bytes: 20 * GIB,
2668 architecture: None,
2669 gpu: None,
2670 data_disk: data_disk_gib.map(|gib| crate::DataDiskRequirement {
2671 size_bytes: gib * GIB,
2672 }),
2673 }),
2674 min_size: 1,
2675 max_size: 1,
2676 scale_policy: None,
2677 nested_virtualization: None,
2678 data_disk_gib_range: range,
2679 })
2680 .build();
2681 stack.resources.insert(
2682 "compute".to_string(),
2683 ResourceEntry {
2684 config: Resource::new(cluster),
2685 lifecycle: ResourceLifecycle::Frozen,
2686 dependencies: Vec::new(),
2687 display_name: None,
2688 description: None,
2689 remote_access: false,
2690 enabled_when: None,
2691 },
2692 );
2693 stack
2694 }
2695
2696 fn data_disk_selection(data_disk_gib: Option<u32>) -> ComputeSettings {
2697 ComputeSettings {
2698 pools: [(
2699 "general".to_string(),
2700 ComputePoolSelection::Fixed {
2701 machines: 1,
2702 machine: None,
2703 failure_domains: None,
2704 data_disk_gib,
2705 },
2706 )]
2707 .into_iter()
2708 .collect(),
2709 containers: HashMap::new(),
2710 }
2711 }
2712
2713 fn general_pool(plan: &ComputePlan) -> &ComputePoolPlan {
2714 plan.pools
2715 .iter()
2716 .find(|pool| pool.pool_id == "general")
2717 .expect("general pool should be planned")
2718 }
2719
2720 #[test]
2721 fn a_deployment_chooses_its_data_disk_within_the_declared_range() {
2722 let range = ComputeChoiceRange {
2723 min: 0,
2724 max: 4096,
2725 default: 200,
2726 };
2727 let stack = stack_with_data_disk_pool(Some(200), Some(range));
2728 for platform in [Platform::Aws, Platform::Machines] {
2729 for (selected, expected_gib) in [(None, 200), (Some(50), 50), (Some(0), 0)] {
2730 let settings = data_disk_selection(selected);
2731 let plan = plan_compute(&stack, platform, Some(&settings)).expect("plan");
2732 let pool = general_pool(&plan);
2733 assert!(
2734 pool.errors.is_empty(),
2735 "{platform} {selected:?}: {:?}",
2736 pool.errors
2737 );
2738 assert_eq!(
2739 pool.data_disk,
2740 Some(ComputePoolDataDiskPlan {
2741 min_gib: 0,
2742 max_gib: 4096,
2743 default_gib: 200,
2744 selected_gib: expected_gib,
2745 }),
2746 "{platform} {selected:?}"
2747 );
2748 assert_eq!(pool.selected.data_disk_gib(), selected, "{platform}");
2750 }
2751
2752 let settings = data_disk_selection(Some(5000));
2753 let plan = plan_compute(&stack, platform, Some(&settings)).expect("plan");
2754 assert_eq!(
2755 general_pool(&plan).errors,
2756 vec!["pool 'general' data disk must be between 0 and 4096 GiB; dataDiskGib 5000 is outside that range".to_string()],
2757 "{platform}"
2758 );
2759 }
2760 }
2761
2762 #[test]
2763 fn a_fixed_or_absent_data_disk_refuses_another_size() {
2764 let fixed = stack_with_data_disk_pool(Some(100), None);
2765 let plan = plan_compute(&fixed, Platform::Aws, None).expect("plan");
2766 assert_eq!(
2767 general_pool(&plan).data_disk,
2768 Some(ComputePoolDataDiskPlan {
2769 min_gib: 100,
2770 max_gib: 100,
2771 default_gib: 100,
2772 selected_gib: 100,
2773 })
2774 );
2775 let plan = plan_compute(&fixed, Platform::Aws, Some(&data_disk_selection(Some(200))))
2776 .expect("plan");
2777 assert_eq!(
2778 general_pool(&plan).errors,
2779 vec![
2780 "pool 'general' has a fixed 100 GiB data disk; dataDiskGib 200 cannot be chosen"
2781 .to_string()
2782 ]
2783 );
2784
2785 let absent = stack_with_data_disk_pool(None, None);
2786 let plan = plan_compute(&absent, Platform::Aws, Some(&data_disk_selection(Some(0))))
2787 .expect("plan");
2788 assert!(general_pool(&plan).errors.is_empty());
2789 assert_eq!(general_pool(&plan).data_disk, None);
2790 let plan = plan_compute(&absent, Platform::Aws, Some(&data_disk_selection(Some(50))))
2791 .expect("plan");
2792 assert_eq!(
2793 general_pool(&plan).errors,
2794 vec![
2795 "pool 'general' declares no data disk, so dataDiskGib 50 cannot be chosen"
2796 .to_string()
2797 ]
2798 );
2799 }
2800
2801 #[test]
2802 fn materialized_machine_profile_is_not_counted_as_workload_demand() {
2803 let mut stack = stack_with_container();
2804 let selected = instance_catalog::find_instance_type(Platform::Aws, "m7g.xlarge")
2805 .expect("machine should exist in catalog");
2806 let cluster = ComputeCluster::new("compute".to_string())
2807 .capacity_group(CapacityGroup {
2808 group_id: "general".to_string(),
2809 instance_type: Some(selected.name.to_string()),
2810 profile: Some(selected.to_machine_profile()),
2811 min_size: 1,
2812 max_size: 1,
2813 scale_policy: None,
2814 nested_virtualization: None,
2815 data_disk_gib_range: None,
2816 })
2817 .build();
2818 stack.resources.insert(
2819 "compute".to_string(),
2820 ResourceEntry {
2821 config: Resource::new(cluster),
2822 lifecycle: ResourceLifecycle::Frozen,
2823 dependencies: Vec::new(),
2824 display_name: None,
2825 description: None,
2826 remote_access: false,
2827 enabled_when: None,
2828 },
2829 );
2830
2831 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2832 let pool = plan.pools.first().expect("general pool should exist");
2833
2834 assert_eq!(pool.requirements.cpu, "2");
2835 assert_eq!(pool.requirements.memory_bytes, 4 * 1024 * 1024 * 1024);
2836 assert_eq!(pool.recommended.machine(), Some("m7g.xlarge"));
2837 assert!(pool
2838 .machines
2839 .iter()
2840 .any(|option| option.machine == "m7g.xlarge"));
2841 }
2842
2843 #[test]
2844 fn nested_x86_fixed_range_pool_preserves_bounds_and_rejects_graviton() {
2845 let daemon = Daemon::new("vm-runtime-loader".to_string())
2846 .code(DaemonCode::Image {
2847 image: "example.com/vm-runtime:latest".to_string(),
2848 })
2849 .cluster("vm-runtime".to_string())
2850 .cpu(ResourceSpec {
2851 min: "2".to_string(),
2852 desired: "2".to_string(),
2853 })
2854 .memory(ResourceSpec {
2855 min: "4Gi".to_string(),
2856 desired: "4Gi".to_string(),
2857 })
2858 .permissions("loader".to_string())
2859 .build();
2860 let cluster = ComputeCluster::new("vm-runtime".to_string())
2861 .capacity_group(CapacityGroup {
2862 group_id: "general".to_string(),
2863 instance_type: None,
2864 profile: Some(MachineProfile {
2865 cpu: "4".to_string(),
2866 memory_bytes: 16 * 1024 * 1024 * 1024,
2867 ephemeral_storage_bytes: 20 * 1024 * 1024 * 1024,
2868 architecture: Some(Architecture::X86_64),
2869 gpu: None,
2870 data_disk: None,
2871 }),
2872 min_size: 2,
2873 max_size: 2,
2874 scale_policy: Some(CapacityGroupScalePolicy::Fixed {
2875 machines: ComputeChoiceRange {
2876 min: 1,
2877 max: 5,
2878 default: 2,
2879 },
2880 }),
2881 nested_virtualization: Some(true),
2882 data_disk_gib_range: None,
2883 })
2884 .build();
2885 let stack = Stack {
2886 id: "vm-runtime".to_string(),
2887 resources: [
2888 (
2889 "vm-runtime-loader".to_string(),
2890 ResourceEntry {
2891 config: Resource::new(daemon),
2892 lifecycle: ResourceLifecycle::Live,
2893 dependencies: Vec::new(),
2894 display_name: None,
2895 description: None,
2896 remote_access: false,
2897 enabled_when: None,
2898 },
2899 ),
2900 (
2901 "vm-runtime".to_string(),
2902 ResourceEntry {
2903 config: Resource::new(cluster),
2904 lifecycle: ResourceLifecycle::Frozen,
2905 dependencies: Vec::new(),
2906 display_name: None,
2907 description: None,
2908 remote_access: false,
2909 enabled_when: None,
2910 },
2911 ),
2912 ]
2913 .into_iter()
2914 .collect(),
2915 permissions: crate::permissions::PermissionsConfig::default(),
2916 supported_platforms: None,
2917 inputs: vec![],
2918 dynamic_container_repositories: Vec::new(),
2919 dynamic_container_image_resources: Vec::new(),
2920 extensions: Vec::new(),
2921 operations: None,
2922 built_architectures: Default::default(),
2923 };
2924
2925 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
2926 let pool = plan.pools.first().expect("general pool should exist");
2927 assert_eq!(pool.recommended.machine(), Some("m8i.2xlarge"));
2928 assert_eq!(pool.recommended.min_size(), 2);
2929 assert_eq!(pool.recommended.max_size(), 2);
2930 assert_eq!(
2931 pool.scale,
2932 CapacityGroupScalePolicy::Fixed {
2933 machines: ComputeChoiceRange {
2934 min: 1,
2935 max: 5,
2936 default: 2,
2937 },
2938 }
2939 );
2940 let graviton = pool
2941 .machines
2942 .iter()
2943 .find(|option| option.machine == "m7g.2xlarge")
2944 .expect("every AWS machine is listed");
2945 assert!(!graviton.available);
2946 assert_eq!(
2947 graviton.unavailable_reasons,
2948 vec![
2949 MachineUnavailableReason::Architecture,
2950 MachineUnavailableReason::NestedVirtualization
2951 ]
2952 );
2953
2954 let invalid_settings = ComputeSettings {
2955 containers: Default::default(),
2956 pools: [(
2957 "general".to_string(),
2958 ComputePoolSelection::Fixed {
2959 machines: 2,
2960 machine: Some("m7g.2xlarge".to_string()),
2961 failure_domains: None,
2962 data_disk_gib: None,
2963 },
2964 )]
2965 .into_iter()
2966 .collect(),
2967 };
2968 let invalid_plan = plan_compute(&stack, Platform::Aws, Some(&invalid_settings))
2969 .expect("plan should build");
2970 assert_eq!(
2971 invalid_plan.pools[0].errors,
2972 vec!["aws machine 'm7g.2xlarge' does not satisfy pool 'general' requirements"]
2973 );
2974 }
2975
2976 fn declared_pool_errors(
2977 scale: CapacityGroupScalePolicy,
2978 selection: ComputePoolSelection,
2979 ) -> Vec<String> {
2980 let mut stack = stack_with_container();
2981 let cluster = ComputeCluster::new("compute".to_string())
2982 .capacity_group(CapacityGroup {
2983 group_id: "general".to_string(),
2984 instance_type: None,
2985 profile: None,
2986 min_size: scale.default_min_size(),
2987 max_size: scale.default_max_size(),
2988 scale_policy: Some(scale),
2989 nested_virtualization: None,
2990 data_disk_gib_range: None,
2991 })
2992 .build();
2993 stack.resources.insert(
2994 "compute".to_string(),
2995 ResourceEntry {
2996 config: Resource::new(cluster),
2997 lifecycle: ResourceLifecycle::Frozen,
2998 dependencies: Vec::new(),
2999 display_name: None,
3000 description: None,
3001 remote_access: false,
3002 enabled_when: None,
3003 },
3004 );
3005 let settings = ComputeSettings {
3006 containers: Default::default(),
3007 pools: [("general".to_string(), selection)].into_iter().collect(),
3008 };
3009 plan_compute(&stack, Platform::Aws, Some(&settings))
3010 .expect("plan should build")
3011 .pools
3012 .remove(0)
3013 .errors
3014 }
3015
3016 fn range(min: u32, max: u32, default: u32) -> ComputeChoiceRange {
3017 ComputeChoiceRange { min, max, default }
3018 }
3019
3020 #[test]
3021 fn generated_pool_offers_the_recommendation_as_a_default_not_a_bound() {
3022 let mut stack = stack_with_container();
3023 let api = stack
3024 .resources
3025 .get_mut("api")
3026 .and_then(|entry| entry.config.downcast_mut::<Container>())
3027 .expect("test stack should contain a container");
3028 api.autoscaling = Some(crate::ContainerAutoscaling {
3029 min: 1,
3030 desired: 1,
3031 max: 3,
3032 target_cpu_percent: Some(70.0),
3033 target_memory_percent: None,
3034 target_http_in_flight_per_replica: None,
3035 max_http_p95_latency_ms: None,
3036 });
3037
3038 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
3040 let pool = &plan.pools[0];
3041 assert_eq!(
3042 pool.scale,
3043 CapacityGroupScalePolicy::Autoscale {
3044 min: range(1, 100, 1),
3045 max: range(1, 100, 4),
3046 }
3047 );
3048 assert_eq!(
3049 (pool.recommended.min_size(), pool.recommended.max_size()),
3050 (1, 4)
3051 );
3052 assert!(pool.errors.is_empty());
3053 }
3054
3055 #[test]
3059 fn generated_pool_has_room_to_start_a_new_replica_before_stopping_the_old_one() {
3060 let plan =
3061 plan_compute(&stack_with_container(), Platform::Aws, None).expect("plan should build");
3062 let pool = &plan.pools[0];
3063 assert_eq!(
3064 pool.scale,
3065 CapacityGroupScalePolicy::Autoscale {
3066 min: range(1, 100, 1),
3067 max: range(1, 100, 2),
3068 }
3069 );
3070 assert_eq!(
3071 (pool.recommended.min_size(), pool.recommended.max_size()),
3072 (1, 2)
3073 );
3074 assert!(matches!(
3075 pool.recommended,
3076 ComputePoolSelection::Autoscale { .. }
3077 ));
3078 assert!(pool.errors.is_empty());
3079
3080 let mut stateful = stack_with_container();
3082 stateful
3083 .resources
3084 .get_mut("api")
3085 .and_then(|entry| entry.config.downcast_mut::<Container>())
3086 .expect("test stack should contain a container")
3087 .stateful = true;
3088 let stateful_plan =
3089 plan_compute(&stateful, Platform::Aws, None).expect("plan should build");
3090 let stateful_pool = &stateful_plan.pools[0];
3091 assert!(matches!(
3092 stateful_pool.recommended,
3093 ComputePoolSelection::Fixed { machines: 1, .. }
3094 ));
3095
3096 assert!(pool.recommended.machine().is_some());
3099 assert_eq!(
3100 pool.recommended.machine(),
3101 stateful_pool.recommended.machine()
3102 );
3103
3104 let saved = ComputeSettings {
3106 containers: Default::default(),
3107 pools: [(
3108 "general".to_string(),
3109 ComputePoolSelection::Fixed {
3110 machines: 1,
3111 machine: pool.recommended.machine().map(str::to_string),
3112 failure_domains: None,
3113 data_disk_gib: None,
3114 },
3115 )]
3116 .into_iter()
3117 .collect(),
3118 };
3119 let saved_plan = plan_compute(&stack_with_container(), Platform::Aws, Some(&saved))
3120 .expect("plan should build");
3121 assert_eq!(
3122 (
3123 saved_plan.pools[0].selected.min_size(),
3124 saved_plan.pools[0].selected.max_size()
3125 ),
3126 (1, 1)
3127 );
3128 }
3129
3130 #[test]
3133 fn generated_pool_beyond_the_offered_fleet_is_sized_to_fit_it() {
3134 let mut stack = stack_with_container();
3135 stack
3136 .resources
3137 .get_mut("api")
3138 .and_then(|entry| entry.config.downcast_mut::<Container>())
3139 .expect("test stack should contain a container")
3140 .replicas = Some(400);
3141
3142 let plan = plan_compute(&stack, Platform::Aws, None).expect("plan should build");
3143 let pool = &plan.pools[0];
3144 assert!(pool.errors.is_empty(), "{:?}", pool.errors);
3145 assert_eq!(pool.recommended.max_size(), GENERATED_POOL_MAX_MACHINES);
3146 }
3147
3148 #[test]
3149 fn generated_pool_rejects_a_fleet_too_small_for_desired_replicas() {
3150 let mut stack = stack_with_container();
3151 let api = stack
3152 .resources
3153 .get_mut("api")
3154 .and_then(|entry| entry.config.downcast_mut::<Container>())
3155 .expect("test stack should contain a container");
3156 api.replicas = Some(3);
3158 let selection = |machines| ComputeSettings {
3159 containers: Default::default(),
3160 pools: [(
3161 "general".to_string(),
3162 ComputePoolSelection::Fixed {
3163 machines,
3164 machine: Some("m7g.xlarge".to_string()),
3165 failure_domains: None,
3166 data_disk_gib: None,
3167 },
3168 )]
3169 .into_iter()
3170 .collect(),
3171 };
3172
3173 let errors = plan_compute(&stack, Platform::Aws, Some(&selection(1)))
3175 .expect("plan should build")
3176 .pools
3177 .remove(0)
3178 .errors;
3179 assert_eq!(errors.len(), 1, "{errors:?}");
3180 assert!(
3181 errors[0].starts_with(
3182 "Pool 'general' is too small for its workloads: 1 x m7g.xlarge has 3.50 vCPU"
3183 ),
3184 "{errors:?}"
3185 );
3186 assert!(errors[0].contains("request 6.00 vCPU"), "{errors:?}");
3187
3188 let errors = plan_compute(&stack, Platform::Aws, Some(&selection(2)))
3189 .expect("plan should build")
3190 .pools
3191 .remove(0)
3192 .errors;
3193 assert!(errors.is_empty(), "{errors:?}");
3194 }
3195
3196 #[test]
3197 fn fixed_and_equal_autoscale_bounds_are_interchangeable_for_declared_pools() {
3198 let fixed = |machines| ComputePoolSelection::Fixed {
3199 machines,
3200 machine: Some("m7g.xlarge".to_string()),
3201 failure_domains: None,
3202 data_disk_gib: None,
3203 };
3204 let autoscale = |min, max| ComputePoolSelection::Autoscale {
3205 min,
3206 max,
3207 machine: Some("m7g.xlarge".to_string()),
3208 failure_domains: None,
3209 data_disk_gib: None,
3210 };
3211 let declared_fixed = CapacityGroupScalePolicy::Fixed {
3212 machines: range(2, 4, 2),
3213 };
3214 let declared_autoscale = CapacityGroupScalePolicy::Autoscale {
3215 min: range(1, 3, 1),
3216 max: range(2, 6, 4),
3217 };
3218
3219 assert!(declared_pool_errors(declared_fixed.clone(), autoscale(3, 3)).is_empty());
3220 assert_eq!(
3221 declared_pool_errors(declared_fixed.clone(), autoscale(2, 4)),
3222 vec!["Pool 'general' must use fixed mode with 2-4 machines; autoscale 2-4 is not allowed"]
3223 );
3224 assert_eq!(
3225 declared_pool_errors(declared_fixed, autoscale(5, 5)),
3226 vec!["Pool 'general' machine count 5 is outside the allowed range 2-4"]
3227 );
3228
3229 assert!(declared_pool_errors(declared_autoscale.clone(), fixed(3)).is_empty());
3231 assert_eq!(
3232 declared_pool_errors(declared_autoscale.clone(), fixed(1)),
3233 vec!["Pool 'general' fixed machine count 1 is outside the allowed range 2-3"]
3234 );
3235 assert_eq!(
3236 declared_pool_errors(
3237 CapacityGroupScalePolicy::Autoscale {
3238 min: range(1, 1, 1),
3239 max: range(3, 5, 3),
3240 },
3241 fixed(1),
3242 ),
3243 vec!["Pool 'general' must use autoscale mode (minimum 1-1, maximum 3-5)"]
3244 );
3245 assert_eq!(
3246 declared_pool_errors(declared_autoscale, autoscale(1, 7)),
3247 vec!["Pool 'general' autoscale maximum 7 is outside the allowed range 2-6"]
3248 );
3249 }
3250
3251 #[test]
3252 fn local_plan_has_no_provider_machine_choices() {
3253 let stack = stack_with_container();
3254
3255 let plan = plan_compute(&stack, Platform::Local, None).expect("plan should build");
3256
3257 let pool = plan.pools.first().expect("general pool should exist");
3258 assert_eq!(pool.selected.machine(), None);
3259 assert!(pool.machines.is_empty());
3260 assert!(pool.errors.is_empty());
3261 }
3262}