//! Resource presets: how much of the host `leleka up` lets the engine take (`docs/deploy.md`, "Resource presets"). //! //! * `dedicated` (default): the host belongs to the runtime. The profile's VRAM budget as it is, engine defaults for the //! memory governor, CPU workers up to the useful maximum. //! * `workstation`: Docker, agents and the IDE share the machine. At least 4 cores (8 on hosts with more than 16) stay //! free of engine workers, the memory governor keeps 8-16 GiB of host RAM free (it sheds the prefix cache first), and //! about 4 GiB of VRAM is left to the desktop; the expert tier is sized from what remains. //! //! `compute` is a pure function of the host facts and the profile; `apply` writes the result into the profile and the //! engine environment. Explicit profile fields and command-line overrides always win over a preset. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use crate::{ facts::{Facts, Gpu}, profile::{ARCHIVE_BYTES, ExpertSource, KarSource, Profile}, }; const GIB: u64 = 1 << 30; const MIB: u64 = 1 << 20; /// The native expert pool refuses more than 15 workers, and fewer cost decode: on the 5090 replay (job 9p0) 8 workers decode 2.4 % slower than 15 /// (136.4 against 139.8 tok/s), so the useful maximum is the pool's limit. /// VRAM the desktop/browser keeps in the workstation preset. const MAX_USEFUL_WORKERS: u32 = 15; /// VRAM the desktop/browser keeps in the workstation preset. Every GiB taken from the expert tier costs decode: 3 GiB less (27 against 30 GiB) was /// 12 % slower on the 5090 replay (job 9p0: 119.6 against 139.8 tok/s), so the margin is the 2 GiB a desktop session needs. const WORKSTATION_VRAM_MARGIN_MIB: u64 = 2048; /// Resident host memory of a memfd-backed engine besides the archive (tokenizer, pinned buffers, CUDA host state). const ENGINE_EXTRA_BYTES: u64 = 3 * GIB; /// Host memory of an engine with the resident expert source: the page-locked RAM copy of the routed experts plus rings, staging pools and pins /// (53.54 GiB, the fixed footprint the engine's own budget reported in the live restart check plat-reconf-live; while it runs the 121 GiB server has only /// 12-13 GiB available besides the 51.5 GiB sealed archive). It is what makes a higher free-RAM target unreachable on that host. const ENGINE_FIXED_RESIDENT_BYTES: u64 = 54 * GIB; /// RAM a Windows desktop session keeps for itself (browser, IDE, Docker Desktop) when the engine shares the machine. const WINDOWS_DESKTOP_RESERVE_BYTES: u64 = 12 * GIB; /// Same in the workstation preset: the coding agent, the IDE, a browser and their tooling work next to the engine (estimate, to be replaced by a /// measured desktop of the 48 GB laptop). const WINDOWS_WORKSTATION_DESKTOP_RESERVE_BYTES: u64 = 18 * GIB; /// Hot part of the file-mapped expert bank the workstation preset plans for on Windows, instead of `min(MemTotal / 2, bank)`: the pages beyond it are /// read from disk when the desktop takes the RAM (estimate; decode speed against this value is not measured yet). const WINDOWS_WORKSTATION_WORKING_SET_GIB: u32 = 8; /// RAM the Windows workstation preset keeps available (memory-governor soft floor; the hard floor is half of it). const WINDOWS_WORKSTATION_RAM_TARGET_BYTES: u64 = 8 * GIB; const MAPPED_WORKING_SET_ENV: &str = "LELEKA_MAPPED_WORKING_SET_GIB"; /// Host memory of the file-backed engine besides its page-locked expert complement (pinned K/V, rings, pools, mapped working set; 11 GiB measured natively). const MAPPED_ENGINE_FIXED_BYTES: u64 = 11 * GIB; /// The memory governor keeps this much beyond its soft floor (`memory.reserve_mib`, 2 GiB in the server profile). const DEFAULT_RESERVE_BYTES: u64 = 2 * GIB; /// Page-locked share of the routed experts in the mapped form never needs to exceed the bank itself. const RESIDENT_BANK_GIB: u64 = 46; /// Host memory the mapped form keeps for the engine itself, the tokenizer and the working set of the page cache. const MAPPED_OVERHEAD_BYTES: u64 = 8 * GIB; /// What the mapped form still needs available to start. const MAPPED_MIN_AVAILABLE_BYTES: u64 = 10 * GIB; pub const CPU_WORKERS_ENV: &str = "LELEKA_ORIGINAL_SERVE_CPU_WORKERS"; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Preset { #[default] Dedicated, Workstation, } impl Preset { pub fn as_str(self) -> &'static str { match self { Preset::Dedicated => "dedicated", Preset::Workstation => "workstation", } } pub fn parse(text: &str) -> Result { match text { "dedicated" => Ok(Preset::Dedicated), "workstation" => Ok(Preset::Workstation), other => Err(format!( "unknown preset '{other}' (use dedicated or workstation)" )), } } } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct ResourcePlan { pub preset: Preset, pub cores: u32, /// `None` when the core count is unknown: the engine keeps its own default. pub cpu_workers: Option, pub gpu_budget_bytes: u64, /// The profile's `min_vram_free_mib`, lowered when the preset lowered the budget. pub min_vram_free_mib: Option, pub vram_free_after_mib: Option, /// Host RAM the memory governor keeps available: (soft, hard) floors in MiB, `None` = engine defaults. pub ram_floors_mib: Option<(u64, u64)>, pub ram_expected_free_after_bytes: Option, /// Windows file-backed form: GiB of experts the engine may page-lock, sized from the free RAM so that the desktop keeps its own working set /// (without it the engine takes nearly all free RAM; live native run 2026-10-25: 31 GiB resident, 14 GiB of swap, a refused start). pub resident_budget_gib: Option, /// Windows file-backed form: lower memory-governor floors in MiB (soft, hard). Windows has no OOM killer and trims its standby list under /// pressure, so the 4 GiB soft floor made for Linux only costs headroom: the engine's start check needs `fixed footprint + soft floor + reserve` /// (29.4 + 4 + 1 GiB against 34 GiB available on the 48 GB laptop, live run 2026-10-25). pub windows_floors_mib: Option<(u64, u64)>, /// Windows workstation preset: GiB of the file-mapped expert bank the engine's start check plans as hot (`LELEKA_MAPPED_WORKING_SET_GIB`). pub mapped_working_set_gib: Option, /// Host RAM cannot hold the sealed archive and the experts next to the free target: serve from SSD/HDD instead /// (archive as a read-only file, experts memory-mapped, this many GiB of them page-locked). pub mapped_resident_gib: Option, /// Shortfalls that make the preset unachievable (the preflight fails on them). pub problems: Vec, pub warnings: Vec, } fn gib_text(bytes: u64) -> String { format!("{:.1} GiB", bytes as f64 / GIB as f64) } /// The largest prompt chunk an expert cache of this GPU budget can lend to the prompt path (measured on the 3080 laptop with the pinned Qwen3.8 /// IQ3_S pack: a budget of 13 GiB holds 2,234 expert slots of 1.97 MiB, about 520 more per GiB; the loan of a chunk plus the 128-slot floor is /// 1,282 slots at 2048, 1,497 at 3072, 1,713 at 4096, 2,144 at 6144 and about 2,575 at 8192; a chunk that does not fit stops the engine from opening). /// Whole GiB, rounded down, with the margin the 1-GiB steps leave: 14+ GiB carry 8192, 13 carry 6144, 12 carry 3072, less keeps 2048. pub fn prefill_capacity_for_budget(gpu_budget_bytes: u64) -> u32 { match gpu_budget_bytes / GIB { 14.. => 8192, 13 => 6144, 12 => 3072, _ => 2048, } } /// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM. pub fn workstation_ram_target(total: u64) -> u64 { if total >= 64 * GIB { 16 * GIB } else if total >= 32 * GIB { 12 * GIB } else { 8 * GIB } } /// The host as the planner should see it when the sealed archive memfd is already resident (an inherited `--kar-fd`, or the /// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the /// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not. pub fn with_resident_archive(facts: &Facts) -> Facts { with_resident_bytes(facts, ARCHIVE_BYTES) } /// [`with_resident_archive`] for a memfd of `bytes` (a `ple_only` memfd holds about 16 GB, not 55). pub fn with_resident_bytes(facts: &Facts, bytes: u64) -> Facts { let mut facts = facts.clone(); facts.memory.available = facts.memory.available.saturating_add(bytes); facts } pub fn compute( facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset, ) -> ResourcePlan { let mut plan = ResourcePlan { preset, cores: facts.cpu_cores, cpu_workers: None, gpu_budget_bytes: profile.gpu_budget_bytes, min_vram_free_mib: profile.min_vram_free_mib, vram_free_after_mib: None, ram_floors_mib: None, ram_expected_free_after_bytes: None, mapped_resident_gib: None, resident_budget_gib: None, windows_floors_mib: None, mapped_working_set_gib: None, problems: Vec::new(), warnings: Vec::new(), }; // CPU if facts.cpu_cores > 0 { let cores = facts.cpu_cores; let leave = match preset { Preset::Dedicated => 2, Preset::Workstation if cores <= 16 => 4, Preset::Workstation => 8, }; let mut workers = cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS); // The pool's workers spin while they wait: one without a core of its own steals cycles from one that has it, so a // bigger count is slower, not just useless (docs/upstream-port-plan.md row 2.3). Where the platform reports the // physical cores (Windows), the count never exceeds every physical core but the host thread's: 7 on the 8-core // laptop instead of 12 (the workstation preset's logical-core count); the 16-core server is unchanged (15). if facts.cpu_physical_cores > 0 { workers = workers.min(facts.cpu_physical_cores.saturating_sub(1).max(1)); } plan.cpu_workers = Some(workers); if preset == Preset::Workstation && cores < leave + 1 { plan.warnings.push(format!( "only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)" )); } } // VRAM if let Some(gpu) = gpu { let budget_mib = profile.gpu_budget_bytes / MIB; if preset == Preset::Workstation { let cap_mib = (gpu .vram_free_mib .saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) / 1024) * 1024; if cap_mib < budget_mib { plan.gpu_budget_bytes = cap_mib * MIB; let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib); plan.min_vram_free_mib = Some(need); // Below half of the profile budget the expert tier and KV window shrink past what was measured. if cap_mib * 2 < budget_mib { plan.problems.push(format!( "the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)", WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib )); } } } let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0)); plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used)); } // Host RAM let ram = &facts.memory; if ram.total > 0 { let target = match preset { // Windows reclaims standby and trimmed mapped pages on its own (the engine trims its working set under pressure), so a // free-RAM target above 8 GiB only starves the prefix cache: live 48 GB run 2026-10-26, 12 GiB left it a budget of 0. Preset::Workstation if facts.os == "windows" => { workstation_ram_target(ram.total).min(WINDOWS_WORKSTATION_RAM_TARGET_BYTES) } Preset::Workstation => workstation_ram_target(ram.total), Preset::Dedicated => profile .memory .soft_floor_mib .map_or(4 * GIB, |mib| mib * MIB), }; if preset == Preset::Workstation { let soft = target / MIB; plan.ram_floors_mib = Some((soft, soft / 2)); } // The sealed memfd holds the whole archive; a file-backed archive with a resident expert bank (rtx5090-32g-file) holds only the bank and // the engine's pins, its archive pages are page cache that the kernel gives back. The mapped file form (laptop) is already the low tier. // `kar_source: none` has no archive at all (the PLE table is read from the shard through the page cache): the same footprint. let resident_file = matches!(profile.kar_source, KarSource::File | KarSource::None) && profile.expert_source == ExpertSource::Resident; if profile.kar_source == KarSource::Memfd || resident_file { let engine = if profile.expert_source == ExpertSource::Resident { ENGINE_FIXED_RESIDENT_BYTES } else { ENGINE_EXTRA_BYTES }; let footprint = if resident_file { engine } else { profile.memfd_bytes() + engine }; let after = ram.available.saturating_sub(footprint); let reserve = profile .memory .reserve_mib .map_or(DEFAULT_RESERVE_BYTES, |mib| mib * MIB); if after >= target + reserve { plan.ram_expected_free_after_bytes = Some(after); } else { // Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing. let resident = ram .available .saturating_sub(target + reserve + MAPPED_OVERHEAD_BYTES) / GIB; let resident = resident.min(RESIDENT_BANK_GIB) as u32; plan.mapped_resident_gib = Some(resident); plan.ram_expected_free_after_bytes = Some( ram.available .saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES), ); plan.warnings.push(format!( "{} of host RAM available, the pinned form needs about {} plus {} free: {} served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", gib_text(ram.available), gib_text(footprint), gib_text(target), if resident_file { "the experts are" } else { "the archive and the experts are" }, resident )); } } } if facts.os == "windows" && profile.kar_source == KarSource::File && profile.expert_source == ExpertSource::Mapped && profile.memory.resident_budget_gib.is_none() && ram.total > 0 { let workstation = preset == Preset::Workstation; let desktop = if workstation { WINDOWS_WORKSTATION_DESKTOP_RESERVE_BYTES } else { WINDOWS_DESKTOP_RESERVE_BYTES }; let engine_fixed = MAPPED_ENGINE_FIXED_BYTES; let room = ram.available.saturating_sub(desktop + engine_fixed) / GIB; plan.resident_budget_gib = Some(room.min(24) as u32); if workstation { // the workstation floors (already raised above) stay: the desktop is the point of the preset plan.mapped_working_set_gib = Some(WINDOWS_WORKSTATION_WORKING_SET_GIB); } else { plan.windows_floors_mib = Some((3072, 1536)); } plan.warnings.push(format!( "Windows: the engine may page-lock {room} GiB of experts ({} available, {} left to the desktop, {} for the engine's own pools); close heavy applications for a larger share", gib_text(ram.available), gib_text(desktop), gib_text(engine_fixed) )); } plan } /// Write the plan into the profile and the engine environment. Values the profile or the command line already set win. pub fn apply( plan: &ResourcePlan, profile: &mut Profile, engine_env: &mut BTreeMap, budget_overridden: bool, ) { if !budget_overridden { profile.gpu_budget_bytes = plan.gpu_budget_bytes; profile.min_vram_free_mib = plan.min_vram_free_mib; } if let Some((soft, hard)) = plan.ram_floors_mib { // The profile's floors are its dedicated-host values; the workstation preset only raises them. let raised = |current: Option, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted))); profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft); profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); } if let Some(resident) = plan.mapped_resident_gib { // `kar_source: none` has no archive to map: it stays none (the PLE table is read from the shard either way) if profile.kar_source != KarSource::None { profile.kar_source = KarSource::File; profile.memfd_extents = crate::profile::MemfdExtents::Full; } profile.expert_source = ExpertSource::Mapped; profile.memory.resident_budget_gib.get_or_insert(resident); profile.memory.lock = Some("off".into()); profile.memory.heal = Some(false); profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); profile.min_ram_available_bytes = profile .min_ram_available_bytes .min(MAPPED_MIN_AVAILABLE_BYTES); } if let Some(resident) = plan.resident_budget_gib { profile.memory.resident_budget_gib.get_or_insert(resident); } // The prompt chunk borrows its buffers from the expert cache, so a smaller VRAM budget (the workstation preset's, or `--gpu-budget-gib`) // that cannot hold the profile's chunk would stop the engine from starting: lower the chunk (and the grid with it) to what the budget carries. if let Some(chunk) = profile.prefill_capacity { let fits = prefill_capacity_for_budget(profile.gpu_budget_bytes); if chunk > fits { profile.prefill_capacity = Some(fits); if let Some(block) = profile.memory.prefix_cache_block && block > fits { profile.memory.prefix_cache_block = Some(fits); } } } if let Some((soft, hard)) = plan.windows_floors_mib { // only ever lowered, and only when the profile asks for more than the Windows values if profile .memory .soft_floor_mib .is_none_or(|current| current > soft) { profile.memory.soft_floor_mib = Some(soft); profile.memory.hard_floor_mib = Some(hard); } } if let Some(gib) = plan.mapped_working_set_gib && !profile.engine_env.contains_key(MAPPED_WORKING_SET_ENV) { engine_env.insert(MAPPED_WORKING_SET_ENV.to_owned(), gib.to_string()); } if let Some(workers) = plan.cpu_workers && !profile.engine_env.contains_key(CPU_WORKERS_ENV) { engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); } } impl ResourcePlan { /// The table `leleka up` prints: what the engine takes and what stays free. pub fn render(&self, facts: &Facts) -> String { let mut out = format!("resources ({} preset)\n", self.preset.as_str()); if let Some(workers) = self.cpu_workers { out.push_str(&format!( " cpu {workers} expert workers of {} cores; ~{} cores stay free\n", self.cores, self.cores.saturating_sub(workers + 1) )); } out.push_str(&format!( " vram budget {}{}\n", gib_text(self.gpu_budget_bytes), self.vram_free_after_mib .map_or(String::new(), |free| format!(", ~{} MiB stay free", free)) )); match (self.ram_floors_mib, self.ram_expected_free_after_bytes) { (Some((soft, hard)), after) => out.push_str(&format!( " host ram caches shed below {} MiB available, requests refused below {} MiB{}\n", soft, hard, after.map_or(String::new(), |b| format!( "; ~{} free after the start", gib_text(b) )) )), (None, Some(after)) => out.push_str(&format!( " host ram engine defaults; ~{} of {} free after the start\n", gib_text(after), gib_text(facts.memory.total) )), (None, None) => {} } for warning in &self.warnings { out.push_str(&format!(" warning {warning}\n")); } out } } #[cfg(test)] mod tests { use super::*; use crate::facts::Memory; use crate::profile::SPARSE_MEMFD_BYTES_ESTIMATE; fn gpu(total: u64, free: u64) -> Gpu { Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120), } } fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts { Facts { cpu_cores: cores, memory: Memory { total: ram_gib * GIB, available: avail_gib * GIB, swap_total: 0, }, ..Facts::default() } } /// The full-copy form of the server profile (the shipped profile is `ple_only`; the tests below build that explicitly). fn server() -> Profile { let mut profile = Profile::builtin("rtx5090-32g").unwrap(); profile.memfd_extents = crate::profile::MemfdExtents::Full; profile } fn laptop() -> Profile { Profile::builtin("rtx3080-16g").unwrap() } #[test] fn the_prompt_chunk_follows_what_the_gpu_budget_can_lend() { assert_eq!(prefill_capacity_for_budget(15 * GIB), 8192); assert_eq!(prefill_capacity_for_budget(14 * GIB), 8192); assert_eq!(prefill_capacity_for_budget(13 * GIB), 6144); assert_eq!(prefill_capacity_for_budget(13 * GIB + 900 * MIB), 6144); assert_eq!(prefill_capacity_for_budget(12 * GIB), 3072); assert_eq!(prefill_capacity_for_budget(10 * GIB), 2048); // the laptop profile ships 6144 / 6144: it stays at the workstation preset's 13 GiB budget, goes down on a smaller one and is // never raised; the server profile (32,819,404,800 B, 30 whole GiB here) keeps its 8192 let apply_with = |budget_gib: u64| { let mut profile = laptop(); let mut env = BTreeMap::new(); let plan = compute( &host(16, 48, 36), Some(&gpu(16384, 16384)), &profile, Preset::Dedicated, ); profile.gpu_budget_bytes = budget_gib * GIB; apply(&plan, &mut profile, &mut env, true); (profile.prefill_capacity, profile.memory.prefix_cache_block) }; assert_eq!(apply_with(13), (Some(6144), Some(6144))); assert_eq!(apply_with(15), (Some(6144), Some(6144))); assert_eq!(apply_with(12), (Some(3072), Some(3072))); assert_eq!(apply_with(10), (Some(2048), Some(2048))); let mut server = server(); let plan = compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &server, Preset::Dedicated, ); apply(&plan, &mut server, &mut BTreeMap::new(), false); assert_eq!(server.prefill_capacity, Some(8192)); } #[test] fn workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known() { let mut laptop_host = host(16, 48, 36); laptop_host.cpu_physical_cores = 8; assert_eq!( compute(&laptop_host, None, &laptop(), Preset::Workstation).cpu_workers, Some(7), "8c/16t: 12 workers would put 5 of them on SMT siblings" ); assert_eq!( compute(&host(16, 48, 36), None, &laptop(), Preset::Workstation).cpu_workers, Some(12), "physical cores unknown: unchanged" ); let mut server_host = host(32, 121, 100); server_host.cpu_physical_cores = 16; assert_eq!( compute( &server_host, Some(&gpu(32607, 32100)), &server(), Preset::Dedicated ) .cpu_workers, Some(15), "the 16-core server is unchanged" ); let mut small = host(2, 16, 8); small.cpu_physical_cores = 1; assert_eq!( compute(&small, None, &laptop(), Preset::Dedicated).cpu_workers, Some(1) ); } #[test] fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() { let plan = compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated, ); assert_eq!(plan.cpu_workers, Some(15)); assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes); assert_eq!(plan.ram_floors_mib, None); assert!(plan.problems.is_empty()); } #[test] fn workstation_leaves_cores_ram_and_vram_on_the_server() { let plan = compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation, ); assert_eq!( plan.cpu_workers, Some(15), "32 cores - 8 left free = 24, capped at the pool's 15" ); assert_eq!( plan.gpu_budget_bytes, 29 * GIB, "32100 MiB free - 2048 MiB, rounded down to GiB" ); assert_eq!(plan.ram_floors_mib, Some((16384, 8192))); assert!(plan.problems.is_empty(), "{:?}", plan.problems); let mut profile = server(); let mut env = BTreeMap::new(); apply(&plan, &mut profile, &mut env, false); assert_eq!(profile.gpu_budget_bytes, 29 * GIB); assert_eq!(profile.memory.soft_floor_mib, Some(16384)); assert_eq!(profile.memory.hard_floor_mib, Some(8192)); assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("15")); } #[test] fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() { let plan = compute( &host(16, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation, ); assert_eq!(plan.cpu_workers, Some(12), "16 threads - 4 left free"); assert_eq!(plan.ram_floors_mib, Some((8192, 4096))); assert_eq!(plan.gpu_budget_bytes, 13 * GIB); assert!(plan.problems.is_empty(), "{:?}", plan.problems); let small = compute( &host(8, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation, ); assert_eq!(small.cpu_workers, Some(4)); } #[test] fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() { let plan = compute( &host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Workstation, ); assert!(!plan.problems.is_empty()); let dedicated = compute( &host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Dedicated, ); assert!(dedicated.problems.is_empty()); } #[test] fn explicit_values_win_and_floors_are_only_raised() { let plan = compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation, ); let mut profile = server(); profile.memory.soft_floor_mib = Some(30000); profile .engine_env .insert(CPU_WORKERS_ENV.into(), "3".into()); let mut env = BTreeMap::new(); apply(&plan, &mut profile, &mut env, true); assert_eq!( profile.gpu_budget_bytes, server().gpu_budget_bytes, "--gpu-budget-gib wins" ); assert_eq!(profile.memory.soft_floor_mib, Some(30000)); assert_eq!( profile.memory.hard_floor_mib, Some(8192), "floors are only ever raised" ); assert!(env.is_empty()); } #[test] fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credited_by_its_own_size() { // 80 GiB available at start: the full pinned form (55.3 GB memfd + the engine's 54 GiB) does not fit next to the 4 GiB target and // the 2 GiB reserve and is sent to the mapped form; with a 16 GB memfd it does let facts = host(32, 121, 80); let gpu = gpu(32607, 32100); let full = compute(&facts, Some(&gpu), &server(), Preset::Dedicated); assert!(full.mapped_resident_gib.is_some(), "{:?}", full.warnings); let mut sparse = server(); sparse.memfd_extents = crate::profile::MemfdExtents::PleOnly; let plan = compute(&facts, Some(&gpu), &sparse, Preset::Dedicated); assert_eq!(plan.mapped_resident_gib, None, "{:?}", plan.warnings); assert_eq!( plan.ram_expected_free_after_bytes, Some(80 * GIB - (SPARSE_MEMFD_BYTES_ESTIMATE + ENGINE_FIXED_RESIDENT_BYTES)), "the footprint is the sparse memfd plus the engine's own memory" ); // a resident sparse memfd is credited with its own size, not the archive's let resident = host(32, 121, 66); let credited = with_resident_bytes(&resident, sparse.memfd_bytes()); assert_eq!( credited.memory.available, 66 * GIB + SPARSE_MEMFD_BYTES_ESTIMATE ); assert_eq!( with_resident_archive(&resident).memory.available, 66 * GIB + ARCHIVE_BYTES ); // a plan that falls back to the mapped form is a different machine: the sparse switch is dropped with the memfd let tiny = host(32, 121, 2); let mut profile = sparse.clone(); let fallback = compute(&tiny, Some(&gpu), &profile, Preset::Dedicated); assert!(fallback.mapped_resident_gib.is_some()); apply(&fallback, &mut profile, &mut BTreeMap::new(), false); assert_eq!( (profile.kar_source, profile.memfd_extents), (KarSource::File, crate::profile::MemfdExtents::Full) ); profile.validate().unwrap(); } #[test] fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() { // the server with the 51.5 GiB memfd already resident: 121 GiB total, 66 GiB available (what the supervisor sees before the engine starts) let resident = host(32, 121, 66); let charged_twice = compute( &resident, Some(&gpu(32607, 32100)), &server(), Preset::Dedicated, ); assert!( charged_twice.mapped_resident_gib.is_some(), "without the correction the pinned form looks impossible" ); let corrected = compute( &with_resident_archive(&resident), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated, ); assert_eq!( corrected.mapped_resident_gib, None, "the archive is already paid for: the engine's 54 GiB fit next to the 4 GiB target and the 2 GiB reserve" ); assert!(corrected.ram_expected_free_after_bytes.is_some()); // a host that really lacks the engine's own memory is still sent to the mapped form let tiny = host(32, 121, 2); assert!( compute( &with_resident_archive(&tiny), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated ) .mapped_resident_gib .is_some() ); // saturating, not wrapping assert!( with_resident_archive(&host(1, 1, u64::MAX / GIB)) .memory .available >= u64::MAX / 2 ); } #[test] fn the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archive() { let file = Profile::builtin("rtx5090-32g-file").unwrap(); assert_eq!( (file.kar_source, file.expert_source), (KarSource::File, ExpertSource::Resident) ); // 121 GiB host with 100 GiB available and no holder: the 54 GiB of the engine fit; the 55 GB archive is page cache, not a charge let plan = compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &file, Preset::Dedicated, ); assert_eq!(plan.mapped_resident_gib, None); assert_eq!(plan.ram_expected_free_after_bytes, Some(46 * GIB)); // the same host is already too small for the memfd profile once it has to create the archive copy assert!( compute( &host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated ) .mapped_resident_gib .is_some() ); // a host that cannot hold the bank is sent to the mapped form, and the warning does not claim the archive moves let small = host(32, 64, 50); let plan = compute(&small, Some(&gpu(32607, 32100)), &file, Preset::Dedicated); assert!(plan.mapped_resident_gib.is_some()); assert!( plan.warnings[0].contains("the experts are served from disk") && !plan.warnings[0].contains("the archive and"), "{:?}", plan.warnings ); let mut applied = file.clone(); apply(&plan, &mut applied, &mut BTreeMap::new(), false); assert_eq!( (applied.kar_source, applied.expert_source), (KarSource::File, ExpertSource::Mapped) ); applied.validate().unwrap(); } #[test] fn unknown_core_count_leaves_the_engine_default() { let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); assert_eq!(plan.cpu_workers, None); } #[test] fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() { // 121 GiB host with 70 GiB available: archive and resident experts (105.5 GiB) do not fit at all let plan = compute( &host(32, 121, 70), Some(&gpu(32607, 32100)), &server(), Preset::Workstation, ); assert_eq!( plan.mapped_resident_gib, Some(44), "70 - 16 target - 2 reserve - 8 overhead" ); assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); assert!(plan.render(&host(32, 121, 70)).contains("served from disk")); let mut profile = server(); let mut env = BTreeMap::new(); apply(&plan, &mut profile, &mut env, false); assert_eq!(profile.kar_source, KarSource::File); assert_eq!(profile.expert_source, ExpertSource::Mapped); assert_eq!(profile.memory.resident_budget_gib, Some(44)); assert_eq!(profile.memory.lock.as_deref(), Some("off")); assert!( profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB ); profile.validate().unwrap(); } #[test] fn the_low_ram_fallback_keeps_a_profile_without_an_archive_without_one() { let plan = compute( &host(32, 121, 70), Some(&gpu(32607, 32100)), &Profile::builtin("rtx5090-32g-gguf-ple").unwrap(), Preset::Workstation, ); assert!(plan.mapped_resident_gib.is_some(), "{plan:?}"); let mut profile = Profile::builtin("rtx5090-32g-gguf-ple").unwrap(); apply(&plan, &mut profile, &mut BTreeMap::new(), false); assert_eq!(profile.kar_source, KarSource::None); assert_eq!(profile.expert_source, ExpertSource::Mapped); profile.validate().unwrap(); } #[test] fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() { let plan = compute( &host(16, 24, 12), Some(&gpu(16384, 15500)), &server(), Preset::Dedicated, ); assert_eq!( plan.mapped_resident_gib, Some(0), "12 GiB available is below the 4 GiB target plus 8 GiB overhead" ); let ample = compute( &host(64, 256, 240), Some(&gpu(32607, 32100)), &server(), Preset::Workstation, ); assert_eq!(ample.mapped_resident_gib, None); assert!(ample.warnings.is_empty(), "{:?}", ample.warnings); } #[test] fn the_windows_file_backed_form_sizes_its_page_locked_experts_from_the_free_ram() { let mut windows = host(16, 48, 34); windows.os = "windows".into(); let plan = compute( &windows, Some(&gpu(16384, 16175)), &laptop(), Preset::Dedicated, ); assert_eq!( plan.resident_budget_gib, Some(11), "34 GiB free - 12 for the desktop - 11 for the engine's pools" ); let mut profile = laptop(); let mut env = BTreeMap::new(); apply(&plan, &mut profile, &mut env, false); assert_eq!(profile.memory.resident_budget_gib, Some(11)); assert_eq!( (profile.memory.soft_floor_mib, profile.memory.hard_floor_mib), (Some(3072), Some(1536)), "Windows lowers the Linux floors of the laptop profile" ); // an explicit profile value wins, and Linux hosts are left alone let mut explicit = laptop(); explicit.memory.resident_budget_gib = Some(16); assert_eq!( compute(&windows, None, &explicit, Preset::Dedicated).resident_budget_gib, None ); assert_eq!( compute(&host(16, 48, 34), None, &laptop(), Preset::Dedicated).resident_budget_gib, None ); // a squeezed machine gets zero, not an underflow let mut squeezed = host(16, 48, 6); squeezed.os = "windows".into(); assert_eq!( compute(&squeezed, None, &laptop(), Preset::Dedicated).resident_budget_gib, Some(0) ); } #[test] fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors() { let mut windows = host(16, 48, 34); windows.os = "windows".into(); let plan = compute( &windows, Some(&gpu(16384, 16175)), &laptop(), Preset::Workstation, ); assert_eq!( plan.resident_budget_gib, Some(5), "34 GiB free - 18 for the agent, IDE and browser - 11 for the engine's pools" ); assert_eq!( plan.windows_floors_mib, None, "the workstation floors are not lowered to the dedicated Windows values" ); assert_eq!(plan.mapped_working_set_gib, Some(8)); let mut profile = laptop(); let mut env = BTreeMap::new(); apply(&plan, &mut profile, &mut env, false); assert_eq!( profile.memory.soft_floor_mib, Some(8 * 1024), "Windows workstation keeps 8 GiB available (12 GiB left the prefix cache no budget)" ); assert_eq!(profile.memory.hard_floor_mib, Some(4 * 1024)); assert_eq!( env.get(MAPPED_WORKING_SET_ENV).map(String::as_str), Some("8") ); // the dedicated preset on the same host is unchanged let dedicated = compute(&windows, None, &laptop(), Preset::Dedicated); assert_eq!( ( dedicated.resident_budget_gib, dedicated.mapped_working_set_gib ), (Some(11), None) ); } #[test] fn presets_parse_and_default_to_dedicated() { assert_eq!(Preset::default(), Preset::Dedicated); assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation); assert!(Preset::parse("x").is_err()); } }